@phren/cli 0.1.44 → 0.1.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/agents/providers/herdr.d.ts +18 -0
  2. package/dist/agents/providers/herdr.js +94 -0
  3. package/dist/agents/providers/spawner.d.ts +13 -0
  4. package/dist/agents/providers/spawner.js +63 -0
  5. package/dist/agents/registry.d.ts +28 -0
  6. package/dist/agents/registry.js +82 -0
  7. package/dist/agents/types.d.ts +51 -0
  8. package/dist/agents/types.js +42 -0
  9. package/dist/cli/actions.d.ts +1 -1
  10. package/dist/cli/actions.js +7 -2
  11. package/dist/cli/config-proactivity.d.ts +6 -6
  12. package/dist/cli/hooks.d.ts +1 -1
  13. package/dist/cli/hooks.js +14 -3
  14. package/dist/cli/search.js +29 -0
  15. package/dist/cli/session-stop.d.ts +1 -1
  16. package/dist/cli/session-tool-hook.d.ts +1 -1
  17. package/dist/cli-registry.d.ts +1 -1
  18. package/dist/cli-registry.js +2 -1
  19. package/dist/content/learning.js +24 -1
  20. package/dist/data/access.js +2 -1
  21. package/dist/generated/memory-ui-graph.browser.js +482 -319
  22. package/dist/governance/locks.js +6 -0
  23. package/dist/graph-core/index.d.ts +2 -0
  24. package/dist/graph-core/index.js +2 -0
  25. package/dist/graph-core/model.d.ts +84 -0
  26. package/dist/graph-core/model.js +445 -0
  27. package/dist/graph-core/types.d.ts +110 -0
  28. package/dist/graph-core/types.js +43 -0
  29. package/dist/index.js +4 -1
  30. package/dist/init/init-uninstall.d.ts +1 -0
  31. package/dist/init/init-uninstall.js +1 -1
  32. package/dist/init/setup.js +11 -4
  33. package/dist/link/context.js +2 -1
  34. package/dist/link/link.js +3 -2
  35. package/dist/link/skills.js +2 -1
  36. package/dist/memory-ui-graph.runtime.js +482 -319
  37. package/dist/phren-art.d.ts +7 -0
  38. package/dist/phren-art.js +6 -41
  39. package/dist/phren-core.d.ts +16 -0
  40. package/dist/phren-core.js +21 -0
  41. package/dist/phren-paths.js +8 -4
  42. package/dist/profile-store.js +3 -2
  43. package/dist/project-config.js +2 -1
  44. package/dist/shared/index.js +1 -1
  45. package/dist/shared/lookup-tail.d.ts +35 -0
  46. package/dist/shared/lookup-tail.js +100 -0
  47. package/dist/shared/retrieval.d.ts +28 -0
  48. package/dist/shared/retrieval.js +45 -0
  49. package/dist/shell/entry.d.ts +3 -3
  50. package/dist/shell/entry.js +19 -44
  51. package/dist/shell/graph/agents.d.ts +48 -0
  52. package/dist/shell/graph/agents.js +152 -0
  53. package/dist/shell/graph/canvas.d.ts +64 -0
  54. package/dist/shell/graph/canvas.js +256 -0
  55. package/dist/shell/graph/controller.d.ts +202 -0
  56. package/dist/shell/graph/controller.js +782 -0
  57. package/dist/shell/graph/glyphs.d.ts +12 -0
  58. package/dist/shell/graph/glyphs.js +31 -0
  59. package/dist/shell/graph/graph-view.d.ts +19 -0
  60. package/dist/shell/graph/graph-view.js +585 -0
  61. package/dist/shell/graph/layout.d.ts +87 -0
  62. package/dist/shell/graph/layout.js +335 -0
  63. package/dist/shell/graph/watch.d.ts +71 -0
  64. package/dist/shell/graph/watch.js +153 -0
  65. package/dist/shell/input.d.ts +3 -0
  66. package/dist/shell/input.js +26 -4
  67. package/dist/shell/intro.d.ts +37 -0
  68. package/dist/shell/intro.js +82 -0
  69. package/dist/shell/logo-fx.d.ts +35 -0
  70. package/dist/shell/logo-fx.js +128 -0
  71. package/dist/shell/render.d.ts +2 -2
  72. package/dist/shell/render.js +15 -28
  73. package/dist/shell/shell.d.ts +15 -1
  74. package/dist/shell/shell.js +50 -7
  75. package/dist/shell/startup.d.ts +40 -0
  76. package/dist/shell/startup.js +113 -0
  77. package/dist/shell/state-store.d.ts +1 -1
  78. package/dist/shell/state-store.js +1 -1
  79. package/dist/shell/types.js +1 -0
  80. package/dist/shell/view.d.ts +3 -0
  81. package/dist/shell/view.js +72 -63
  82. package/dist/store-registry.js +3 -3
  83. package/dist/test-global-setup.d.ts +1 -0
  84. package/dist/test-global-setup.js +22 -0
  85. package/dist/tool-registry.js +1 -0
  86. package/dist/ui/data.d.ts +15 -7
  87. package/dist/ui/data.js +102 -3
  88. package/dist/ui/server.js +6 -56
  89. package/dist/utils-fts.js +2 -1
  90. package/dist/utils-helpers.d.ts +1 -0
  91. package/dist/utils-helpers.js +6 -0
  92. package/dist/utils.d.ts +1 -1
  93. package/dist/utils.js +1 -1
  94. package/package.json +11 -7
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Agents running in a Herdr workspace.
3
+ *
4
+ * `herdr agent list` prints one JSON envelope describing every agent pane —
5
+ * which agent, what it is doing, which directory, and whether it is focused —
6
+ * and answers in a few milliseconds, so it is cheap enough to poll.
7
+ *
8
+ * Nothing Herdr-specific may leak past this file: the rest of phren only ever
9
+ * sees `AgentRecord`.
10
+ */
11
+ import type { AgentProvider, AgentRecord } from "../types.js";
12
+ /** Injected so tests never shell out. */
13
+ export type CommandExistsFn = (cmd: string) => boolean;
14
+ export type RunJsonFn = (argv: string[], timeoutMs: number) => unknown | null;
15
+ export declare function runHerdrJson(argv: string[], timeoutMs: number): unknown | null;
16
+ /** Pull the agent array out of Herdr's envelope, tolerating shape drift. */
17
+ export declare function parseHerdrAgents(payload: unknown): AgentRecord[];
18
+ export declare function createHerdrProvider(commandExists: CommandExistsFn, runJson?: RunJsonFn): AgentProvider;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Agents running in a Herdr workspace.
3
+ *
4
+ * `herdr agent list` prints one JSON envelope describing every agent pane —
5
+ * which agent, what it is doing, which directory, and whether it is focused —
6
+ * and answers in a few milliseconds, so it is cheap enough to poll.
7
+ *
8
+ * Nothing Herdr-specific may leak past this file: the rest of phren only ever
9
+ * sees `AgentRecord`.
10
+ */
11
+ import { execFileSync } from "child_process";
12
+ import { clampInt, resolveExecCommand } from "../../utils-helpers.js";
13
+ import { debugLog } from "../../shared.js";
14
+ import { errorMessage } from "../../utils.js";
15
+ /** Herdr's vocabulary for what an agent is doing, mapped onto phren's. */
16
+ function toStatus(raw) {
17
+ switch (String(raw ?? "").toLowerCase()) {
18
+ case "working":
19
+ case "running":
20
+ case "busy":
21
+ return "working";
22
+ case "done":
23
+ case "complete":
24
+ case "completed":
25
+ return "done";
26
+ case "error":
27
+ case "failed":
28
+ return "error";
29
+ default:
30
+ return "idle";
31
+ }
32
+ }
33
+ export function runHerdrJson(argv, timeoutMs) {
34
+ try {
35
+ const exec = resolveExecCommand("herdr");
36
+ const out = execFileSync(exec.command, argv, {
37
+ encoding: "utf8",
38
+ stdio: ["ignore", "pipe", "ignore"],
39
+ shell: exec.shell,
40
+ timeout: timeoutMs,
41
+ maxBuffer: 2 * 1024 * 1024,
42
+ }).trim();
43
+ if (!out)
44
+ return null;
45
+ return JSON.parse(out);
46
+ }
47
+ catch (err) {
48
+ debugLog(`herdr provider: ${errorMessage(err)}`);
49
+ return null;
50
+ }
51
+ }
52
+ /** Pull the agent array out of Herdr's envelope, tolerating shape drift. */
53
+ export function parseHerdrAgents(payload) {
54
+ if (typeof payload !== "object" || payload === null)
55
+ return [];
56
+ const result = payload.result;
57
+ const agents = typeof result === "object" && result !== null ? result.agents : undefined;
58
+ if (!Array.isArray(agents))
59
+ return [];
60
+ const out = [];
61
+ for (const entry of agents) {
62
+ if (typeof entry !== "object" || entry === null)
63
+ continue;
64
+ const a = entry;
65
+ const cwd = typeof a.foreground_cwd === "string" && a.foreground_cwd ? a.foreground_cwd : a.cwd;
66
+ const paneId = a.pane_id;
67
+ if (typeof cwd !== "string" || !cwd || typeof paneId !== "string" || !paneId)
68
+ continue;
69
+ const title = typeof a.terminal_title_stripped === "string" && a.terminal_title_stripped
70
+ ? a.terminal_title_stripped
71
+ : typeof a.terminal_title === "string" ? a.terminal_title : paneId;
72
+ out.push({
73
+ id: paneId,
74
+ label: title,
75
+ cwd,
76
+ status: toStatus(a.agent_status),
77
+ kind: typeof a.agent === "string" ? a.agent : undefined,
78
+ focused: a.focused === true,
79
+ focus: ["herdr", "agent", "focus", paneId],
80
+ provider: "herdr",
81
+ });
82
+ }
83
+ return out;
84
+ }
85
+ export function createHerdrProvider(commandExists, runJson = runHerdrJson) {
86
+ return {
87
+ name: "herdr",
88
+ available: () => commandExists("herdr"),
89
+ list() {
90
+ const timeoutMs = clampInt(process.env.PHREN_HERDR_TIMEOUT_MS, 3000, 250, 30000);
91
+ return parseHerdrAgents(runJson(["agent", "list"], timeoutMs));
92
+ },
93
+ };
94
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Agents spawned by phren-agent's own multi-agent mode.
3
+ *
4
+ * The spawner runs in a different process from the shell, so it publishes each
5
+ * agent as a small JSON file under `.runtime/agents/` and removes it on exit.
6
+ * That makes phren's own agents visible in the graph on the same footing as
7
+ * any other host's, and gives the provider contract a second real
8
+ * implementation rather than a speculative one.
9
+ */
10
+ import { type AgentProvider } from "../types.js";
11
+ /** Where a spawner publishes its live agents. */
12
+ export declare function agentsRuntimeDir(phrenPath: string): string;
13
+ export declare function createSpawnerProvider(phrenPath: string, now?: () => number): AgentProvider;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Agents spawned by phren-agent's own multi-agent mode.
3
+ *
4
+ * The spawner runs in a different process from the shell, so it publishes each
5
+ * agent as a small JSON file under `.runtime/agents/` and removes it on exit.
6
+ * That makes phren's own agents visible in the graph on the same footing as
7
+ * any other host's, and gives the provider contract a second real
8
+ * implementation rather than a speculative one.
9
+ */
10
+ import * as fs from "fs";
11
+ import * as path from "path";
12
+ import { runtimeFile } from "../../shared.js";
13
+ import { debugLog } from "../../shared.js";
14
+ import { errorMessage } from "../../utils.js";
15
+ import { isAgentRecord } from "../types.js";
16
+ /** Where a spawner publishes its live agents. */
17
+ export function agentsRuntimeDir(phrenPath) {
18
+ return runtimeFile(phrenPath, "agents");
19
+ }
20
+ /** Records older than this are treated as leaked by a process that died badly. */
21
+ const STALE_MS = 5 * 60_000;
22
+ export function createSpawnerProvider(phrenPath, now = Date.now) {
23
+ const dir = agentsRuntimeDir(phrenPath);
24
+ return {
25
+ name: "phren-agent",
26
+ available: () => {
27
+ try {
28
+ return fs.existsSync(dir);
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ },
34
+ list() {
35
+ let entries;
36
+ try {
37
+ entries = fs.readdirSync(dir).filter((name) => name.endsWith(".json"));
38
+ }
39
+ catch {
40
+ return [];
41
+ }
42
+ const out = [];
43
+ for (const entry of entries) {
44
+ const file = path.join(dir, entry);
45
+ try {
46
+ const stat = fs.statSync(file);
47
+ if (now() - stat.mtimeMs > STALE_MS)
48
+ continue;
49
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
50
+ const records = Array.isArray(parsed) ? parsed : [parsed];
51
+ for (const record of records) {
52
+ if (isAgentRecord(record))
53
+ out.push({ ...record, provider: "phren-agent" });
54
+ }
55
+ }
56
+ catch (err) {
57
+ debugLog(`spawner provider: ${entry}: ${errorMessage(err)}`);
58
+ }
59
+ }
60
+ return out;
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Collect the agents running on this machine and join them onto the graph.
3
+ *
4
+ * This module stays free of heavy imports on purpose: the graph view calls it
5
+ * on a timer, and `cli-registry.ts` treats cold start as a constraint. The
6
+ * project lookup is injected rather than imported, which keeps the FTS index
7
+ * out of this path and makes the join testable without a store.
8
+ */
9
+ import type { AgentProvider, AgentRecord, JoinedAgent } from "./types.js";
10
+ /** Off by default, like every other optional feature here. */
11
+ export declare function agentsEnabled(): boolean;
12
+ /** Resolves a working directory to a phren project, or null. */
13
+ export type ProjectResolver = (cwd: string) => string | null;
14
+ /**
15
+ * Ask every available provider, in order. A provider that throws or hangs is
16
+ * skipped rather than allowed to break a repaint; duplicates by id keep the
17
+ * first answer, so an earlier provider wins.
18
+ */
19
+ export declare function collectAgents(providers: AgentProvider[]): AgentRecord[];
20
+ /**
21
+ * Attach each agent to the phren project its directory belongs to. The
22
+ * resolver is the same one the hooks use, so a git worktree lands on the
23
+ * repository it came from. Agents outside any project keep a null project and
24
+ * still appear in the list.
25
+ */
26
+ export declare function joinAgents(records: AgentRecord[], resolve: ProjectResolver): JoinedAgent[];
27
+ /** Sort for display: what you are looking at first, then busy, then the rest. */
28
+ export declare function sortAgents(agents: JoinedAgent[]): JoinedAgent[];
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Collect the agents running on this machine and join them onto the graph.
3
+ *
4
+ * This module stays free of heavy imports on purpose: the graph view calls it
5
+ * on a timer, and `cli-registry.ts` treats cold start as a constraint. The
6
+ * project lookup is injected rather than imported, which keeps the FTS index
7
+ * out of this path and makes the join testable without a store.
8
+ */
9
+ import { isFeatureEnabled } from "../utils-helpers.js";
10
+ import { debugLog } from "../shared.js";
11
+ import { errorMessage } from "../utils.js";
12
+ /** Off by default, like every other optional feature here. */
13
+ export function agentsEnabled() {
14
+ return isFeatureEnabled("PHREN_FEATURE_AGENTS", false);
15
+ }
16
+ /**
17
+ * Ask every available provider, in order. A provider that throws or hangs is
18
+ * skipped rather than allowed to break a repaint; duplicates by id keep the
19
+ * first answer, so an earlier provider wins.
20
+ */
21
+ export function collectAgents(providers) {
22
+ const seen = new Set();
23
+ const out = [];
24
+ for (const provider of providers) {
25
+ let records = [];
26
+ try {
27
+ if (!provider.available())
28
+ continue;
29
+ records = provider.list();
30
+ }
31
+ catch (err) {
32
+ debugLog(`agent provider ${provider.name}: ${errorMessage(err)}`);
33
+ continue;
34
+ }
35
+ for (const record of records) {
36
+ const key = `${record.provider ?? provider.name}:${record.id}`;
37
+ if (seen.has(key))
38
+ continue;
39
+ seen.add(key);
40
+ out.push({ provider: provider.name, ...record });
41
+ }
42
+ }
43
+ return out;
44
+ }
45
+ /**
46
+ * Attach each agent to the phren project its directory belongs to. The
47
+ * resolver is the same one the hooks use, so a git worktree lands on the
48
+ * repository it came from. Agents outside any project keep a null project and
49
+ * still appear in the list.
50
+ */
51
+ export function joinAgents(records, resolve) {
52
+ const cache = new Map();
53
+ return records.map((record) => {
54
+ let project = cache.get(record.cwd);
55
+ if (project === undefined) {
56
+ try {
57
+ project = resolve(record.cwd);
58
+ }
59
+ catch (err) {
60
+ debugLog(`agent join ${record.cwd}: ${errorMessage(err)}`);
61
+ project = null;
62
+ }
63
+ cache.set(record.cwd, project);
64
+ }
65
+ return { ...record, project };
66
+ });
67
+ }
68
+ /** Sort for display: what you are looking at first, then busy, then the rest. */
69
+ export function sortAgents(agents) {
70
+ const rank = (a) => {
71
+ if (a.focused)
72
+ return 0;
73
+ if (a.status === "working")
74
+ return 1;
75
+ if (a.status === "error")
76
+ return 2;
77
+ if (a.status === "idle")
78
+ return 3;
79
+ return 4;
80
+ };
81
+ return agents.slice().sort((a, b) => rank(a) - rank(b) || a.label.localeCompare(b.label));
82
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * What phren knows about a coding agent running on this machine.
3
+ *
4
+ * phren does not spawn or supervise these; it discovers them from whatever is
5
+ * already managing them — a Herdr workspace, phren-agent's own multi-agent
6
+ * spawner, a tmux session — and joins them onto the knowledge graph by the
7
+ * directory they are working in.
8
+ *
9
+ * The contract is deliberately small and host-agnostic. Anything that can
10
+ * print this shape is a provider, which is why a tmux or Zellij user needs a
11
+ * few lines of shell rather than a change to phren.
12
+ */
13
+ export type AgentStatus = "working" | "idle" | "done" | "error";
14
+ export interface AgentRecord {
15
+ /** Stable for as long as the agent lives; used to address it. */
16
+ id: string;
17
+ /** Human label, e.g. the pane's title. */
18
+ label: string;
19
+ /** Working directory, which is how the agent joins a phren project. */
20
+ cwd: string;
21
+ status: AgentStatus;
22
+ /** Which agent this is ("claude", "codex", …), when the host knows. */
23
+ kind?: string;
24
+ /** Whether the host considers this the agent the user is looking at. */
25
+ focused?: boolean;
26
+ /**
27
+ * Command that brings this agent to the front, as argv. phren never needs to
28
+ * know what focusing means for a given host — the provider says how.
29
+ */
30
+ focus?: string[];
31
+ /** Which provider produced this record, for the pane and for debugging. */
32
+ provider?: string;
33
+ }
34
+ /** An agent record joined to the phren project its directory belongs to. */
35
+ export interface JoinedAgent extends AgentRecord {
36
+ /** Resolved phren project, or null when the directory is not a phren project. */
37
+ project: string | null;
38
+ }
39
+ export interface AgentProvider {
40
+ name: string;
41
+ /** Cheap probe. Must not throw and must not block on network or a lock. */
42
+ available(): boolean;
43
+ /** Never throws: a provider that cannot answer returns nothing. */
44
+ list(): AgentRecord[];
45
+ }
46
+ /**
47
+ * Structural guard for records that arrive from outside phren. These drive a
48
+ * command invocation, so a malformed entry is dropped rather than trusted —
49
+ * the same posture governance takes with its on-disk JSON.
50
+ */
51
+ export declare function isAgentRecord(value: unknown): value is AgentRecord;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What phren knows about a coding agent running on this machine.
3
+ *
4
+ * phren does not spawn or supervise these; it discovers them from whatever is
5
+ * already managing them — a Herdr workspace, phren-agent's own multi-agent
6
+ * spawner, a tmux session — and joins them onto the knowledge graph by the
7
+ * directory they are working in.
8
+ *
9
+ * The contract is deliberately small and host-agnostic. Anything that can
10
+ * print this shape is a provider, which is why a tmux or Zellij user needs a
11
+ * few lines of shell rather than a change to phren.
12
+ */
13
+ const STATUSES = new Set(["working", "idle", "done", "error"]);
14
+ /**
15
+ * Structural guard for records that arrive from outside phren. These drive a
16
+ * command invocation, so a malformed entry is dropped rather than trusted —
17
+ * the same posture governance takes with its on-disk JSON.
18
+ */
19
+ export function isAgentRecord(value) {
20
+ if (typeof value !== "object" || value === null || Array.isArray(value))
21
+ return false;
22
+ const rec = value;
23
+ if (typeof rec.id !== "string" || !rec.id)
24
+ return false;
25
+ if (typeof rec.label !== "string")
26
+ return false;
27
+ if (typeof rec.cwd !== "string" || !rec.cwd)
28
+ return false;
29
+ if (typeof rec.status !== "string" || !STATUSES.has(rec.status))
30
+ return false;
31
+ if (rec.kind !== undefined && typeof rec.kind !== "string")
32
+ return false;
33
+ if (rec.focused !== undefined && typeof rec.focused !== "boolean")
34
+ return false;
35
+ if (rec.focus !== undefined) {
36
+ if (!Array.isArray(rec.focus) || rec.focus.length === 0)
37
+ return false;
38
+ if (!rec.focus.every((part) => typeof part === "string" && part.length > 0))
39
+ return false;
40
+ }
41
+ return true;
42
+ }
@@ -9,7 +9,7 @@ export declare function handleDoctor(args: string[]): Promise<void>;
9
9
  export declare function handleStatus(): Promise<void>;
10
10
  export declare function handleQualityFeedback(args: string[]): Promise<void>;
11
11
  export declare function handleMemoryUi(args: string[]): Promise<void>;
12
- export declare function handleShell(_args: string[], profile: string): Promise<void>;
12
+ export declare function handleShell(args: string[], profile: string): Promise<void>;
13
13
  export declare function handleUpdate(args: string[]): Promise<void>;
14
14
  export declare function handleReview(args: string[]): Promise<void>;
15
15
  export declare function handleConsolidationStatus(args: string[]): Promise<void>;
@@ -303,8 +303,13 @@ export async function handleMemoryUi(args) {
303
303
  allowPortFallback: !portRequested,
304
304
  });
305
305
  }
306
- export async function handleShell(_args, profile) {
307
- await startShell(getPhrenPath(), profile);
306
+ export async function handleShell(args, profile) {
307
+ const phrenPath = getPhrenPath();
308
+ const { parseShellArgs, resolveShellStartup } = await import("../shell/startup.js");
309
+ const { startup, warnings } = resolveShellStartup(parseShellArgs(args), { phrenPath, profile });
310
+ if (warnings.length)
311
+ startup.notice = warnings.join(" ");
312
+ await startShell(phrenPath, profile, startup);
308
313
  }
309
314
  export async function handleUpdate(args) {
310
315
  const result = await runPhrenUpdate({ refreshStarter: args.includes("--refresh-starter") });
@@ -1,14 +1,14 @@
1
1
  export declare function buildProactivitySnapshot(phrenPath: string): {
2
2
  path: string;
3
3
  configured: {
4
- proactivity: "high" | "medium" | "low" | null;
5
- proactivityFindings: "high" | "medium" | "low" | null;
6
- proactivityTask: "high" | "medium" | "low" | null;
4
+ proactivity: "high" | "low" | "medium" | null;
5
+ proactivityFindings: "high" | "low" | "medium" | null;
6
+ proactivityTask: "high" | "low" | "medium" | null;
7
7
  };
8
8
  effective: {
9
- proactivity: "high" | "medium" | "low";
10
- proactivityFindings: "high" | "medium" | "low";
11
- proactivityTask: "high" | "medium" | "low";
9
+ proactivity: "high" | "low" | "medium";
10
+ proactivityFindings: "high" | "low" | "medium";
11
+ proactivityTask: "high" | "low" | "medium";
12
12
  };
13
13
  };
14
14
  export declare function handleConfigProactivity(subcommand: "proactivity" | "proactivity.findings" | "proactivity.tasks", args: string[]): void;
@@ -1,6 +1,6 @@
1
1
  export { parseCitations, validateCitation, annotateStale, clearCitationValidCache, type ParsedCitation, } from "./hooks-citations.js";
2
2
  export { getProjectGlobBoost, clearProjectGlobCache, } from "./hooks-globs.js";
3
- export { detectTaskIntent, filterTaskByPriority, searchDocuments, applyTrustFilter, rankResults, selectSnippets, type SelectedSnippet, } from "../shared/retrieval.js";
3
+ export { detectTaskIntent, filterTaskByPriority, searchDocuments, applyTrustFilter, rankResults, applyRelevanceFloor, DEFAULT_MIN_QUERY_RELEVANCE, selectSnippets, type SelectedSnippet, } from "../shared/retrieval.js";
4
4
  export { buildHookOutput, } from "./hooks-output.js";
5
5
  export { handleHookSessionStart, handleHookStop, handleBackgroundSync, handleHookContext, handleHookTool, trackSessionMetrics, filterConversationInsightsForProactivity, extractToolFindings, filterToolFindingsForProactivity, resolveSubprocessArgs, } from "./hooks-session.js";
6
6
  export interface HookPromptInput {
package/dist/cli/hooks.js CHANGED
@@ -9,7 +9,7 @@ import { mergeConfig, } 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";
12
- import { buildRobustFtsQuery, extractKeywordEntries, isFeatureEnabled, clampInt, errorMessage, } from "../utils.js";
12
+ import { buildRobustFtsQuery, extractKeywordEntries, isFeatureEnabled, clampInt, clampFloat, errorMessage, } from "../utils.js";
13
13
  import { getHooksEnabledPreference } from "../init/init.js";
14
14
  import { logger } from "../logger.js";
15
15
  import { isToolHookEnabled, runPrePromptHooks } from "../hooks.js";
@@ -25,13 +25,13 @@ export { parseCitations, validateCitation, annotateStale, clearCitationValidCach
25
25
  // Globs
26
26
  export { getProjectGlobBoost, clearProjectGlobCache, } from "./hooks-globs.js";
27
27
  // Retrieval
28
- export { detectTaskIntent, filterTaskByPriority, searchDocuments, applyTrustFilter, rankResults, selectSnippets, } from "../shared/retrieval.js";
28
+ export { detectTaskIntent, filterTaskByPriority, searchDocuments, applyTrustFilter, rankResults, applyRelevanceFloor, DEFAULT_MIN_QUERY_RELEVANCE, selectSnippets, } from "../shared/retrieval.js";
29
29
  // Output
30
30
  export { buildHookOutput, } from "./hooks-output.js";
31
31
  // Session
32
32
  export { handleHookSessionStart, handleHookStop, handleBackgroundSync, handleHookContext, handleHookTool, trackSessionMetrics, filterConversationInsightsForProactivity, extractToolFindings, filterToolFindingsForProactivity, resolveSubprocessArgs, } from "./hooks-session.js";
33
33
  // ── Imports for the orchestrator ─────────────────────────────────────────────
34
- import { searchDocumentsAsync, applyTrustFilter, rankResults, selectSnippets, detectTaskIntent, } from "../shared/retrieval.js";
34
+ import { searchDocumentsAsync, applyTrustFilter, rankResults, applyRelevanceFloor, DEFAULT_MIN_QUERY_RELEVANCE, selectSnippets, detectTaskIntent, } from "../shared/retrieval.js";
35
35
  import { buildHookOutput } from "./hooks-output.js";
36
36
  import { getGitContext, trackSessionMetrics, } from "./hooks-session.js";
37
37
  import { approximateTokens, SNIPPET_OVERHEAD_TOKENS } from "../shared/retrieval.js";
@@ -172,6 +172,17 @@ export async function handleHookPrompt() {
172
172
  const tRank0 = Date.now();
173
173
  rows = rankResults(rows, intent, gitCtx, detectedProject, getPhrenPath(), db, cwd, keywords);
174
174
  stage.rankMs = Date.now() - tRank0;
175
+ if (!rows.length)
176
+ process.exit(0);
177
+ // Relevance floor: inject signal or nothing. Ranking scores on priors too,
178
+ // so a doc can rank well with no real tie to this prompt — drop those rather
179
+ // than pad to a quota with noise (env PHREN_MIN_QUERY_RELEVANCE=0 disables).
180
+ const relevanceFloor = clampFloat(process.env.PHREN_MIN_QUERY_RELEVANCE, DEFAULT_MIN_QUERY_RELEVANCE, 0, 1);
181
+ const preFloorCount = rows.length;
182
+ rows = applyRelevanceFloor(rows, keywords, gitCtx, detectedProject, relevanceFloor);
183
+ if (rows.length !== preFloorCount) {
184
+ debugLog(`relevance-floor: ${preFloorCount} -> ${rows.length} rows (floor=${relevanceFloor})`);
185
+ }
175
186
  if (!rows.length)
176
187
  process.exit(0);
177
188
  let safeTokenBudget = clampInt(process.env.PHREN_CONTEXT_TOKEN_BUDGET, 550, 180, 10000);
@@ -5,6 +5,8 @@ import { buildIndex, extractSnippet, queryDocRows, queryRows, queryFragmentLinks
5
5
  import { buildFtsQueryVariants, errorMessage, isValidProjectName } from "../utils.js";
6
6
  import { logger } from "../logger.js";
7
7
  import { keywordFallbackSearch } from "../core/search.js";
8
+ import { recordLookupEvents } from "../shared/governance.js";
9
+ import { bestFindingNodeId } from "../finding-graph-id.js";
8
10
  const MAX_HISTORY = 20;
9
11
  const SEARCH_TYPE_ALIASES = {
10
12
  skills: "skill",
@@ -267,11 +269,38 @@ export async function runSearch(opts, phrenPath, profile) {
267
269
  lines.push(`Type filter: ${opts.type}`);
268
270
  lines.push("");
269
271
  }
272
+ const hits = [];
270
273
  for (const row of rows) {
271
274
  const snippet = extractSnippet(row.content, opts.query, 7);
272
275
  lines.push(`[${row.project}/${row.filename}] (${row.type})`);
273
276
  lines.push(snippet);
274
277
  lines.push("");
278
+ hits.push({ project: row.project, filename: row.filename, type: row.type, snippet, path: row.path, content: row.content });
279
+ }
280
+ // Live activity: the CLI records the same lookup events the MCP search
281
+ // does, so `phren search` in one terminal lights up a graph watching in
282
+ // another. Best-effort — logging must never fail a search.
283
+ if (opts.query) {
284
+ try {
285
+ const at = new Date().toISOString();
286
+ recordLookupEvents(phrenPath, hits.map((hit) => {
287
+ const nodeId = hit.type === "findings" ? bestFindingNodeId(hit.project, hit.content, opts.query ?? "") : null;
288
+ return {
289
+ at,
290
+ query: opts.query ?? "",
291
+ project: hit.project,
292
+ filename: hit.filename,
293
+ type: hit.type,
294
+ path: hit.path,
295
+ snippet: hit.snippet,
296
+ source: "search",
297
+ ...(nodeId ? { nodeId } : {}),
298
+ };
299
+ }));
300
+ }
301
+ catch (err) {
302
+ logger.debug("search", `cli search lookup-events: ${errorMessage(err)}`);
303
+ }
275
304
  }
276
305
  return { lines, exitCode: 0 };
277
306
  }
@@ -4,7 +4,7 @@ import { type PushStatus, type SyncStatus } from "../shared/governance.js";
4
4
  * Returns lines that contain insight-signal words and look like actionable knowledge.
5
5
  */
6
6
  export declare function extractConversationInsights(text: string): string[];
7
- export declare function filterConversationInsightsForProactivity(insights: string[], level?: "high" | "medium" | "low"): string[];
7
+ export declare function filterConversationInsightsForProactivity(insights: string[], level?: "high" | "low" | "medium"): string[];
8
8
  /**
9
9
  * Build the `lastSync` patch for a sync attempt, carrying the failure streak
10
10
  * forward. Success resets the counter and stamps `lastSuccessfulPushAt`;
@@ -8,7 +8,7 @@ export declare function filterToolFindingsForProactivity(candidates: Array<{
8
8
  text: string;
9
9
  confidence: number;
10
10
  explicit?: boolean;
11
- }>, level?: "high" | "medium" | "low"): Array<{
11
+ }>, level?: "high" | "low" | "medium"): Array<{
12
12
  text: string;
13
13
  confidence: number;
14
14
  explicit?: boolean;
@@ -35,7 +35,7 @@ export interface Command {
35
35
  hidden?: boolean;
36
36
  run: RunFn;
37
37
  }
38
- export declare const ENV_HELP = "Environment variables:\n PHREN_PATH Override phren directory (default: ~/.phren)\n PHREN_PROFILE Active profile name\n PHREN_DEBUG Enable debug logging (set to 1)\n\n Embeddings:\n PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)\n PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint\n PHREN_EMBEDDING_API_KEY API key for embedding endpoint\n PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)\n\n Context injection:\n PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)\n PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)\n PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)\n\n Feature flags:\n PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)\n PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction\n PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations\n PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding\n PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback\n\n Run 'phren help all' to see everything.\n";
38
+ export declare const ENV_HELP = "Environment variables:\n PHREN_PATH Override phren directory (default: ~/.phren)\n PHREN_PROFILE Active profile name\n PHREN_DEBUG Enable debug logging (set to 1)\n\n Embeddings:\n PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)\n PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint\n PHREN_EMBEDDING_API_KEY API key for embedding endpoint\n PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)\n\n Context injection:\n PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)\n PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)\n PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)\n\n Feature flags:\n PHREN_FEATURE_AGENTS=1 Show running coding agents on the graph\n PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)\n PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction\n PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations\n PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding\n PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback\n\n Run 'phren help all' to see everything.\n";
39
39
  export declare const DOC_TOPICS: Record<string, string>;
40
40
  export declare const REGISTRY: Command[];
41
41
  export declare function lookupCommand(name: string): Command | undefined;
@@ -43,6 +43,7 @@ export const ENV_HELP = `Environment variables:
43
43
  PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)
44
44
 
45
45
  Feature flags:
46
+ PHREN_FEATURE_AGENTS=1 Show running coding agents on the graph
46
47
  PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)
47
48
  PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction
48
49
  PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations
@@ -226,7 +227,7 @@ export const REGISTRY = [
226
227
  {
227
228
  name: "shell",
228
229
  topic: "core",
229
- usage: "phren shell",
230
+ usage: "phren shell [--view <view>] [--project <name>] [--here]",
230
231
  summary: "Interactive memory shell",
231
232
  featured: true,
232
233
  run: async (args, ctx) => {
@@ -3,7 +3,8 @@ import * as path from "path";
3
3
  import * as crypto from "crypto";
4
4
  import { debugLog, appendAuditLog, phrenOk, phrenErr, PhrenError } from "../shared.js";
5
5
  import { normalizeMemoryScope } from "../shared.js";
6
- import { withFileLock } from "../shared/governance.js";
6
+ import { withFileLock, recordLookupEvents } from "../shared/governance.js";
7
+ import { findingNodeIdForLine } from "../finding-graph-id.js";
7
8
  import { isValidProjectName } from "../utils.js";
8
9
  import { storeAwareProjectPath } from "../store-routing.js";
9
10
  import { buildCitationComment, buildScopeComment, buildSourceComment, getHeadCommit, getRepoRoot, inferCitationLocation, } from "./citation.js";
@@ -365,6 +366,28 @@ export function addFindingToFile(phrenPath, project, learning, citationInput, op
365
366
  if (typeof result.data === "string")
366
367
  return phrenOk({ message: result.data, status: "skipped" });
367
368
  appendAuditLog(phrenPath, "add_finding", `project=${project}${result.data.created ? " created=true" : ""} citation_commit=${result.data.citation.commit ?? "none"} citation_file=${result.data.citation.file ?? "none"}`);
369
+ // Live activity: a write lights up the same graph node a lookup would, so a
370
+ // watching shell shows findings being saved as well as read. Best-effort.
371
+ try {
372
+ const bullet = result.data.bullet;
373
+ if (bullet) {
374
+ // Derive the node id the same way buildGraph does, so a watching graph
375
+ // lights the node that was just written rather than a phantom id.
376
+ const nodeId = findingNodeIdForLine(project, bullet.startsWith("-") ? bullet : `- ${bullet}`);
377
+ recordLookupEvents(phrenPath, [{
378
+ query: "",
379
+ project,
380
+ filename: FINDINGS_FILENAME,
381
+ type: "findings",
382
+ snippet: bullet.replace(/^-\s+/, "").replace(/\s*<!--.*?-->/g, "").trim(),
383
+ source: "write",
384
+ ...(nodeId ? { nodeId } : {}),
385
+ }]);
386
+ }
387
+ }
388
+ catch (err) {
389
+ debugLog(`addFindingToFile lookup-event: ${String(err)}`);
390
+ }
368
391
  const cap = Number.parseInt((process.env.PHREN_FINDINGS_CAP) || "", 10) || DEFAULT_FINDINGS_CAP;
369
392
  const activeCount = countActiveFindings(result.data.content);
370
393
  if (activeCount > cap) {