@phren/cli 0.3.34 → 0.3.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.
Files changed (68) hide show
  1. package/dist/bridge/agent-hooks.d.ts +11 -1
  2. package/dist/bridge/agent-hooks.js +56 -19
  3. package/dist/bridge/changes.js +30 -13
  4. package/dist/bridge/dispatch-command.js +3 -1
  5. package/dist/bridge/health.js +3 -1
  6. package/dist/bridge/host-key.d.ts +16 -0
  7. package/dist/bridge/host-key.js +35 -0
  8. package/dist/bridge/launch-brief.d.ts +2 -0
  9. package/dist/bridge/launch-brief.js +5 -0
  10. package/dist/bridge/link.js +11 -4
  11. package/dist/bridge/owner-inbox-sources.d.ts +5 -0
  12. package/dist/bridge/owner-inbox-sources.js +94 -0
  13. package/dist/bridge/owner-inbox-view.js +20 -1
  14. package/dist/bridge/owner-inbox.d.ts +7 -3
  15. package/dist/bridge/owner-inbox.js +113 -69
  16. package/dist/bridge/pair.js +3 -2
  17. package/dist/bridge/server.js +3 -23
  18. package/dist/bridge/sudo.d.ts +36 -6
  19. package/dist/bridge/sudo.js +180 -37
  20. package/dist/bridge/worker-reports.d.ts +8 -1
  21. package/dist/bridge/worker-reports.js +28 -7
  22. package/dist/bridge-hook.mjs +817 -473
  23. package/dist/clanker.d.ts +54 -0
  24. package/dist/clanker.js +188 -0
  25. package/dist/cli/config.js +30 -0
  26. package/dist/cli/hooks-output.d.ts +1 -1
  27. package/dist/cli/hooks-output.js +28 -21
  28. package/dist/cli/hooks.js +1 -1
  29. package/dist/cli/namespaces-skills.js +2 -2
  30. package/dist/cli/namespaces-tasks.js +46 -7
  31. package/dist/cli/session-start.js +12 -3
  32. package/dist/cli/session-stop.js +9 -0
  33. package/dist/cli/team.js +3 -0
  34. package/dist/cli-handlers.js +7 -0
  35. package/dist/cli-registry.js +1 -0
  36. package/dist/data/task-format.d.ts +5 -1
  37. package/dist/data/task-format.js +13 -5
  38. package/dist/index.js +82 -50
  39. package/dist/init/init-configure.d.ts +2 -0
  40. package/dist/init/init-configure.js +12 -0
  41. package/dist/init/init-uninstall.js +21 -2
  42. package/dist/init/init.d.ts +2 -0
  43. package/dist/init/init.js +11 -3
  44. package/dist/init/preferences.d.ts +6 -0
  45. package/dist/init/teardown.js +18 -4
  46. package/dist/link/doctor.js +2 -2
  47. package/dist/link/link.js +9 -0
  48. package/dist/link/refresh.d.ts +10 -0
  49. package/dist/link/refresh.js +34 -0
  50. package/dist/mcp/local-index.d.ts +20 -0
  51. package/dist/mcp/local-index.js +39 -1
  52. package/dist/shared/index.d.ts +14 -0
  53. package/dist/shared/index.js +88 -74
  54. package/dist/shared/retrieval.js +1 -1
  55. package/dist/skill/files.js +40 -11
  56. package/dist/skill/registry.d.ts +6 -0
  57. package/dist/skill/registry.js +21 -5
  58. package/dist/task/lifecycle.js +3 -1
  59. package/dist/tools/dispatch.js +5 -2
  60. package/dist/tools/finding.js +20 -11
  61. package/dist/tools/graph.d.ts +2 -0
  62. package/dist/tools/graph.js +2 -0
  63. package/dist/tools/search.d.ts +2 -0
  64. package/dist/tools/search.js +88 -6
  65. package/dist/tools/tasks.js +45 -0
  66. package/dist/tools/types.d.ts +3 -1
  67. package/dist/tools/types.js +3 -2
  68. package/package.json +1 -1
@@ -21,6 +21,7 @@ import { rankResults, searchKnowledgeRows, applyTrustFilter, searchFederatedStor
21
21
  import { formatActorAttribution, parseScopeComment, parseSourceComment, collectSymbolCitations } from "../content/citation.js";
22
22
  import { resolveActiveSessionScope } from "./session.js";
23
23
  import { logger } from "../logger.js";
24
+ import { CLANKER_FETCH_HINT, clankerEnabled, findEntry, formatRow, queryTerms, rowKeywords, rowTitle, rowsForDoc } from "../clanker.js";
24
25
  import { DETAIL_PAGE_CHARS, LIST_TEXT_MAX_CHARS, SUMMARY_MAX_CHARS, SUMMARY_MAX_TRUTHS, clipText, shrinkToBudget, snippetBudget } from "../response-budget.js";
25
26
  /**
26
27
  * Q30: Log zero-result queries to .runtime/search-misses.jsonl.
@@ -136,6 +137,9 @@ async function handleGetMemoryDetail(ctx, { id: rawId, offset }) {
136
137
  catch {
137
138
  return mcpResponse({ ok: false, error: `Invalid memory ID format: "${rawId}" contains malformed URL encoding.` });
138
139
  }
140
+ const entryId = rawId.trim().toLowerCase().match(/^(fid:[a-z0-9]{8}|bid:[a-f0-9]{8})$/)?.[1];
141
+ if (entryId)
142
+ return handleGetEntryDetail(ctx, entryId);
139
143
  const match = id.match(/^mem:([^/]+)\/(.+)$/);
140
144
  if (!match) {
141
145
  return mcpResponse({ ok: false, error: `Invalid memory ID format "${rawId}". Expected mem:project/path/to/file.md.` });
@@ -197,6 +201,43 @@ async function handleGetMemoryDetail(ctx, { id: rawId, offset }) {
197
201
  },
198
202
  });
199
203
  }
204
+ /** One finding (`fid:`) or task (`bid:`) with its continuation lines, found through the index. */
205
+ function handleGetEntryDetail(ctx, entryId) {
206
+ const db = ctx.db();
207
+ // Active files first, then the archive topics that keep a finding's fid.
208
+ const docs = queryDocRows(db, "SELECT project, filename, type, content, path FROM docs WHERE content LIKE ? ORDER BY CASE type WHEN 'findings' THEN 0 WHEN 'task' THEN 0 ELSE 1 END", [`%${entryId}%`]) ?? [];
209
+ for (const doc of docs) {
210
+ // The file itself: the index drops comment lines such as citations.
211
+ let fileText = doc.content;
212
+ try {
213
+ fileText = fs.readFileSync(doc.path, "utf8");
214
+ }
215
+ catch (err) {
216
+ logger.debug("search", `get_memory_detail entry read: ${errorMessage(err)}`);
217
+ }
218
+ const entry = findEntry(fileText, entryId) ?? findEntry(doc.content, entryId);
219
+ if (!entry)
220
+ continue;
221
+ const content = clipText(entry.text, DETAIL_PAGE_CHARS);
222
+ const source = getDocSourceKey(doc, ctx.phrenPath);
223
+ return mcpResponse({
224
+ ok: true,
225
+ message: `[${entryId}] ${source} (${doc.type})\n\n${content}`,
226
+ data: {
227
+ id: entryId,
228
+ project: doc.project,
229
+ filename: doc.filename,
230
+ type: doc.type,
231
+ source: `mem:${source}`,
232
+ title: rowTitle(entry.line),
233
+ keywords: rowKeywords(entry.line),
234
+ content,
235
+ path: doc.path,
236
+ },
237
+ }, { compact: true });
238
+ }
239
+ return mcpResponse({ ok: false, error: `Memory not found: ${entryId}` });
240
+ }
200
241
  async function handleSearchKnowledge(ctx, { query, limit, project, type, tag, since, status, include_history, synthesize }) {
201
242
  const { phrenPath } = ctx;
202
243
  try {
@@ -446,6 +487,29 @@ async function handleSearchKnowledge(ctx, { query, limit, project, type, tag, si
446
487
  catch (err) {
447
488
  logger.debug("search", `fragment query: ${errorMessage(err)}`);
448
489
  }
490
+ const fallbackNote = usedFallback ? " (keyword fallback)" : "";
491
+ const fragmentNote = relatedFragments.length > 0 ? `\n\nRelated fragments: ${relatedFragments.join(", ")}` : "";
492
+ if (clankerEnabled(phrenPath)) {
493
+ // One row per matching finding or task (fid:/bid:), else per document.
494
+ const terms = queryTerms(query);
495
+ const rowCap = maxResults * 2;
496
+ const clankerRows = [];
497
+ for (const row of rows) {
498
+ if (clankerRows.length >= rowCap)
499
+ break;
500
+ const federationSource = "federationSource" in row ? row.federationSource : undefined;
501
+ const docId = federationSource ? `${federationSource}:${row.project}/${row.filename}` : `mem:${getDocSourceKey(row, phrenPath)}`;
502
+ const bestLine = extractSnippet(row.content, query, 1, 400);
503
+ clankerRows.push(...rowsForDoc(row, docId, terms, bestLine, Math.min(3, rowCap - clankerRows.length)));
504
+ }
505
+ runCustomHooks(phrenPath, "post-search", { PHREN_QUERY: query, PHREN_RESULT_COUNT: String(clankerRows.length) });
506
+ return mcpResponse({
507
+ ok: true,
508
+ message: `${clankerRows.length} row(s) for "${query}"${fallbackNote}. ${CLANKER_FETCH_HINT}\n${clankerRows.map((row) => formatRow(row, !filterProject)).join("\n")}${fragmentNote}`,
509
+ // The rows are the message; data carries only the ids so they are not sent twice.
510
+ data: { query, count: clankerRows.length, ids: clankerRows.map((row) => row.id), fallback: usedFallback },
511
+ }, { compact: true });
512
+ }
449
513
  const formatted = results.map((r) => {
450
514
  const fedNote = r.federation_source ? ` [from: ${r.federation_source}]` : "";
451
515
  const more = r.truncated && r.id ? ` · excerpt; full text: get_memory_detail id="${r.id}"` : "";
@@ -495,8 +559,6 @@ async function handleSearchKnowledge(ctx, { query, limit, project, type, tag, si
495
559
  debugLog(`search synthesis failed: ${errorMessage(err)}`);
496
560
  }
497
561
  }
498
- const fallbackNote = usedFallback ? " (keyword fallback)" : "";
499
- const fragmentNote = relatedFragments.length > 0 ? `\n\nRelated fragments: ${relatedFragments.join(", ")}` : "";
500
562
  const synthesisBlock = synthesis ? `\n\n${synthesis}\n\n---\n\n` : "\n\n";
501
563
  runCustomHooks(phrenPath, "post-search", { PHREN_QUERY: query, PHREN_RESULT_COUNT: String(results.length) });
502
564
  return mcpResponse({
@@ -711,6 +773,24 @@ async function handleGetFindings(ctx, { project, limit, offset, include_supersed
711
773
  const requested = limit ?? 50;
712
774
  const hiddenHistoryCount = includeHistory ? 0 : historyCount;
713
775
  const historyNote = hiddenHistoryCount > 0 ? ` (${hiddenHistoryCount} historical hidden)` : "";
776
+ if (clankerEnabled(phrenPath)) {
777
+ const page = filteredItems.slice(from, from + requested);
778
+ const rows = page.map((entry) => ({
779
+ id: entry.stableId ? `fid:${entry.stableId}` : entry.id,
780
+ date: entry.date,
781
+ title: rowTitle(entry.text),
782
+ keywords: rowKeywords(entry.text),
783
+ ...(entry.status !== "active" ? { status: entry.status } : {}),
784
+ }));
785
+ const nextOffset = from + page.length < filteredItems.length ? from + page.length : null;
786
+ const range = from > 0 ? `${from + 1}–${from + page.length} of ${filteredItems.length}` : `${page.length}/${filteredItems.length}`;
787
+ const lines = rows.map((row) => `${row.id} ${row.date} ${row.title} [${row.keywords.join(", ")}]${row.status ? ` (${row.status})` : ""}`);
788
+ return mcpResponse({
789
+ ok: true,
790
+ message: `Findings for ${project} (${range})${historyNote}. ${CLANKER_FETCH_HINT}\n${lines.join("\n")}${nextOffset !== null ? `\nMore: offset=${nextOffset}` : ""}`,
791
+ data: { project, total: filteredItems.length, offset: from, next_offset: nextOffset, status: status ?? null, include_history: includeHistory, historyCount: hiddenHistoryCount },
792
+ }, { compact: true });
793
+ }
714
794
  const buildPage = (size) => {
715
795
  const capped = filteredItems.slice(from, from + size).map(entry => ({
716
796
  ...entry,
@@ -790,15 +870,17 @@ async function handleStoreList(ctx) {
790
870
  });
791
871
  }
792
872
  // ── Registration ─────────────────────────────────────────────────────────────
873
+ /** These tools answer from the FTS index; the MCP server refreshes it before each call. */
874
+ export const readsIndex = true;
793
875
  export function register(server, ctx) {
794
876
  server.registerTool("get_memory_detail", {
795
877
  title: "◆ phren · memory detail",
796
878
  description: "Fetch the full content of a specific memory entry by its ID. Use this to expand a search_knowledge " +
797
- "excerpt or an entry from the hook-prompt compact memory index. Long documents are paged by offset. " +
798
- "The id format is `mem:project/path/to/file.md` as shown in the memory index.",
879
+ "excerpt or a row from clanker mode's compact index. A `fid:` (finding) or `bid:` (task) id returns that one entry; " +
880
+ "a `mem:project/path/to/file.md` id returns the document, paged by offset.",
799
881
  inputSchema: z.object({
800
- id: z.string().describe("Memory ID in the format `mem:project/path/to/file.md` (e.g. `mem:my-app/reference/api/auth.md`). " +
801
- "Returned by search_knowledge results and the hook-prompt compact index."),
882
+ id: z.string().describe("`fid:xxxxxxxx`, `bid:xxxxxxxx`, or `mem:project/path/to/file.md` (e.g. `mem:my-app/reference/api/auth.md`). " +
883
+ "Returned by search_knowledge, get_findings, get_tasks and the hook-prompt index."),
802
884
  offset: z.number().int().min(0).optional().describe(`Character offset to start reading from. Documents longer than ${DETAIL_PAGE_CHARS} characters are returned in pages; pass the previous response's next_offset.`),
803
885
  }),
804
886
  }, (params) => handleGetMemoryDetail(ctx, params));
@@ -14,6 +14,7 @@ import { normalizeMemoryScope } from "../shared.js";
14
14
  import { permissionDeniedError } from "../governance/rbac.js";
15
15
  import { getMachineName } from "../machine-identity.js";
16
16
  import { claimTaskSynced } from "../sync/task-claim.js";
17
+ import { CLANKER_FETCH_HINT, clankerEnabled, rowKeywords, rowTitle } from "../clanker.js";
17
18
  import { LIST_RESPONSE_MAX_CHARS, LIST_TEXT_MAX_CHARS, clipTail, shrinkToBudget } from "../response-budget.js";
18
19
  const TASK_SECTION_ORDER = ["Active", "Queue", "Done"];
19
20
  const DEFAULT_TASK_LIMIT = 20;
@@ -99,6 +100,22 @@ function buildTaskSummary(doc, includedSections, base, original = doc) {
99
100
  }
100
101
  return lines.join("\n");
101
102
  }
103
+ /** Clanker mode: one line per task (id, title, keywords, priority, claim). */
104
+ function buildClankerTaskRows(doc, includedSections) {
105
+ const lines = [`## ${doc.project}`];
106
+ for (const section of includedSections) {
107
+ const items = doc.items[section];
108
+ if (!items.length)
109
+ continue;
110
+ lines.push(`${section}:`);
111
+ for (const item of items) {
112
+ const id = item.stableId ? `bid:${item.stableId}` : item.id;
113
+ const tags = [item.priority, item.claim ? `claimed: ${item.claim.computer}` : undefined].filter(Boolean);
114
+ lines.push(`${id} ${rowTitle(item.line)} [${rowKeywords(item.line).join(", ")}]${tags.length ? ` (${tags.join("; ")})` : ""}`);
115
+ }
116
+ }
117
+ return lines;
118
+ }
102
119
  export function register(server, ctx) {
103
120
  const { phrenPath, profile, updateFileInIndex } = ctx;
104
121
  const withWriteQueue = (fn) => ctx.withWriteQueue(async () => {
@@ -191,6 +208,18 @@ export function register(server, ctx) {
191
208
  }
192
209
  const requested = limit ?? DEFAULT_TASK_LIMIT;
193
210
  const counts = taskCounts(phrenPath, doc);
211
+ if (clankerEnabled(phrenPath)) {
212
+ const buildRows = (size) => {
213
+ const page = size < requested ? buildTaskView(filtered, status, size, Math.min(done_limit ?? DEFAULT_DONE_LIMIT, size), offset) : view;
214
+ const more = page.truncated ? `\nMore: offset=${(offset ?? 0) + size}` : "";
215
+ return {
216
+ ok: true,
217
+ message: `${buildClankerTaskRows(page.doc, page.includedSections).join("\n")}${more}\n${CLANKER_FETCH_HINT}`,
218
+ data: { project, counts, includedSections: page.includedSections, totalItems: page.totalItems, totalUnpaged: page.totalUnpaged, offset: offset ?? 0, truncated: page.truncated },
219
+ };
220
+ };
221
+ return mcpResponse(shrinkToBudget(requested, buildRows).payload, { compact: true });
222
+ }
194
223
  const buildPage = (size) => {
195
224
  const page = size < requested ? buildTaskView(filtered, status, size, Math.min(done_limit ?? DEFAULT_DONE_LIMIT, size), offset) : view;
196
225
  const sectionCounts = page.includedSections
@@ -241,6 +270,22 @@ export function register(server, ctx) {
241
270
  };
242
271
  if (summary)
243
272
  return mcpResponse(buildPage(requested, true));
273
+ if (clankerEnabled(phrenPath)) {
274
+ const buildRows = (size) => {
275
+ const built = filteredDocs.map(({ doc, filtered }) => {
276
+ const view = buildTaskView(filtered, status, size, Math.min(done_limit ?? DEFAULT_DONE_LIMIT, size), offset);
277
+ return { project: doc.project, view, lines: buildClankerTaskRows(view.doc, view.includedSections) };
278
+ });
279
+ const anyTruncated = built.some(({ view }) => view.truncated);
280
+ return {
281
+ ok: true,
282
+ message: `${built.map(({ lines }) => lines.join("\n")).join("\n\n")}${anyTruncated ? "\nSome lists are capped; pass project, limit or offset for more." : ""}\n${CLANKER_FETCH_HINT}`,
283
+ data: { projects: built.map(({ project, view }) => ({ project, includedSections: view.includedSections, totalItems: view.totalItems, truncated: view.truncated })) },
284
+ };
285
+ };
286
+ // Every project at once is an overview: keep it smaller than one project's list.
287
+ return mcpResponse(shrinkToBudget(requested, buildRows, LIST_RESPONSE_MAX_CHARS / 4).payload, { compact: true });
288
+ }
244
289
  const fitted = shrinkToBudget(requested, (size) => buildPage(size, false));
245
290
  if (JSON.stringify(fitted.payload, null, 2).length <= LIST_RESPONSE_MAX_CHARS)
246
291
  return mcpResponse(fitted.payload);
@@ -71,10 +71,12 @@ interface McpToolResult {
71
71
  * Convert an McpToolResult into the MCP SDK response format.
72
72
  * Single shared implementation — replaces the per-file jsonResponse() duplicates.
73
73
  * Responses over MCP_RESPONSE_MAX_CHARS are replaced by a shortened message;
74
- * `unbounded` opts out for payloads that only make sense whole (exports).
74
+ * `unbounded` opts out for payloads that only make sense whole (exports);
75
+ * `compact` drops the indentation (clanker mode, where whitespace is most of a row).
75
76
  */
76
77
  export declare function mcpResponse(payload: McpToolResult, opts?: {
77
78
  unbounded?: boolean;
79
+ compact?: boolean;
78
80
  }): {
79
81
  content: {
80
82
  type: "text";
@@ -68,10 +68,11 @@ export function resolveStoreForProject(ctx, projectInput, mode = "write") {
68
68
  * Convert an McpToolResult into the MCP SDK response format.
69
69
  * Single shared implementation — replaces the per-file jsonResponse() duplicates.
70
70
  * Responses over MCP_RESPONSE_MAX_CHARS are replaced by a shortened message;
71
- * `unbounded` opts out for payloads that only make sense whole (exports).
71
+ * `unbounded` opts out for payloads that only make sense whole (exports);
72
+ * `compact` drops the indentation (clanker mode, where whitespace is most of a row).
72
73
  */
73
74
  export function mcpResponse(payload, opts = {}) {
74
- const text = JSON.stringify(payload, null, 2);
75
+ const text = opts.compact ? JSON.stringify(payload) : JSON.stringify(payload, null, 2);
75
76
  if (opts.unbounded || text.length <= MCP_RESPONSE_MAX_CHARS)
76
77
  return { content: [{ type: "text", text }] };
77
78
  // Last resort: a client rejects an oversized result outright, so send a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.34",
3
+ "version": "0.3.36",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {