@phren/cli 0.1.27 → 0.1.28

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,4 +1,3 @@
1
- export declare const CLI_COMMANDS: string[];
2
1
  export type TopLevelInvocation = {
3
2
  kind: "manage";
4
3
  argv: string[];
@@ -1,198 +1,12 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
- import { parseMcpMode, runInit } from "./init/init.js";
4
3
  import { errorMessage } from "./utils.js";
5
4
  import { logger } from "./logger.js";
6
- import { defaultPhrenPath, expandHomePath, findPhrenPath, readRootManifest } from "./shared.js";
5
+ import { defaultPhrenPath, expandHomePath, getPhrenPath, readRootManifest, } from "./shared.js";
6
+ import { resolveRuntimeProfile } from "./runtime-profile.js";
7
7
  import { VERSION } from "./package-metadata.js";
8
- import { addProjectFromPath } from "./core/project.js";
9
- import { PROJECT_OWNERSHIP_MODES, getProjectOwnershipDefault, parseProjectOwnershipMode, } from "./project-config.js";
10
- const HELP_TEXT = `phren - persistent memory for AI agents
11
-
12
- phren Interactive memory shell
13
- phren init Set up phren
14
- phren quickstart Quick setup: init + project scaffold
15
- phren add [path] Register a project
16
- phren search <query> Search what phren knows
17
- phren status Health check
18
- phren doctor [--fix] Diagnose and repair
19
- phren web-ui Open the knowledge graph
20
- phren tasks Cross-project task view
21
- phren graph Fragment knowledge graph
22
- phren shell Interactive memory shell
23
-
24
- phren manage <command> Alias for the top-level commands above
25
- phren mem <command> Alias for \`phren manage\`
26
-
27
- Legacy shortcuts still work:
28
- phren init, phren search, phren task, phren config, ...
29
-
30
- phren help <topic> Detailed help
31
- Topics: projects, skills, hooks, config, maintain, setup, stores, team, env, all
32
- `;
33
- const INTEGRATED_HELP_TEXT = HELP_TEXT;
34
- const HELP_TOPICS = {
35
- projects: `Projects:
36
- phren add [path] [--ownership <mode>] Register a project
37
- phren projects list List all tracked projects
38
- phren projects configure <name> [--ownership <mode>] [--hooks on|off]
39
- Update per-project settings
40
- phren projects remove <name> Remove a project
41
- `,
42
- skills: `Skills:
43
- phren skills list List installed skills
44
- phren skills add <project> <path> Link a skill into a project
45
- phren skills show <name> Show skill content
46
- phren skills resolve <project|global> Print resolved skill manifest
47
- phren skills doctor <project|global> Diagnose skill visibility
48
- phren skills sync <project|global> Regenerate skill mirror
49
- phren skills enable <project|global> <name> Enable a disabled skill
50
- phren skills disable <project|global> <name> Disable a skill without deleting
51
- phren skills remove <project> <name> Remove a skill
52
- phren detect-skills [--import] Find untracked skills in ~/.claude/skills/
53
- `,
54
- hooks: `Hooks:
55
- phren hooks list [--project <name>] Show hook status per tool
56
- phren hooks enable <tool> Enable hooks for a tool
57
- phren hooks disable <tool> Disable hooks for a tool
58
- phren hooks add-custom <event> <cmd> Add a custom hook
59
- phren hooks remove-custom <event> Remove custom hooks
60
- phren hooks errors [--limit <n>] Show recent hook errors
61
- `,
62
- config: `Configuration:
63
- phren config show [--project <name>] Show current config
64
- phren config policy [get|set ...] Retention, TTL, confidence, decay
65
- phren config workflow [get|set ...] Risky-memory thresholds
66
- phren config proactivity [level] Set proactivity level
67
- phren config task-mode [mode] Set task automation mode
68
- phren config finding-sensitivity [lvl] Set finding capture sensitivity
69
- phren config index [get|set ...] Indexer include/exclude globs
70
- phren config synonyms [list|add|remove] Manage learned synonyms
71
- phren config project-ownership [mode] Default ownership for new projects
72
- phren config machines Registered machines
73
- phren config profiles Profiles and projects
74
- phren config telemetry [on|off] Opt-in usage telemetry
75
-
76
- All config subcommands accept --project <name> for per-project overrides.
77
- `,
78
- maintain: `Maintenance:
79
- phren maintain govern [project] Queue stale memories for review
80
- phren maintain prune [project] Delete expired entries
81
- phren maintain consolidate [project] Deduplicate findings
82
- phren maintain extract [project] Mine git/GitHub signals
83
- `,
84
- setup: `Setup:
85
- phren init [--mode shared|project-local] [--machine <n>] [--profile <n>] [--dry-run] [-y]
86
- phren quickstart Quick setup: init + project scaffold
87
- phren mcp-mode [on|off|status] Toggle MCP integration
88
- phren hooks-mode [on|off|status] Toggle hook execution
89
- phren verify Check init completed OK
90
- phren uninstall Remove phren config and hooks
91
- phren update [--refresh-starter] Update to latest version
92
- `,
93
- stores: `Stores:
94
- phren store list List registered stores
95
- phren store add <name> --remote <url> Add a team store
96
- phren store remove <name> Remove a store (local only)
97
- phren store sync Pull all stores
98
- `,
99
- team: `Team:
100
- phren team init <name> [--remote <url>] Create a new team store
101
- phren team join <git-url> [--name <name>] Join an existing team store
102
- phren team add-project <store> <project> Add a project to a team store
103
- phren team list List team stores
104
- `,
105
- env: `Environment variables:
106
- PHREN_PATH Override phren directory (default: ~/.phren)
107
- PHREN_PROFILE Active profile name
108
- PHREN_DEBUG Enable debug logging (set to 1)
109
-
110
- Embeddings:
111
- PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)
112
- PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint
113
- PHREN_EMBEDDING_API_KEY API key for embedding endpoint
114
- PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)
115
-
116
- Context injection:
117
- PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)
118
- PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)
119
- PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)
120
-
121
- Feature flags:
122
- PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction
123
- PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations
124
- PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding
125
- PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback
126
-
127
- Run 'phren help all' to see everything.
128
- `,
129
- };
130
- function buildFullHelp() {
131
- return `phren - persistent knowledge for your agents
132
-
133
- Usage:
134
- phren Interactive shell
135
- phren init Set up phren
136
- phren quickstart Quick setup: init + project scaffold
137
- phren add [path] Register a project
138
- phren search <query> Search what phren knows
139
- phren status Health check
140
- phren doctor [--fix] Diagnose and repair
141
- phren web-ui Open the knowledge graph
142
- phren tasks Cross-project task view
143
- phren graph Fragment knowledge graph
144
- phren add-finding <p> "." Tell phren what you learned
145
- phren pin <p> "..." Save a truth
146
- phren review [project] Show review queue
147
- phren session-context Current session state
148
-
149
- ${Object.values(HELP_TOPICS).join("\n")}`;
150
- }
151
- export const CLI_COMMANDS = [
152
- "search",
153
- "shell",
154
- "update",
155
- "config",
156
- "maintain",
157
- "hook-prompt",
158
- "hook-session-start",
159
- "hook-stop",
160
- "hook-context",
161
- "hook-tool",
162
- "add-finding",
163
- "pin",
164
- "doctor",
165
- "debug-injection",
166
- "inspect-index",
167
- "web-ui",
168
- "quality-feedback",
169
- "skill-list",
170
- "skills",
171
- "hooks",
172
- "detect-skills",
173
- "task",
174
- "tasks",
175
- "finding",
176
- "quickstart",
177
- "background-maintenance",
178
- "background-sync",
179
- "projects",
180
- "extract-memories",
181
- "govern-memories",
182
- "prune-memories",
183
- "consolidate-memories",
184
- "index-policy",
185
- "policy",
186
- "workflow",
187
- "access",
188
- "review",
189
- "consolidation-status",
190
- "session-context",
191
- "truths",
192
- "store",
193
- "team",
194
- "promote",
195
- ];
8
+ import { TOPIC_ORDER, helpTopicNames, lookupCommand, } from "./cli-registry.js";
9
+ import { formatCheatSheet, formatCommand, formatDocTopic, formatFullHelp, formatTopic, } from "./cli-help.js";
196
10
  function looksLikePhrenRootArg(arg) {
197
11
  if (!arg || arg.startsWith("-"))
198
12
  return false;
@@ -231,7 +45,7 @@ export function resolveTopLevelInvocation(argv) {
231
45
  return { kind: "manage", argv };
232
46
  }
233
47
  export function printIntegratedHelp() {
234
- console.log(INTEGRATED_HELP_TEXT);
48
+ console.log(formatCheatSheet());
235
49
  }
236
50
  export function printIntegratedVersion() {
237
51
  console.log(`phren v${VERSION}`);
@@ -248,258 +62,98 @@ async function finish(exitCode) {
248
62
  await flushTopLevelOutput();
249
63
  return true;
250
64
  }
251
- function getOptionValue(args, name) {
252
- const exactIdx = args.indexOf(name);
253
- if (exactIdx !== -1)
254
- return args[exactIdx + 1];
255
- const prefixed = args.find((arg) => arg.startsWith(`${name}=`));
256
- return prefixed ? prefixed.slice(name.length + 1) : undefined;
65
+ function buildCliContext() {
66
+ return {
67
+ phrenPath: () => getPhrenPath(),
68
+ profile: () => resolveRuntimeProfile(getPhrenPath()),
69
+ };
257
70
  }
258
- function getPositionalArgs(args, optionNamesWithValues) {
259
- const positions = [];
260
- for (let i = 0; i < args.length; i += 1) {
261
- const arg = args[i];
262
- if (optionNamesWithValues.includes(arg)) {
263
- i += 1;
264
- continue;
265
- }
266
- if (optionNamesWithValues.some((name) => arg.startsWith(`${name}=`))) {
267
- continue;
268
- }
269
- if (!arg.startsWith("--"))
270
- positions.push(arg);
71
+ async function runHelp(args) {
72
+ const target = args[0]?.toLowerCase();
73
+ if (!target) {
74
+ console.log(formatCheatSheet());
75
+ return finish();
271
76
  }
272
- return positions;
273
- }
274
- function parseTaskModeFlag(raw) {
275
- if (!raw)
276
- return undefined;
277
- const normalized = raw.trim().toLowerCase();
278
- return ["off", "manual", "suggest", "auto"].includes(normalized)
279
- ? normalized
280
- : undefined;
281
- }
282
- function parseProactivityFlag(raw) {
283
- if (!raw)
284
- return undefined;
285
- const normalized = raw.trim().toLowerCase();
286
- return ["high", "medium", "low"].includes(normalized)
287
- ? normalized
288
- : undefined;
289
- }
290
- async function promptProjectOwnership(phrenPath, fallback) {
291
- if (!process.stdin.isTTY || !process.stdout.isTTY)
292
- return fallback;
293
- const readline = await import("readline");
294
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
295
- return new Promise((resolve) => {
296
- rl.question(`Project ownership [${PROJECT_OWNERSHIP_MODES.join("/")}] (${fallback}): `, (input) => {
297
- rl.close();
298
- resolve(parseProjectOwnershipMode(input.trim()) ?? fallback);
299
- });
300
- });
301
- }
302
- export async function runTopLevelCommand(argv, opts = {}) {
303
- const argvCommand = argv[0];
304
- if (argvCommand === "--help" || argvCommand === "-h" || argvCommand === "help") {
305
- const topic = argv[1]?.toLowerCase();
306
- if (topic === "all") {
307
- console.log(buildFullHelp());
308
- }
309
- else if (topic && HELP_TOPICS[topic]) {
310
- console.log(HELP_TOPICS[topic]);
311
- }
312
- else if (topic) {
313
- console.log(`Unknown topic: ${topic}\nAvailable: ${Object.keys(HELP_TOPICS).join(", ")}, all`);
314
- }
315
- else {
316
- console.log(HELP_TEXT);
317
- }
77
+ if (target === "all") {
78
+ console.log(formatFullHelp());
318
79
  return finish();
319
80
  }
320
- if (argvCommand === "add") {
321
- const positional = getPositionalArgs(argv.slice(1), ["--ownership"]);
322
- const targetPath = positional[0] || process.cwd();
323
- const ownershipArg = getOptionValue(argv.slice(1), "--ownership");
324
- const phrenPath = defaultPhrenPath();
325
- const profile = (process.env.PHREN_PROFILE) || undefined;
326
- if (!fs.existsSync(phrenPath) || !fs.existsSync(path.join(phrenPath, ".config"))) {
327
- console.log("phren is not set up yet. Run: phren init");
328
- return finish(1);
329
- }
330
- const ownership = ownershipArg
331
- ? parseProjectOwnershipMode(ownershipArg)
332
- : await promptProjectOwnership(phrenPath, getProjectOwnershipDefault(phrenPath));
333
- if (ownershipArg && !ownership) {
334
- console.error(`Invalid --ownership value "${ownershipArg}". Use one of: ${PROJECT_OWNERSHIP_MODES.join(", ")}`);
335
- return finish(1);
336
- }
337
- try {
338
- const added = addProjectFromPath(phrenPath, path.resolve(targetPath), profile, ownership);
339
- if (!added.ok) {
340
- console.error(added.error);
341
- return finish(1);
342
- }
343
- console.log(`Added project "${added.data.project}" (${added.data.ownership})`);
344
- if (added.data.files.claude)
345
- console.log(` ${added.data.files.claude}`);
346
- console.log(` ${added.data.files.findings}`);
347
- console.log(` ${added.data.files.task}`);
348
- console.log(` ${added.data.files.summary}`);
349
- }
350
- catch (e) {
351
- console.error(`Could not add project: ${e instanceof Error ? e.message : String(e)}`);
352
- return finish(1);
353
- }
81
+ // Topic precedence: a name that's both a topic and a command (e.g. "projects",
82
+ // "skills") shows the topic view, which lists every command in that group.
83
+ // Matches the legacy HELP_TOPICS behavior.
84
+ if (TOPIC_ORDER.includes(target)) {
85
+ console.log(formatTopic(target));
354
86
  return finish();
355
87
  }
356
- if (argvCommand === "init") {
357
- const initArgs = argv.slice(1);
358
- const machineIdx = initArgs.indexOf("--machine");
359
- const profileIdx = initArgs.indexOf("--profile");
360
- const mcpIdx = initArgs.indexOf("--mcp");
361
- const templateIdx = initArgs.indexOf("--template");
362
- const modeArg = getOptionValue(initArgs, "--mode");
363
- if (modeArg && !["shared", "project-local"].includes(modeArg)) {
364
- console.error(`Invalid --mode value "${modeArg}". Use "shared" or "project-local".`);
365
- return finish(1);
366
- }
367
- const ownershipMode = parseProjectOwnershipMode(getOptionValue(initArgs, "--project-ownership"));
368
- const taskMode = parseTaskModeFlag(getOptionValue(initArgs, "--task-mode"));
369
- const findingsProactivity = parseProactivityFlag(getOptionValue(initArgs, "--findings-proactivity"));
370
- const taskProactivity = parseProactivityFlag(getOptionValue(initArgs, "--task-proactivity"));
371
- const mcpMode = mcpIdx !== -1 ? parseMcpMode(initArgs[mcpIdx + 1]) : undefined;
372
- if (mcpIdx !== -1 && !mcpMode) {
373
- console.error(`Invalid --mcp value "${initArgs[mcpIdx + 1] || ""}". Use "on" or "off".`);
374
- return finish(1);
375
- }
376
- const ownershipArg = getOptionValue(initArgs, "--project-ownership");
377
- if (ownershipArg && !ownershipMode) {
378
- console.error(`Invalid --project-ownership value "${ownershipArg}". Use one of: ${PROJECT_OWNERSHIP_MODES.join(", ")}`);
379
- return finish(1);
380
- }
381
- const taskModeArg = getOptionValue(initArgs, "--task-mode");
382
- if (taskModeArg && !taskMode) {
383
- console.error(`Invalid --task-mode value "${taskModeArg}". Use one of: off, manual, suggest, auto.`);
384
- return finish(1);
385
- }
386
- const findingsArg = getOptionValue(initArgs, "--findings-proactivity");
387
- if (findingsArg && !findingsProactivity) {
388
- console.error(`Invalid --findings-proactivity value "${findingsArg}". Use one of: high, medium, low.`);
389
- return finish(1);
390
- }
391
- const taskArg = getOptionValue(initArgs, "--task-proactivity");
392
- if (taskArg && !taskProactivity) {
393
- console.error(`Invalid --task-proactivity value "${taskArg}". Use one of: high, medium, low.`);
394
- return finish(1);
395
- }
396
- const cloneUrl = getOptionValue(initArgs, "--clone-url");
397
- try {
398
- await runInit({
399
- mode: modeArg,
400
- machine: machineIdx !== -1 ? initArgs[machineIdx + 1] : undefined,
401
- profile: profileIdx !== -1 ? initArgs[profileIdx + 1] : undefined,
402
- mcp: mcpMode,
403
- projectOwnershipDefault: ownershipMode,
404
- taskMode,
405
- findingsProactivity,
406
- taskProactivity,
407
- template: templateIdx !== -1 ? initArgs[templateIdx + 1] : undefined,
408
- applyStarterUpdate: initArgs.includes("--apply-starter-update"),
409
- dryRun: initArgs.includes("--dry-run"),
410
- yes: initArgs.includes("--yes") || initArgs.includes("-y"),
411
- express: initArgs.includes("--express"),
412
- force: initArgs.includes("--force"),
413
- _walkthroughCloneUrl: cloneUrl,
414
- });
415
- }
416
- catch (err) {
417
- console.error(errorMessage(err));
418
- return finish(1);
419
- }
88
+ const cmdHelp = formatCommand(target);
89
+ if (cmdHelp !== null) {
90
+ console.log(cmdHelp);
420
91
  return finish();
421
92
  }
422
- if (argvCommand === "uninstall") {
423
- const { runUninstall } = await import("./init/init.js");
424
- const skipConfirm = argv.includes("--yes") || argv.includes("-y");
425
- await runUninstall({ yes: skipConfirm });
93
+ const docHelp = formatDocTopic(target);
94
+ if (docHelp !== null) {
95
+ console.log(docHelp);
426
96
  return finish();
427
97
  }
428
- if (argvCommand === "status") {
429
- const { runStatus } = await import("./status.js");
430
- await runStatus();
98
+ console.log(`Unknown topic: ${target}\nAvailable: ${helpTopicNames().join(", ")}`);
99
+ return finish();
100
+ }
101
+ export async function runTopLevelCommand(argv, opts = {}) {
102
+ const argvCommand = argv[0];
103
+ // Health ping. Must run before lookupCommand - `--health` starts with `--`
104
+ // so it's never a registered command name.
105
+ if (argvCommand === "--health")
431
106
  return finish();
107
+ if (argvCommand === "--help" || argvCommand === "-h" || argvCommand === "help") {
108
+ return runHelp(argv.slice(1));
432
109
  }
433
- if (argvCommand === "verify") {
434
- const { runPostInitVerify, getVerifyOutcomeNote } = await import("./init/init.js");
435
- const { getWorkflowPolicy } = await import("./shared/governance.js");
436
- const phrenPath = findPhrenPath() || defaultPhrenPath();
437
- const result = runPostInitVerify(phrenPath);
438
- console.log(`phren verify: ${result.ok ? "ok" : "issues found"}`);
439
- console.log(` tasks: ${getWorkflowPolicy(phrenPath).taskMode} mode`);
440
- for (const check of result.checks) {
441
- console.log(` ${check.ok ? "pass" : "FAIL"} ${check.name}: ${check.detail}`);
442
- if (!check.ok && check.fix) {
443
- console.log(` fix: ${check.fix}`);
110
+ // Bare invocation. On a TTY (and unless suppressed), drop into the shell.
111
+ // On a non-TTY pipeline, fall through to the unknown-command path below;
112
+ // matches legacy behavior so scripts that grep stderr for "Unknown command"
113
+ // keep working.
114
+ if (!argvCommand) {
115
+ if (process.stdin.isTTY && process.stdout.isTTY) {
116
+ if (opts.allowDefaultShell === false) {
117
+ console.log(formatCheatSheet());
118
+ return finish();
444
119
  }
445
- }
446
- if (!result.ok) {
447
- const note = getVerifyOutcomeNote(phrenPath, result.checks);
448
- if (note)
449
- console.log(`\nNote: ${note}`);
450
- console.log(`\nRun \`phren init\` to fix setup issues.`);
451
- }
452
- return finish(result.ok ? 0 : 1);
453
- }
454
- if (argvCommand === "mcp-mode") {
455
- const { runMcpMode } = await import("./init/init.js");
456
- try {
457
- await runMcpMode(argv[1]);
458
- return finish();
459
- }
460
- catch (err) {
461
- console.error(errorMessage(err));
462
- return finish(1);
463
- }
464
- }
465
- if (argvCommand === "hooks-mode") {
466
- const { runHooksMode } = await import("./init/init.js");
467
- try {
468
- await runHooksMode(argv[1]);
120
+ const shellCmd = lookupCommand("shell");
121
+ if (shellCmd)
122
+ await shellCmd.run([], buildCliContext());
469
123
  return finish();
470
124
  }
471
- catch (err) {
472
- console.error(errorMessage(err));
473
- return finish(1);
474
- }
475
- }
476
- if (argvCommand === "link") {
477
- console.error("`phren link` has been removed. Use `phren init` instead.");
478
- return finish(1);
479
- }
480
- if (argvCommand === "--health") {
481
- return finish();
125
+ return false;
482
126
  }
483
- if (!argvCommand && process.stdin.isTTY && process.stdout.isTTY) {
484
- if (opts.allowDefaultShell === false) {
485
- console.log(HELP_TEXT);
486
- return finish();
487
- }
488
- const { runCliCommand } = await import("./cli/cli.js");
489
- await runCliCommand("shell", []);
127
+ const cmd = lookupCommand(argvCommand);
128
+ if (!cmd)
129
+ return false;
130
+ // Intercept before any handler runs - in particular before namespace
131
+ // handlers that used to print their own per-subcommand help text.
132
+ if (argv.includes("--help") || argv.includes("-h")) {
133
+ const out = formatCommand(cmd.name);
134
+ if (out)
135
+ console.log(out);
490
136
  return finish();
491
137
  }
492
- if (argvCommand && CLI_COMMANDS.includes(argvCommand)) {
493
- const { runCliCommand } = await import("./cli/cli.js");
138
+ // Telemetry. Broadens from the legacy CLI_COMMANDS-only branch - natives
139
+ // (add/init/etc.) are now tracked too. Telemetry is opt-in. Hidden internal
140
+ // commands (hook-prompt, background-sync, etc.) are skipped: they fire on
141
+ // every prompt and would drown the meaningful counts.
142
+ if (!cmd.hidden) {
494
143
  try {
495
144
  const { trackCliCommand } = await import("./telemetry.js");
496
- trackCliCommand(defaultPhrenPath(), argvCommand);
145
+ trackCliCommand(defaultPhrenPath(), cmd.name);
497
146
  }
498
147
  catch (err) {
499
148
  logger.debug("cli", `trackCliCommand: ${errorMessage(err)}`);
500
149
  }
501
- await runCliCommand(argvCommand, argv.slice(1));
502
- return finish();
503
150
  }
504
- return false;
151
+ try {
152
+ const code = await cmd.run(argv.slice(1), buildCliContext());
153
+ return finish(typeof code === "number" ? code : undefined);
154
+ }
155
+ catch (err) {
156
+ console.error(errorMessage(err));
157
+ return finish(1);
158
+ }
505
159
  }
@@ -17,6 +17,7 @@ export declare function expandHomePath(input: string): string;
17
17
  export declare function defaultPhrenPath(): string;
18
18
  export declare function rootManifestPath(phrenPath: string): string;
19
19
  export declare function atomicWriteText(filePath: string, content: string): void;
20
+ export declare function isInstallMode(value: unknown): value is InstallMode;
20
21
  export declare function readRootManifest(phrenPath: string): PhrenRootManifest | null;
21
22
  export declare function writeRootManifest(phrenPath: string, manifest: PhrenRootManifest): void;
22
23
  export declare function resolveInstallContext(phrenPath: string): InstallContext;
@@ -47,7 +47,7 @@ export function atomicWriteText(filePath, content) {
47
47
  throw err;
48
48
  }
49
49
  }
50
- function isInstallMode(value) {
50
+ export function isInstallMode(value) {
51
51
  return value === "shared" || value === "project-local";
52
52
  }
53
53
  function isSyncMode(value) {
@@ -1,5 +1,6 @@
1
1
  export declare const PROACTIVITY_LEVELS: readonly ["high", "medium", "low"];
2
2
  export type ProactivityLevel = typeof PROACTIVITY_LEVELS[number];
3
+ export declare function parseProactivityLevel(raw: string | undefined | null): ProactivityLevel | undefined;
3
4
  export declare function getProactivityLevel(explicitPhrenPath?: string): ProactivityLevel;
4
5
  export declare function getProactivityLevelForFindings(explicitPhrenPath?: string): ProactivityLevel;
5
6
  export declare function getProactivityLevelForTask(explicitPhrenPath?: string): ProactivityLevel;
@@ -9,7 +9,7 @@ const DEFAULT_PROACTIVITY_LEVEL = "high";
9
9
  const EXPLICIT_FINDING_SIGNAL_PATTERN = /\b(add finding|worth remembering)\b/i;
10
10
  const EXPLICIT_FINDING_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\]/i;
11
11
  const EXPLICIT_TASK_SIGNAL_PATTERN = /\b(?:add(?:\s+(?:this|that|it))?\s+(?:to\s+(?:the\s+)?)?(?:task|todo(?:\s+list)?|task(?:\s+list)?)|add\s+(?:a\s+)?task|put(?:\s+(?:this|that|it))?\s+(?:in|on)\s+(?:the\s+)?(?:task|todo(?:\s+list)?|task(?:\s+list)?))\b/i;
12
- function parseProactivityLevel(raw) {
12
+ export function parseProactivityLevel(raw) {
13
13
  if (!raw)
14
14
  return undefined;
15
15
  const normalized = raw.trim().toLowerCase();
package/dist/shared.d.ts CHANGED
@@ -1,8 +1,8 @@
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, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
5
- export { PROACTIVITY_LEVELS, type ProactivityLevel, getProactivityLevel, getProactivityLevelForFindings, getProactivityLevelForTask, hasExplicitFindingSignal, hasExplicitTaskSignal, hasExecutionIntent, hasDiscoveryIntent, shouldAutoCaptureFindingsForLevel, shouldAutoCaptureTaskForLevel, } from "./proactivity.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, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
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;
8
8
  export declare function impactLogFile(phrenPath: string): string;
package/dist/shared.js CHANGED
@@ -6,8 +6,8 @@ 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, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
10
- export { PROACTIVITY_LEVELS, getProactivityLevel, getProactivityLevelForFindings, getProactivityLevelForTask, hasExplicitFindingSignal, hasExplicitTaskSignal, hasExecutionIntent, hasDiscoveryIntent, shouldAutoCaptureFindingsForLevel, shouldAutoCaptureTaskForLevel, } from "./proactivity.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, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
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) {
13
13
  if (typeof scope !== "string")
@@ -9,4 +9,6 @@ export declare function resolveExecCommand(cmd: string): ResolvedExecCommand;
9
9
  export declare function errorMessage(err: unknown): string;
10
10
  export declare function isFeatureEnabled(envName: string, defaultValue?: boolean): boolean;
11
11
  export declare function clampInt(raw: string | undefined, fallback: number, min: number, max: number): number;
12
+ export declare function getOptionValue(args: string[], name: string): string | undefined;
13
+ export declare function getPositionalArgs(args: string[], optionNamesWithValues: string[]): string[];
12
14
  export {};
@@ -78,3 +78,27 @@ export function clampInt(raw, fallback, min, max) {
78
78
  return fallback;
79
79
  return Math.min(max, Math.max(min, parsed));
80
80
  }
81
+ // ── Argv parsing helpers ────────────────────────────────────────────────────
82
+ export function getOptionValue(args, name) {
83
+ const exactIdx = args.indexOf(name);
84
+ if (exactIdx !== -1)
85
+ return args[exactIdx + 1];
86
+ const prefixed = args.find((arg) => arg.startsWith(`${name}=`));
87
+ return prefixed ? prefixed.slice(name.length + 1) : undefined;
88
+ }
89
+ export function getPositionalArgs(args, optionNamesWithValues) {
90
+ const positions = [];
91
+ for (let i = 0; i < args.length; i += 1) {
92
+ const arg = args[i];
93
+ if (optionNamesWithValues.includes(arg)) {
94
+ i += 1;
95
+ continue;
96
+ }
97
+ if (optionNamesWithValues.some((name) => arg.startsWith(`${name}=`))) {
98
+ continue;
99
+ }
100
+ if (!arg.startsWith("--"))
101
+ positions.push(arg);
102
+ }
103
+ return positions;
104
+ }
package/dist/utils.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { runGitOrThrow, runGit, normalizeExecCommand, resolveExecCommand, errorMessage, isFeatureEnabled, clampInt, } from "./utils-helpers.js";
1
+ export { runGitOrThrow, runGit, normalizeExecCommand, resolveExecCommand, errorMessage, isFeatureEnabled, clampInt, getOptionValue, getPositionalArgs, } from "./utils-helpers.js";
2
2
  export { isValidProjectName, safeProjectPath, queueFilePath, } from "./utils-paths.js";
3
3
  export { STOP_WORDS, extractKeywordEntries, extractKeywords, learnedSynonymsPath, loadLearnedSynonyms, loadSynonymMap, learnSynonym, removeLearnedSynonym, sanitizeFts5Query, buildRobustFtsQuery, buildRelaxedFtsQuery, buildFtsQueryVariants, } from "./utils-fts.js";