@phren/cli 0.1.32 → 0.1.34

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 (82) hide show
  1. package/dist/capabilities/cli.js +2 -2
  2. package/dist/cli/config-access.d.ts +1 -0
  3. package/dist/cli/config-access.js +59 -0
  4. package/dist/cli/config-llm.d.ts +1 -0
  5. package/dist/cli/config-llm.js +60 -0
  6. package/dist/cli/config-policy.d.ts +11 -0
  7. package/dist/cli/config-policy.js +328 -0
  8. package/dist/cli/config-proactivity.d.ts +15 -0
  9. package/dist/cli/config-proactivity.js +135 -0
  10. package/dist/cli/config-shared.d.ts +6 -0
  11. package/dist/cli/config-shared.js +23 -0
  12. package/dist/cli/config-synonyms.d.ts +1 -0
  13. package/dist/cli/config-synonyms.js +63 -0
  14. package/dist/cli/config.d.ts +6 -24
  15. package/dist/cli/config.js +13 -670
  16. package/dist/cli/team.js +26 -13
  17. package/dist/content/dedup.js +25 -3
  18. package/dist/content/learning.js +10 -16
  19. package/dist/finding-graph-id.d.ts +15 -0
  20. package/dist/finding-graph-id.js +58 -0
  21. package/dist/generated/memory-ui-graph.browser.js +15 -15
  22. package/dist/governance/activity.d.ts +36 -0
  23. package/dist/governance/activity.js +83 -0
  24. package/dist/governance/rbac.d.ts +17 -0
  25. package/dist/governance/rbac.js +37 -1
  26. package/dist/governance/scores.js +26 -45
  27. package/dist/index.js +32 -1
  28. package/dist/memory-ui-graph.runtime.js +15 -15
  29. package/dist/phren-paths.d.ts +6 -0
  30. package/dist/phren-paths.js +8 -0
  31. package/dist/shared/governance.d.ts +1 -0
  32. package/dist/shared/governance.js +1 -0
  33. package/dist/shared/index.d.ts +2 -0
  34. package/dist/shared/index.js +90 -17
  35. package/dist/shared/retrieval.js +25 -6
  36. package/dist/shared.d.ts +1 -1
  37. package/dist/shared.js +1 -1
  38. package/dist/telemetry.js +4 -1
  39. package/dist/tools/config.js +39 -2
  40. package/dist/tools/finding.d.ts +1 -0
  41. package/dist/tools/finding.js +40 -2
  42. package/dist/tools/search.js +28 -1
  43. package/dist/ui/data.d.ts +2 -0
  44. package/dist/ui/data.js +8 -3
  45. package/dist/ui/graph.js +2 -0
  46. package/dist/ui/page.js +45 -2
  47. package/dist/ui/scripts.d.ts +13 -0
  48. package/dist/ui/scripts.js +229 -2
  49. package/dist/ui/server.js +165 -1
  50. package/dist/ui/styles.d.ts +1 -0
  51. package/dist/ui/styles.js +38 -0
  52. package/package.json +3 -3
  53. package/dist/cli-hooks-prompt.d.ts +0 -18
  54. package/dist/cli-hooks-prompt.js +0 -359
  55. package/dist/cli-hooks-session-handlers.d.ts +0 -3
  56. package/dist/cli-hooks-session-handlers.js +0 -356
  57. package/dist/cli-hooks-stop.d.ts +0 -11
  58. package/dist/cli-hooks-stop.js +0 -584
  59. package/dist/init-bootstrap.d.ts +0 -5
  60. package/dist/init-bootstrap.js +0 -21
  61. package/dist/init-detect.d.ts +0 -8
  62. package/dist/init-detect.js +0 -38
  63. package/dist/init-env.d.ts +0 -6
  64. package/dist/init-env.js +0 -114
  65. package/dist/init-fresh.d.ts +0 -10
  66. package/dist/init-fresh.js +0 -234
  67. package/dist/init-hooks.d.ts +0 -5
  68. package/dist/init-hooks.js +0 -26
  69. package/dist/init-mcp.d.ts +0 -8
  70. package/dist/init-mcp.js +0 -65
  71. package/dist/init-modes.d.ts +0 -4
  72. package/dist/init-modes.js +0 -135
  73. package/dist/init-npm.d.ts +0 -10
  74. package/dist/init-npm.js +0 -37
  75. package/dist/init-project-local.d.ts +0 -2
  76. package/dist/init-project-local.js +0 -99
  77. package/dist/init-semantic.d.ts +0 -4
  78. package/dist/init-semantic.js +0 -48
  79. package/dist/init-types.d.ts +0 -59
  80. package/dist/init-types.js +0 -1
  81. package/dist/init-update.d.ts +0 -10
  82. package/dist/init-update.js +0 -96
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A single "lookup event" — emitted each time a memory search lands on a result.
3
+ * Powers the live activity feed in the web UI (SSE) and the VS Code extension
4
+ * (file watcher). Kept deliberately compact so the JSONL stays cheap to tail.
5
+ */
6
+ export interface LookupEvent {
7
+ /** ISO timestamp of when the lookup happened. */
8
+ at: string;
9
+ /** The search query that surfaced this memory. */
10
+ query: string;
11
+ /** Project the memory belongs to. */
12
+ project: string;
13
+ /** Memory filename (e.g. "findings.md", "reference/api/auth.md"). */
14
+ filename: string;
15
+ /** Doc type: findings, reference, summary, task, skill, claude. */
16
+ type: string;
17
+ /** Source key / path of the memory, when available. */
18
+ path?: string;
19
+ /** Precomputed graph node id for this hit (e.g. a specific finding), when resolvable. */
20
+ nodeId?: string;
21
+ /** Short snippet of the matched content. */
22
+ snippet?: string;
23
+ /** What triggered the lookup: "search" (MCP search) | "inject" (hook). */
24
+ source: string;
25
+ /** Originating session id, when known. */
26
+ session?: string;
27
+ }
28
+ /**
29
+ * Append one or more lookup events to the live log. Best-effort: a logging
30
+ * failure must never break a search, so all errors are swallowed (debug-logged).
31
+ */
32
+ export declare function recordLookupEvents(phrenPath: string, events: Array<Omit<LookupEvent, "at"> & {
33
+ at?: string;
34
+ }>): void;
35
+ /** Read the most recent lookup events (newest first), parsed from the JSONL log. */
36
+ export declare function readRecentLookups(phrenPath: string, limit?: number): LookupEvent[];
@@ -0,0 +1,83 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { lookupEventsLogFile } from "../phren-paths.js";
4
+ import { debugLog } from "../shared.js";
5
+ import { errorMessage } from "../utils.js";
6
+ const MAX_LOG_LINES = 500;
7
+ const ROTATE_BYTES = 500_000;
8
+ const MAX_SNIPPET_CHARS = 240;
9
+ function clampSnippet(snippet) {
10
+ if (!snippet)
11
+ return undefined;
12
+ const flat = snippet.replace(/\s+/g, " ").trim();
13
+ if (flat.length <= MAX_SNIPPET_CHARS)
14
+ return flat;
15
+ return flat.slice(0, MAX_SNIPPET_CHARS - 1) + "…";
16
+ }
17
+ /**
18
+ * Append one or more lookup events to the live log. Best-effort: a logging
19
+ * failure must never break a search, so all errors are swallowed (debug-logged).
20
+ */
21
+ export function recordLookupEvents(phrenPath, events) {
22
+ if (!events.length)
23
+ return;
24
+ const logPath = lookupEventsLogFile(phrenPath);
25
+ try {
26
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
27
+ const now = new Date().toISOString();
28
+ const lines = events.map((e) => JSON.stringify({
29
+ at: e.at ?? now,
30
+ query: e.query,
31
+ project: e.project,
32
+ filename: e.filename,
33
+ type: e.type,
34
+ ...(e.path ? { path: e.path } : {}),
35
+ ...(e.nodeId ? { nodeId: e.nodeId } : {}),
36
+ ...(e.snippet ? { snippet: clampSnippet(e.snippet) } : {}),
37
+ source: e.source,
38
+ ...(e.session ? { session: e.session } : {}),
39
+ }));
40
+ fs.appendFileSync(logPath, lines.join("\n") + "\n");
41
+ }
42
+ catch (err) {
43
+ debugLog(`recordLookupEvents write failed: ${errorMessage(err)}`);
44
+ return;
45
+ }
46
+ try {
47
+ const stat = fs.statSync(logPath);
48
+ if (stat.size > ROTATE_BYTES) {
49
+ const content = fs.readFileSync(logPath, "utf8");
50
+ const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES);
51
+ fs.writeFileSync(logPath, kept.join("\n") + "\n");
52
+ }
53
+ }
54
+ catch (err) {
55
+ debugLog(`recordLookupEvents rotation failed: ${errorMessage(err)}`);
56
+ }
57
+ }
58
+ /** Read the most recent lookup events (newest first), parsed from the JSONL log. */
59
+ export function readRecentLookups(phrenPath, limit = 40) {
60
+ const logPath = lookupEventsLogFile(phrenPath);
61
+ try {
62
+ if (!fs.existsSync(logPath))
63
+ return [];
64
+ const lines = fs.readFileSync(logPath, "utf8").split("\n").filter(Boolean);
65
+ const recent = lines.slice(-limit).reverse();
66
+ const out = [];
67
+ for (const line of recent) {
68
+ try {
69
+ const parsed = JSON.parse(line);
70
+ if (parsed && typeof parsed.at === "string")
71
+ out.push(parsed);
72
+ }
73
+ catch {
74
+ // Skip malformed lines rather than failing the whole read.
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+ catch (err) {
80
+ debugLog(`readRecentLookups failed: ${errorMessage(err)}`);
81
+ return [];
82
+ }
83
+ }
@@ -17,6 +17,23 @@
17
17
  * The actor is read from the PHREN_ACTOR env var (falls back to open if unset).
18
18
  */
19
19
  type RbacAction = "add_finding" | "remove_finding" | "edit_finding" | "complete_task" | "add_task" | "remove_task" | "update_task" | "pin_task" | "manage_config";
20
+ export declare const ACCESS_ROLE_KEYS: readonly ["admins", "contributors", "readers"];
21
+ export type AccessRole = (typeof ACCESS_ROLE_KEYS)[number];
22
+ export type AccessRolePatch = Partial<Record<AccessRole, string[]>>;
23
+ /**
24
+ * Single source of truth for writing access-control role lists. Writes to the
25
+ * global `.config/access-control.json` or, when `project` is given, to that
26
+ * project's `phren.project.yaml` under the `access` key (merged with any
27
+ * existing roles). Returns the role lists as written at the chosen scope.
28
+ *
29
+ * Shared by the CLI (`phren config access`) and the MCP `set_config` tool so
30
+ * the two paths can never diverge.
31
+ */
32
+ export declare function setAccessRoles(phrenPath: string, patch: AccessRolePatch, project?: string): {
33
+ admins: string[];
34
+ contributors: string[];
35
+ readers: string[];
36
+ };
20
37
  /**
21
38
  * Convenience wrapper: returns a permission-denied MCP error string,
22
39
  * or null if the action is allowed.
@@ -20,7 +20,7 @@ import * as fs from "fs";
20
20
  import * as path from "path";
21
21
  import { debugLog } from "../shared.js";
22
22
  import { errorMessage } from "../utils.js";
23
- import { readProjectConfig } from "../project-config.js";
23
+ import { readProjectConfig, writeProjectConfig } from "../project-config.js";
24
24
  function configDir(phrenPath) {
25
25
  return path.join(phrenPath, ".config");
26
26
  }
@@ -45,6 +45,42 @@ function normalizeStringArray(value) {
45
45
  return [];
46
46
  return value.filter((item) => typeof item === "string" && item.trim().length > 0);
47
47
  }
48
+ export const ACCESS_ROLE_KEYS = ["admins", "contributors", "readers"];
49
+ /**
50
+ * Single source of truth for writing access-control role lists. Writes to the
51
+ * global `.config/access-control.json` or, when `project` is given, to that
52
+ * project's `phren.project.yaml` under the `access` key (merged with any
53
+ * existing roles). Returns the role lists as written at the chosen scope.
54
+ *
55
+ * Shared by the CLI (`phren config access`) and the MCP `set_config` tool so
56
+ * the two paths can never diverge.
57
+ */
58
+ export function setAccessRoles(phrenPath, patch, project) {
59
+ const clean = {};
60
+ for (const key of ACCESS_ROLE_KEYS) {
61
+ if (patch[key] !== undefined)
62
+ clean[key] = normalizeStringArray(patch[key]);
63
+ }
64
+ if (project) {
65
+ const current = readProjectConfig(phrenPath, project).access ?? {};
66
+ writeProjectConfig(phrenPath, project, { access: { ...current, ...clean } });
67
+ }
68
+ else {
69
+ const current = readGlobalAccessControl(phrenPath) ?? {};
70
+ const next = { ...current, ...clean };
71
+ const dir = configDir(phrenPath);
72
+ fs.mkdirSync(dir, { recursive: true });
73
+ fs.writeFileSync(path.join(dir, "access-control.json"), JSON.stringify(next, null, 2) + "\n");
74
+ }
75
+ const written = project
76
+ ? (readProjectConfig(phrenPath, project).access ?? {})
77
+ : (readGlobalAccessControl(phrenPath) ?? {});
78
+ return {
79
+ admins: normalizeStringArray(written.admins),
80
+ contributors: normalizeStringArray(written.contributors),
81
+ readers: normalizeStringArray(written.readers),
82
+ };
83
+ }
48
84
  function mergeAccessControl(global, projectAccess) {
49
85
  // If neither global nor project access is configured, open mode
50
86
  if (!global && !projectAccess)
@@ -34,24 +34,14 @@ function entriesObject(data) {
34
34
  return data.entries;
35
35
  return data;
36
36
  }
37
- function validateScoresJson(filePath) {
38
- try {
39
- if (!fs.existsSync(filePath))
40
- return true;
41
- const raw = fs.readFileSync(filePath, "utf8");
42
- const data = JSON.parse(raw);
43
- if (!isRecord(data))
44
- return false;
45
- if (isVersionedEntries(data) && !hasValidSchemaVersion(data))
46
- return false;
47
- if (isVersionedEntries(data) && !isRecord(data.entries))
48
- return false;
49
- return Object.values(entriesObject(data)).every((entry) => isEntryScore(entry));
50
- }
51
- catch (err) {
52
- debugLog(`validateScoresJson failed for ${filePath}: ${errorMessage(err)}`);
37
+ function validateScoresData(data) {
38
+ if (!isRecord(data))
53
39
  return false;
54
- }
40
+ if (isVersionedEntries(data) && !hasValidSchemaVersion(data))
41
+ return false;
42
+ if (isVersionedEntries(data) && !isRecord(data.entries))
43
+ return false;
44
+ return Object.values(entriesObject(data)).every((entry) => isEntryScore(entry));
55
45
  }
56
46
  function normalizeVersionedEntries(data, guard) {
57
47
  const out = {};
@@ -69,11 +59,11 @@ function readScoresFile(phrenPath) {
69
59
  try {
70
60
  if (!fs.existsSync(file))
71
61
  return { ...DEFAULT_MEMORY_SCORES_FILE.entries };
72
- if (!validateScoresJson(file)) {
62
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
63
+ if (!validateScoresData(parsed)) {
73
64
  debugLog(`readScoresFile: ${file} failed validation, using defaults`);
74
65
  return { ...DEFAULT_MEMORY_SCORES_FILE.entries };
75
66
  }
76
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
77
67
  return normalizeVersionedEntries(parsed, isEntryScore).entries;
78
68
  }
79
69
  catch (err) {
@@ -103,24 +93,27 @@ function appendScoreJournal(phrenPath, key, delta) {
103
93
  fs.appendFileSync(file, JSON.stringify(entry) + "\n");
104
94
  });
105
95
  }
96
+ function parseScoreJournal(raw, context) {
97
+ return raw
98
+ .split("\n")
99
+ .filter(Boolean)
100
+ .map((line) => {
101
+ try {
102
+ return JSON.parse(line);
103
+ }
104
+ catch (err) {
105
+ logger.debug("scores", `${context} parseLine: ${errorMessage(err)}`);
106
+ return null;
107
+ }
108
+ })
109
+ .filter((entry) => entry !== null && typeof entry.key === "string" && typeof entry.delta === "object" && entry.delta !== null);
110
+ }
106
111
  function readScoreJournal(phrenPath) {
107
112
  const file = scoresJournalFile(phrenPath);
108
113
  if (!fs.existsSync(file))
109
114
  return [];
110
115
  try {
111
- return fs.readFileSync(file, "utf8")
112
- .split("\n")
113
- .filter(Boolean)
114
- .map((line) => {
115
- try {
116
- return JSON.parse(line);
117
- }
118
- catch (err) {
119
- logger.debug("scores", `readScoreJournal parseLine: ${errorMessage(err)}`);
120
- return null;
121
- }
122
- })
123
- .filter((entry) => entry !== null && typeof entry.key === "string" && typeof entry.delta === "object" && entry.delta !== null);
116
+ return parseScoreJournal(fs.readFileSync(file, "utf8"), "readScoreJournal");
124
117
  }
125
118
  catch (err) {
126
119
  debugLog(`readScoreJournal failed: ${errorMessage(err)}`);
@@ -140,19 +133,7 @@ function claimScoreJournal(phrenPath) {
140
133
  if (!claimedFile)
141
134
  return [];
142
135
  try {
143
- return fs.readFileSync(claimedFile, "utf8")
144
- .split("\n")
145
- .filter(Boolean)
146
- .map((line) => {
147
- try {
148
- return JSON.parse(line);
149
- }
150
- catch (err) {
151
- logger.debug("scores", `claimScoreJournal parseLine: ${errorMessage(err)}`);
152
- return null;
153
- }
154
- })
155
- .filter((entry) => entry !== null && typeof entry.key === "string" && typeof entry.delta === "object" && entry.delta !== null);
136
+ return parseScoreJournal(fs.readFileSync(claimedFile, "utf8"), "claimScoreJournal");
156
137
  }
157
138
  catch (err) {
158
139
  debugLog(`claimScoreJournal failed: ${errorMessage(err)}`);
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import * as fs from "fs";
5
5
  import * as path from "path";
6
6
  import { findPhrenPathWithArg, debugLog, runtimeDir, } from "./shared.js";
7
7
  import { log as structuredLog, logger } from "./logger.js";
8
- import { buildIndex, updateFileInIndex as updateFileInIndexFn, } from "./shared/index.js";
8
+ import { buildIndex, flushEmbeddingQueue, updateFileInIndex as updateFileInIndexFn, } from "./shared/index.js";
9
9
  import { runCustomHooks } from "./hooks.js";
10
10
  import { register as registerSearch } from "./tools/search.js";
11
11
  import { register as registerTask } from "./tools/tasks.js";
@@ -74,6 +74,7 @@ async function main() {
74
74
  cleanStaleLocks(phrenPath);
75
75
  let db = null;
76
76
  let indexReady = false;
77
+ let shuttingDown = false;
77
78
  try {
78
79
  db = await buildIndex(phrenPath, profile);
79
80
  indexReady = true;
@@ -173,8 +174,15 @@ async function main() {
173
174
  "get_findings",
174
175
  "get_tasks",
175
176
  ]);
177
+ const registeredToolNames = new Set();
176
178
  server.registerTool = function (name, config, handler) {
177
179
  const registeredName = name;
180
+ // Registration runs before server.connect, so throwing here fails fast at
181
+ // startup instead of letting a later module silently shadow an earlier tool.
182
+ if (registeredToolNames.has(registeredName)) {
183
+ throw new Error(`Duplicate MCP tool registration: "${String(registeredName)}"`);
184
+ }
185
+ registeredToolNames.add(registeredName);
178
186
  let finalConfig = config;
179
187
  if (ALWAYS_LOAD_TOOLS.has(registeredName)) {
180
188
  const cfgObj = config;
@@ -182,6 +190,17 @@ async function main() {
182
190
  finalConfig = { ...cfgObj, _meta: { ...existingMeta, "anthropic/alwaysLoad": true } };
183
191
  }
184
192
  const wrapped = async (...args) => {
193
+ if (shuttingDown) {
194
+ return {
195
+ content: [{
196
+ type: "text",
197
+ text: JSON.stringify({
198
+ ok: false,
199
+ error: "phren-mcp server is shutting down; retry in a new session",
200
+ }, null, 2),
201
+ }],
202
+ };
203
+ }
185
204
  if (!indexReady || !db) {
186
205
  return {
187
206
  content: [{
@@ -237,6 +256,7 @@ async function main() {
237
256
  console.error(`phren-mcp running (${phrenPath})`);
238
257
  // Graceful shutdown: drain write queue and close DB before exit
239
258
  async function shutdown(signal) {
259
+ shuttingDown = true;
240
260
  structuredLog("info", "shutdown", `Received ${signal}, draining write queue...`);
241
261
  try {
242
262
  await writeQueue;
@@ -244,6 +264,17 @@ async function main() {
244
264
  catch {
245
265
  // Write queue errors already logged
246
266
  }
267
+ // Persist any pending embeddings; bounded so a slow/unreachable Ollama
268
+ // can't stall shutdown.
269
+ try {
270
+ await Promise.race([
271
+ flushEmbeddingQueue(),
272
+ new Promise((resolve) => setTimeout(resolve, 3000)),
273
+ ]);
274
+ }
275
+ catch (err) {
276
+ logger.warn("shutdown", `embFlush: ${errorMessage(err)}`);
277
+ }
247
278
  try {
248
279
  db?.close();
249
280
  }