@phren/cli 0.1.34 → 0.1.36

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/hooks.d.ts CHANGED
@@ -5,6 +5,15 @@ export interface HookError {
5
5
  }
6
6
  export declare function commandExists(cmd: string): boolean;
7
7
  export declare function detectInstalledTools(): Set<string>;
8
+ /**
9
+ * True if a path lives inside an ephemeral npx download cache
10
+ * (`~/.npm/_npx/<hash>/…`). Baking such a path into a hook command that has no
11
+ * self-healing fallback is fragile: npx prunes that cache and the `<hash>`
12
+ * segment changes between versions, silently breaking every phren hook. Hook
13
+ * commands that resolve here must fall back to `npx -y <spec>` (which
14
+ * re-resolves on every run) or the ~/.local/bin/phren wrapper instead.
15
+ */
16
+ export declare function isEphemeralNpxPath(p: string): boolean;
8
17
  /** Shell-escape a value by wrapping in single quotes with proper escaping of embedded single quotes. */
9
18
  export declare function shellEscape(s: string): string;
10
19
  export interface LifecycleCommands {
package/dist/hooks.js CHANGED
@@ -65,6 +65,17 @@ function resolveCliEntryScript() {
65
65
  const local = path.join(path.dirname(fileURLToPath(import.meta.url)), "index.js");
66
66
  return fs.existsSync(local) ? local : null;
67
67
  }
68
+ /**
69
+ * True if a path lives inside an ephemeral npx download cache
70
+ * (`~/.npm/_npx/<hash>/…`). Baking such a path into a hook command that has no
71
+ * self-healing fallback is fragile: npx prunes that cache and the `<hash>`
72
+ * segment changes between versions, silently breaking every phren hook. Hook
73
+ * commands that resolve here must fall back to `npx -y <spec>` (which
74
+ * re-resolves on every run) or the ~/.local/bin/phren wrapper instead.
75
+ */
76
+ export function isEphemeralNpxPath(p) {
77
+ return /(^|[/\\])_npx[/\\]/.test(p);
78
+ }
68
79
  function phrenPackageSpec() {
69
80
  return PACKAGE_SPEC;
70
81
  }
@@ -82,7 +93,12 @@ function buildPackageLifecycleCommands() {
82
93
  };
83
94
  }
84
95
  export function buildLifecycleCommands(phrenPath, options = {}) {
85
- const entry = resolveCliEntryScript();
96
+ const rawEntry = resolveCliEntryScript();
97
+ // A bare `node <entry>` hook has no fallback if <entry> disappears. When the
98
+ // package is running from the npx cache, that entry path is ephemeral, so we
99
+ // drop it here and let resolution fall through to the ~/.local/bin/phren
100
+ // wrapper (preferred) or the self-healing `npx -y <spec>` last resort.
101
+ const entry = rawEntry && !isEphemeralNpxPath(rawEntry) ? rawEntry : null;
86
102
  const nativeWindows = process.platform === "win32" && !options.forcePosix;
87
103
  const escapedPhren = phrenPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
88
104
  const quotedPhren = shellEscape(phrenPath);
package/dist/index.js CHANGED
@@ -1,30 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
2
  import * as fs from "fs";
5
3
  import * as path from "path";
6
4
  import { findPhrenPathWithArg, debugLog, runtimeDir, } from "./shared.js";
7
5
  import { log as structuredLog, logger } from "./logger.js";
8
- import { buildIndex, flushEmbeddingQueue, updateFileInIndex as updateFileInIndexFn, } from "./shared/index.js";
9
- import { runCustomHooks } from "./hooks.js";
10
- import { register as registerSearch } from "./tools/search.js";
11
- import { register as registerTask } from "./tools/tasks.js";
12
- import { register as registerFinding } from "./tools/finding.js";
13
- import { register as registerMemory } from "./tools/memory.js";
14
- import { register as registerData } from "./tools/data.js";
15
- import { register as registerGraph } from "./tools/graph.js";
16
- import { register as registerSession } from "./tools/session.js";
17
- import { register as registerOps } from "./tools/ops.js";
18
- import { register as registerSkills } from "./tools/skills.js";
19
- import { register as registerHooks } from "./tools/hooks.js";
20
- import { register as registerExtract } from "./tools/extract.js";
21
- import { register as registerConfig } from "./tools/config.js";
22
- import { mcpResponse } from "./tools/types.js";
23
6
  import { errorMessage } from "./utils.js";
24
7
  import { printIntegratedHelp, printIntegratedVersion, resolveTopLevelInvocation, runTopLevelCommand, } from "./entrypoint.js";
25
- import { startEmbeddingWarmup } from "./startup-embedding.js";
26
- import { resolveRuntimeProfile } from "./runtime-profile.js";
27
- import { VERSION as PACKAGE_VERSION } from "./package-metadata.js";
8
+ // NOTE: the MCP-server-only module graph (MCP SDK, FTS indexer, tool registries,
9
+ // startup-embedding, custom-hook engine) is intentionally NOT imported here. It is
10
+ // dynamically imported inside main() so that top-level commands — hook-prompt,
11
+ // --version, --help — which never reach main() do not pay its ~1.8s cold-start cost.
12
+ // This matters most for the PostToolUse `hook-tool`, which spawns per tool call.
28
13
  const invocation = resolveTopLevelInvocation(process.argv.slice(2));
29
14
  if (invocation.kind === "help") {
30
15
  printIntegratedHelp();
@@ -70,6 +55,19 @@ function cleanStaleLocks(phrenPath) {
70
55
  }
71
56
  }
72
57
  async function main() {
58
+ // Lazy-load the MCP-server-only module graph. Only the long-lived MCP server
59
+ // reaches main(), so paying the import cost here — not at module scope — keeps
60
+ // every hook subprocess fast (hook-prompt, hook-tool, --version never get here).
61
+ const [{ McpServer }, { StdioServerTransport }, { buildIndex, flushEmbeddingQueue, updateFileInIndex: updateFileInIndexFn }, { runCustomHooks }, { mcpResponse }, { startEmbeddingWarmup }, { resolveRuntimeProfile }, { VERSION: PACKAGE_VERSION },] = await Promise.all([
62
+ import("@modelcontextprotocol/sdk/server/mcp.js"),
63
+ import("@modelcontextprotocol/sdk/server/stdio.js"),
64
+ import("./shared/index.js"),
65
+ import("./hooks.js"),
66
+ import("./tools/types.js"),
67
+ import("./startup-embedding.js"),
68
+ import("./runtime-profile.js"),
69
+ import("./package-metadata.js"),
70
+ ]);
73
71
  const profile = resolveRuntimeProfile(phrenPath);
74
72
  cleanStaleLocks(phrenPath);
75
73
  let db = null;
@@ -239,18 +237,24 @@ async function main() {
239
237
  updateFileInIndexFn(db, filePath, phrenPath);
240
238
  },
241
239
  };
242
- registerSearch(server, ctx);
243
- registerTask(server, ctx);
244
- registerFinding(server, ctx);
245
- registerMemory(server, ctx);
246
- registerData(server, ctx);
247
- registerGraph(server, ctx);
248
- registerSession(server, ctx);
249
- registerOps(server, ctx);
250
- registerSkills(server, ctx);
251
- registerHooks(server, ctx);
252
- registerExtract(server, ctx);
253
- registerConfig(server, ctx);
240
+ // Lazy-imported tool registries — only the MCP server needs them. Registration
241
+ // order is irrelevant (each module registers a disjoint set of tools).
242
+ const toolModules = await Promise.all([
243
+ import("./tools/search.js"),
244
+ import("./tools/tasks.js"),
245
+ import("./tools/finding.js"),
246
+ import("./tools/memory.js"),
247
+ import("./tools/data.js"),
248
+ import("./tools/graph.js"),
249
+ import("./tools/session.js"),
250
+ import("./tools/ops.js"),
251
+ import("./tools/skills.js"),
252
+ import("./tools/hooks.js"),
253
+ import("./tools/extract.js"),
254
+ import("./tools/config.js"),
255
+ ]);
256
+ for (const mod of toolModules)
257
+ mod.register(server, ctx);
254
258
  const transport = new StdioServerTransport();
255
259
  await server.connect(transport);
256
260
  console.error(`phren-mcp running (${phrenPath})`);
@@ -305,11 +305,11 @@ export function configureClaude(phrenPath, opts = {}) {
305
305
  upsertPhrenHook("UserPromptSubmit", {
306
306
  type: "command",
307
307
  command: lifecycle.userPromptSubmit || `node "${entryScript}" hook-prompt`,
308
- timeout: 3,
308
+ timeout: 10,
309
309
  });
310
310
  // Mirror pre-prompt custom hooks into Claude's settings.json as
311
311
  // peer UserPromptSubmit entries so they run in parallel with phren
312
- // and don't share its 3-second timeout budget. See
312
+ // and don't share its timeout budget. See
313
313
  // upsertCustomPrePromptSiblings docstring for details.
314
314
  try {
315
315
  upsertCustomPrePromptSiblings(hooksMap, phrenPath);
@@ -20,6 +20,19 @@ import { log } from "./shared.js";
20
20
  * @param verb - label used in log messages, e.g. "Updated" or "Configured"
21
21
  */
22
22
  export function configureMcpTargets(phrenPath, opts, verb = "Configured") {
23
+ // Install the stable ~/.local/bin/phren wrapper BEFORE writing any hook
24
+ // commands. buildLifecycleCommands prefers that wrapper (it carries an npx
25
+ // fallback, so it survives nvm switches and npx cache clears); if it doesn't
26
+ // yet exist, hook commands fall through to the ephemeral npx-cache entry path
27
+ // and break the next time npx prunes its cache. configureHooksIfEnabled runs
28
+ // later and re-installs the wrapper idempotently, emitting the user-facing
29
+ // "CLI wrapper" line — this early install is intentionally silent.
30
+ try {
31
+ installPhrenCliWrapper(phrenPath);
32
+ }
33
+ catch (err) {
34
+ debugLog(`configureMcpTargets: early wrapper install failed: ${errorMessage(err)}`);
35
+ }
23
36
  let claudeStatus = "no_settings";
24
37
  try {
25
38
  const status = configureClaude(phrenPath, { mcpEnabled: opts.mcpEnabled, hooksEnabled: opts.hooksEnabled });
@@ -8,7 +8,7 @@ import { validateGovernanceJson } from "../shared/governance.js";
8
8
  import { errorMessage } from "../utils.js";
9
9
  import { buildIndex, queryRows } from "../shared/index.js";
10
10
  import { validateTaskFormat, validateFindingsFormat } from "../shared/content.js";
11
- import { detectInstalledTools } from "../hooks.js";
11
+ import { detectInstalledTools, isEphemeralNpxPath } from "../hooks.js";
12
12
  import { validateSkillFrontmatter, validateSkillsDir } from "./skills.js";
13
13
  import { verifyFileChecksums, updateFileChecksums } from "./checksums.js";
14
14
  import { buildSkillManifest } from "../skill/registry.js";
@@ -329,6 +329,7 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
329
329
  });
330
330
  let hookOk = false;
331
331
  let lifecycleOk = false;
332
+ let hooksEphemeral = false;
332
333
  try {
333
334
  const cfg = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
334
335
  const hooks = cfg?.hooks || {};
@@ -339,6 +340,11 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
339
340
  const stopHookOk = stopHooks.includes("hook-stop");
340
341
  const startHookOk = startHooks.includes("hook-session-start");
341
342
  lifecycleOk = stopHookOk && startHookOk;
343
+ // A hook command that points into the npx cache (~/.npm/_npx/<hash>/…)
344
+ // works until npx prunes that cache, then breaks silently. Flag it so a
345
+ // re-init (which now resolves to the stable ~/.local/bin/phren wrapper)
346
+ // can repair it before the user notices context has stopped flowing.
347
+ hooksEphemeral = [promptHooks, stopHooks, startHooks].some(isEphemeralNpxPath);
342
348
  }
343
349
  catch (err) {
344
350
  debugLog(`doctor: failed to read Claude settings for hook check: ${errorMessage(err)}`);
@@ -357,6 +363,13 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
357
363
  ? "session-start + stop lifecycle hooks configured"
358
364
  : "missing lifecycle hooks (expected hook-session-start and hook-stop)",
359
365
  });
366
+ checks.push({
367
+ name: "hook-path-stable",
368
+ ok: !hooksEphemeral,
369
+ detail: hooksEphemeral
370
+ ? "hook commands point into the ephemeral npx cache (~/.npm/_npx/…); re-run `npx @phren/cli init` to repoint at the stable ~/.local/bin/phren wrapper"
371
+ : "hook commands use a stable entrypoint",
372
+ });
360
373
  const runtimeHealthPath = runtimeHealthFile(phrenPath);
361
374
  let runtime = null;
362
375
  if (fs.existsSync(runtimeHealthPath)) {
@@ -269,7 +269,7 @@ hooks:
269
269
  - hooks:
270
270
  - type: command
271
271
  command: "${promptCmd}"
272
- timeout: 3
272
+ timeout: 10
273
273
  Stop:
274
274
  - hooks:
275
275
  - type: command
package/dist/logger.js CHANGED
@@ -1,13 +1,32 @@
1
1
  import * as fs from "fs";
2
2
  import { runtimeFile, findPhrenPath } from "./shared.js";
3
3
  let _cachedPhrenPath;
4
+ const LOG_MAX_BYTES = 5_000_000; // rotate debug.log past ~5MB
5
+ const LOG_KEEP_LINES = 2000; // keep the most recent lines on rotation
6
+ /** Truncate debug.log to its last LOG_KEEP_LINES if it has grown past the cap. */
7
+ function rotateIfLarge(logPath) {
8
+ try {
9
+ if (fs.statSync(logPath).size <= LOG_MAX_BYTES)
10
+ return;
11
+ const lines = fs.readFileSync(logPath, "utf-8").split("\n");
12
+ fs.writeFileSync(logPath, lines.slice(-LOG_KEEP_LINES).join("\n"));
13
+ }
14
+ catch {
15
+ // statSync ENOENT (no file yet) or any IO error — nothing to rotate
16
+ }
17
+ }
4
18
  export function log(level, tool, message, extra) {
5
19
  try {
20
+ // debug-level logging is opt-in (matches debugLog). It was the bulk of the
21
+ // 30MB debug.log — mostly expected-ENOENT noise logged on the normal path.
22
+ if (level === "debug" && !process.env.PHREN_DEBUG)
23
+ return;
6
24
  if (_cachedPhrenPath === undefined)
7
25
  _cachedPhrenPath = findPhrenPath();
8
26
  if (!_cachedPhrenPath)
9
27
  return;
10
28
  const logPath = runtimeFile(_cachedPhrenPath, "debug.log");
29
+ rotateIfLarge(logPath);
11
30
  const line = JSON.stringify({ ts: new Date().toISOString(), level, tool, message, ...extra });
12
31
  fs.appendFileSync(logPath, line + "\n");
13
32
  }