@phren/cli 0.3.32 → 0.3.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.
@@ -12,7 +12,7 @@ import { resolveAllStores } from "../store-registry.js";
12
12
  import { readFindings, FINDINGS_FILENAME } from "../data/access.js";
13
13
  import { debugLog, runtimeFile, DOC_TYPES, FINDING_TAGS, isMemoryScopeVisible, normalizeMemoryScope, } from "../shared.js";
14
14
  import { FINDING_LIFECYCLE_STATUSES, parseFindingLifecycle, } from "../shared/content.js";
15
- import { decodeStringRow, queryRows, queryDocRows, queryFragmentLinks, logFragmentMiss, extractSnippet, queryDocBySourceKey, normalizeMemoryId, } from "../shared/index.js";
15
+ import { decodeStringRow, queryRows, queryDocRows, queryFragmentLinks, logFragmentMiss, extractSnippet, getDocSourceKey, queryDocBySourceKey, normalizeMemoryId, } from "../shared/index.js";
16
16
  import { runCustomHooks } from "../hooks.js";
17
17
  import { entryScoreKey, getQualityMultiplier, getRetentionPolicy, recordLookupEvents } from "../shared/governance.js";
18
18
  import { bestFindingNodeId } from "../finding-graph-id.js";
@@ -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 { DETAIL_PAGE_CHARS, LIST_TEXT_MAX_CHARS, SUMMARY_MAX_CHARS, SUMMARY_MAX_TRUTHS, clipText, shrinkToBudget, snippetBudget } from "../response-budget.js";
24
25
  /**
25
26
  * Q30: Log zero-result queries to .runtime/search-misses.jsonl.
26
27
  * Strips PII-like tokens (emails, UUIDs, numbers) and keeps only query terms.
@@ -125,7 +126,7 @@ function filterTaskContentByScope(content, activeScope) {
125
126
  return out.join("\n");
126
127
  }
127
128
  // ── Handlers ─────────────────────────────────────────────────────────────────
128
- async function handleGetMemoryDetail(ctx, { id: rawId }) {
129
+ async function handleGetMemoryDetail(ctx, { id: rawId, offset }) {
129
130
  const { phrenPath } = ctx;
130
131
  // Normalize ID: decode URL encoding and normalize path separators
131
132
  let id;
@@ -165,15 +166,27 @@ async function handleGetMemoryDetail(ctx, { id: rawId }) {
165
166
  // Get quality score if available
166
167
  const scoreKey = entryScoreKey(doc.project, doc.filename, doc.content);
167
168
  const qualityMultiplier = getQualityMultiplier(phrenPath, scoreKey);
169
+ // Large documents come back a page at a time; next_offset continues the read.
170
+ const total = doc.content.length;
171
+ const start = Math.min(offset ?? 0, total);
172
+ const end = Math.min(total, start + DETAIL_PAGE_CHARS);
173
+ const content = doc.content.slice(start, end);
174
+ const nextOffset = end < total ? end : null;
175
+ const pageNote = start > 0 || nextOffset !== null
176
+ ? `\n\n[Characters ${start}–${end} of ${total}.${nextOffset !== null ? ` Call again with offset=${nextOffset} for more.` : ""}]`
177
+ : "";
168
178
  return mcpResponse({
169
179
  ok: true,
170
- message: `[${id.slice(4)}] (${doc.type})\n\n${doc.content}`,
180
+ message: `[${id.slice(4)}] (${doc.type})\n\n${content}${pageNote}`,
171
181
  data: {
172
182
  id,
173
183
  project: doc.project,
174
184
  filename: doc.filename,
175
185
  type: doc.type,
176
- content: doc.content,
186
+ content,
187
+ offset: start,
188
+ total_chars: total,
189
+ next_offset: nextOffset,
177
190
  path: doc.path,
178
191
  created_at: createdAt,
179
192
  updated_at: updatedAt,
@@ -367,16 +380,22 @@ async function handleSearchKnowledge(ctx, { query, limit, project, type, tag, si
367
380
  if (rows.length > maxResults) {
368
381
  rows = rows.slice(0, maxResults);
369
382
  }
383
+ // Snippets share one character budget so a response stays well under the
384
+ // client's tool-result limit however long the matched lines are.
385
+ const perResultChars = snippetBudget(rows.length);
370
386
  const results = rows.map((row) => {
371
- const snippet = extractSnippet(row.content, query);
387
+ const snippet = extractSnippet(row.content, query, 5, perResultChars);
372
388
  const lifecycle = row.type === "findings" ? lifecycleByRowKey.get(findingRowKey(row)) : undefined;
373
389
  const federationSource = "federationSource" in row ? row.federationSource : undefined;
374
390
  const symbols = row.type === "findings" ? collectSymbolCitations(row.content) : [];
375
391
  return {
392
+ // Federated rows live in another store's index, which get_memory_detail cannot read.
393
+ ...(federationSource ? {} : { id: `mem:${getDocSourceKey(row, phrenPath)}` }),
376
394
  project: row.project,
377
395
  filename: row.filename,
378
396
  type: row.type,
379
397
  snippet,
398
+ truncated: snippet.length < row.content.length,
380
399
  path: row.path,
381
400
  status: lifecycle?.primaryStatus,
382
401
  statuses: lifecycle?.statuses,
@@ -429,7 +448,8 @@ async function handleSearchKnowledge(ctx, { query, limit, project, type, tag, si
429
448
  }
430
449
  const formatted = results.map((r) => {
431
450
  const fedNote = r.federation_source ? ` [from: ${r.federation_source}]` : "";
432
- return `### ${r.project}/${r.filename} (${r.type})${fedNote}\n${r.snippet}\n\n\`${r.path}\``;
451
+ const more = r.truncated && r.id ? ` · excerpt; full text: get_memory_detail id="${r.id}"` : "";
452
+ return `### ${r.project}/${r.filename} (${r.type})${fedNote}\n${r.snippet}\n\n\`${r.path}\`${more}`;
433
453
  });
434
454
  // Memory synthesis: generate a concise paragraph from top results when requested
435
455
  let synthesis;
@@ -523,9 +543,12 @@ async function handleGetProjectSummary(ctx, { name }) {
523
543
  const claudeDoc = docs.find(doc => doc.type === "claude");
524
544
  const canonicalDoc = docs.find(doc => doc.type === "canonical");
525
545
  const indexedFiles = docs.map(doc => ({ filename: doc.filename, type: doc.type, path: doc.path }));
546
+ const detailHint = (doc) => `get_memory_detail id="mem:${getDocSourceKey(doc, ctx.phrenPath)}"`;
547
+ const summary = summaryDoc ? clipText(summaryDoc.content, SUMMARY_MAX_CHARS) : null;
548
+ const summaryTruncated = summaryDoc ? summary !== summaryDoc.content : false;
526
549
  const parts = [`# ${name}`];
527
550
  if (summaryDoc) {
528
- parts.push(`\n## Summary\n${summaryDoc.content}`);
551
+ parts.push(`\n## Summary\n${summary}${summaryTruncated ? `\n\n[Summary cut at ${SUMMARY_MAX_CHARS} characters; full text: ${detailHint(summaryDoc)}]` : ""}`);
529
552
  }
530
553
  else {
531
554
  parts.push("\n*No summary.md found for this project.*");
@@ -537,7 +560,10 @@ async function handleGetProjectSummary(ctx, { name }) {
537
560
  if (canonicalDoc) {
538
561
  const truthLines = canonicalDoc.content.split("\n").filter((l) => l.startsWith("- "));
539
562
  if (truthLines.length > 0) {
540
- parts.push(`\n## Truths (${truthLines.length})\n${truthLines.join("\n")}`);
563
+ const shown = truthLines.slice(0, SUMMARY_MAX_TRUTHS).map((line) => clipText(line, LIST_TEXT_MAX_CHARS));
564
+ const clipped = truthLines.length > shown.length || shown.some((line, i) => line !== truthLines[i]);
565
+ const more = clipped ? `\n[Truths shortened; full text: ${detailHint(canonicalDoc)}]` : "";
566
+ parts.push(`\n## Truths (${truthLines.length})\n${shown.join("\n")}${more}`);
541
567
  }
542
568
  }
543
569
  const fileList = indexedFiles.map((f) => `- ${f.filename} (${f.type})`).join("\n");
@@ -547,7 +573,8 @@ async function handleGetProjectSummary(ctx, { name }) {
547
573
  message: parts.join("\n"),
548
574
  data: {
549
575
  name,
550
- summary: summaryDoc?.content ?? null,
576
+ summary,
577
+ summaryTruncated,
551
578
  // What the project holds, counted the way every graph counts it.
552
579
  counts: projectMemoryCounts(storeName ? (resolveAllStores(ctx.phrenPath).find((s) => s.name === storeName)?.path ?? ctx.phrenPath) : ctx.phrenPath, lookupName),
553
580
  agentsMdPath: claudeDoc?.path ?? null,
@@ -650,7 +677,7 @@ async function handleListProjects(ctx, { page, page_size }) {
650
677
  data: { projects: projectList, total: allProjects.length, page: pageNum, totalPages, pageSize },
651
678
  });
652
679
  }
653
- async function handleGetFindings(ctx, { project, limit, include_superseded, include_history, status }) {
680
+ async function handleGetFindings(ctx, { project, limit, offset, include_superseded, include_history, status }) {
654
681
  if (!isValidProjectName(project))
655
682
  return mcpResponse({ ok: false, error: `Invalid project name: "${project}"` });
656
683
  const resolved = resolveStoreForProject(ctx, project, "read");
@@ -680,44 +707,54 @@ async function handleGetFindings(ctx, { project, limit, include_superseded, incl
680
707
  : `No findings found for "${project}".`;
681
708
  return mcpResponse({ ok: true, message: msg, data: { project, findings: [], total: 0, status: status ?? null, include_history: includeHistory, historyCount } });
682
709
  }
683
- const capped = filteredItems.slice(0, limit ?? 50).map(entry => ({
684
- ...entry,
685
- symbol: entry.citationData?.symbol,
686
- lifecycle: {
687
- status: entry.status,
688
- status_updated: entry.status_updated,
689
- status_reason: entry.status_reason,
690
- status_ref: entry.status_ref,
691
- },
692
- }));
693
- const lines = capped.map((entry) => {
694
- const metadata = [];
695
- metadata.push(`status=${entry.status}`);
696
- if (entry.taskItem)
697
- metadata.push(`task=${entry.taskItem}`);
698
- if (entry.scope)
699
- metadata.push(`scope=${entry.scope}`);
700
- if (entry.symbol)
701
- metadata.push(`name=${entry.symbol}`);
702
- if (entry.supersedes)
703
- metadata.push(`supersedes="${entry.supersedes.slice(0, 30)}"`);
704
- if (entry.supersededBy)
705
- metadata.push(`superseded_by="${entry.supersededBy.slice(0, 30)}"`);
706
- if (entry.contradicts?.length)
707
- metadata.push(`contradicts=${entry.contradicts.length}`);
708
- if (entry.tier === "archived")
709
- metadata.push("tier=archived");
710
- const idLabel = entry.stableId ? `${entry.id}|fid:${entry.stableId}` : entry.id;
711
- const attribution = formatActorAttribution(entry.actor, entry.machine);
712
- return `- [${idLabel}] ${entry.date}: ${entry.text}${attribution ? ` ${attribution}` : ""}${entry.confidence !== undefined ? ` [confidence ${entry.confidence.toFixed(2)}]` : ""}${metadata.length > 0 ? ` [${metadata.join(" ")}]` : ""}${entry.citation ? ` (${entry.citation})` : ""}`;
713
- });
710
+ const from = offset ?? 0;
711
+ const requested = limit ?? 50;
714
712
  const hiddenHistoryCount = includeHistory ? 0 : historyCount;
715
713
  const historyNote = hiddenHistoryCount > 0 ? ` (${hiddenHistoryCount} historical hidden)` : "";
716
- return mcpResponse({
717
- ok: true,
718
- message: `Findings for ${project} (${capped.length}/${filteredItems.length})${historyNote}:\n` + lines.join("\n"),
719
- data: { project, findings: capped, total: filteredItems.length, status: status ?? null, include_history: includeHistory, historyCount: hiddenHistoryCount },
720
- });
714
+ const buildPage = (size) => {
715
+ const capped = filteredItems.slice(from, from + size).map(entry => ({
716
+ ...entry,
717
+ symbol: entry.citationData?.symbol,
718
+ lifecycle: {
719
+ status: entry.status,
720
+ status_updated: entry.status_updated,
721
+ status_reason: entry.status_reason,
722
+ status_ref: entry.status_ref,
723
+ },
724
+ }));
725
+ const lines = capped.map((entry) => {
726
+ const metadata = [];
727
+ metadata.push(`status=${entry.status}`);
728
+ if (entry.taskItem)
729
+ metadata.push(`task=${entry.taskItem}`);
730
+ if (entry.scope)
731
+ metadata.push(`scope=${entry.scope}`);
732
+ if (entry.symbol)
733
+ metadata.push(`name=${entry.symbol}`);
734
+ if (entry.supersedes)
735
+ metadata.push(`supersedes="${entry.supersedes.slice(0, 30)}"`);
736
+ if (entry.supersededBy)
737
+ metadata.push(`superseded_by="${entry.supersededBy.slice(0, 30)}"`);
738
+ if (entry.contradicts?.length)
739
+ metadata.push(`contradicts=${entry.contradicts.length}`);
740
+ if (entry.tier === "archived")
741
+ metadata.push("tier=archived");
742
+ const idLabel = entry.stableId ? `${entry.id}|fid:${entry.stableId}` : entry.id;
743
+ const attribution = formatActorAttribution(entry.actor, entry.machine);
744
+ return `- [${idLabel}] ${entry.date}: ${entry.text}${attribution ? ` ${attribution}` : ""}${entry.confidence !== undefined ? ` [confidence ${entry.confidence.toFixed(2)}]` : ""}${metadata.length > 0 ? ` [${metadata.join(" ")}]` : ""}${entry.citation ? ` (${entry.citation})` : ""}`;
745
+ });
746
+ const nextOffset = from + capped.length < filteredItems.length ? from + capped.length : null;
747
+ const pageNote = size < requested && nextOffset !== null
748
+ ? `\n\n[Cut to ${capped.length} rows to fit the response budget. Continue with offset=${nextOffset}.]`
749
+ : "";
750
+ const range = from > 0 ? `${from + 1}–${from + capped.length} of ${filteredItems.length}` : `${capped.length}/${filteredItems.length}`;
751
+ return {
752
+ ok: true,
753
+ message: `Findings for ${project} (${range})${historyNote}:\n` + lines.join("\n") + pageNote,
754
+ data: { project, findings: capped, total: filteredItems.length, offset: from, next_offset: nextOffset, status: status ?? null, include_history: includeHistory, historyCount: hiddenHistoryCount },
755
+ };
756
+ };
757
+ return mcpResponse(shrinkToBudget(requested, buildPage).payload);
721
758
  }
722
759
  async function handleStoreList(ctx) {
723
760
  const { phrenPath } = ctx;
@@ -756,12 +793,13 @@ async function handleStoreList(ctx) {
756
793
  export function register(server, ctx) {
757
794
  server.registerTool("get_memory_detail", {
758
795
  title: "◆ phren · memory detail",
759
- description: "Fetch the full content of a specific memory entry by its ID. Use this after receiving a compact " +
760
- "memory index from the hook-prompt (when PHREN_FEATURE_PROGRESSIVE_DISCLOSURE is enabled). " +
796
+ 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. " +
761
798
  "The id format is `mem:project/path/to/file.md` as shown in the memory index.",
762
799
  inputSchema: z.object({
763
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`). " +
764
- "Returned by the hook-prompt compact index when PHREN_FEATURE_PROGRESSIVE_DISCLOSURE=1."),
801
+ "Returned by search_knowledge results and the hook-prompt compact index."),
802
+ 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.`),
765
803
  }),
766
804
  }, (params) => handleGetMemoryDetail(ctx, params));
767
805
  server.registerTool("search_knowledge", {
@@ -804,7 +842,8 @@ export function register(server, ctx) {
804
842
  description: "List recent findings for a project without requiring a search query.",
805
843
  inputSchema: z.object({
806
844
  project: z.string().describe("Project name."),
807
- limit: z.number().int().min(1).max(200).optional().describe("Max rows to return (default 50)."),
845
+ limit: z.number().int().min(1).max(200).optional().describe("Max rows to return (default 50). Fewer come back if the rows would not fit the response budget."),
846
+ offset: z.number().int().min(0).optional().describe("Skip the first N rows. Use with limit to page."),
808
847
  include_superseded: z.boolean().optional().describe("If true, include findings that have been superseded by a newer finding (hidden by default)."),
809
848
  include_history: z.boolean().optional().describe("When true, include historical findings (superseded/retracted). Default false."),
810
849
  status: z.enum(FINDING_LIFECYCLE_STATUSES).optional().describe("Filter findings by lifecycle status."),
@@ -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 { LIST_RESPONSE_MAX_CHARS, LIST_TEXT_MAX_CHARS, clipTail, shrinkToBudget } from "../response-budget.js";
17
18
  const TASK_SECTION_ORDER = ["Active", "Queue", "Done"];
18
19
  const DEFAULT_TASK_LIMIT = 20;
19
20
  /** Done items are historical — cap tightly by default to avoid large responses. */
@@ -62,6 +63,11 @@ function buildTaskView(doc, status, limit, doneLimit, offset) {
62
63
  else {
63
64
  items[section] = sliced;
64
65
  }
66
+ // Context is an append-only log that can run to many KB; lists show its
67
+ // latest notes and a single-task lookup returns it whole.
68
+ items[section] = items[section].map((item) => item.context && item.context.length > LIST_TEXT_MAX_CHARS
69
+ ? { ...item, context: clipTail(item.context, LIST_TEXT_MAX_CHARS), contextTruncated: true }
70
+ : item);
65
71
  }
66
72
  const totalItems = TASK_SECTION_ORDER.reduce((sum, section) => sum + items[section].length, 0);
67
73
  return {
@@ -105,7 +111,7 @@ export function register(server, ctx) {
105
111
  });
106
112
  server.registerTool("get_tasks", {
107
113
  title: "◆ phren · tasks",
108
- description: "Get tasks. Defaults to Active and Queue sections only. Pass status='all' to include Done items.",
114
+ description: "Get tasks. Defaults to Active and Queue sections only. Pass status='all' to include Done items. Lists show the latest part of a long Context (contextTruncated: true); look up one task by project and id for its full context.",
109
115
  inputSchema: z.object({
110
116
  project: z.string().optional().describe("Project name. Omit to get all projects."),
111
117
  id: z.string().optional().describe("Task ID like A1, Q3, D2. Requires project."),
@@ -167,7 +173,8 @@ export function register(server, ctx) {
167
173
  if (!result.ok)
168
174
  return mcpResponse({ ok: false, error: result.error });
169
175
  const doc = result.data;
170
- const view = buildTaskView(filterTaskDoc(phrenPath, doc, { responsibility, readiness }), status, limit, done_limit, offset);
176
+ const filtered = filterTaskDoc(phrenPath, doc, { responsibility, readiness });
177
+ const view = buildTaskView(filtered, status, limit, done_limit, offset);
171
178
  if (!fs.existsSync(doc.path)) {
172
179
  return mcpResponse({
173
180
  ok: true,
@@ -182,42 +189,63 @@ export function register(server, ctx) {
182
189
  data: { project, counts: taskCounts(phrenPath, doc), includedSections: view.includedSections, totalItems: view.totalItems, summary: true },
183
190
  });
184
191
  }
185
- const sectionCounts = view.includedSections
186
- .map((s) => `${s}: ${view.doc.items[s].length}/${doc.items[s].length}`)
187
- .join(", ");
188
- const paginationNote = view.truncated
189
- ? `\n\n_${sectionCounts} (offset ${offset ?? 0}). Use offset/limit to page._`
190
- : (offset ? `\n\n_Page offset: ${offset}. ${sectionCounts}._` : "");
191
- return mcpResponse({
192
- ok: true,
193
- message: `## ${project}\n${taskMarkdown(view.doc)}${paginationNote}`,
194
- data: { project, counts: taskCounts(phrenPath, doc), items: Object.fromEntries(TASK_SECTION_ORDER.map(section => [section, view.doc.items[section].map(entry => taskView(phrenPath, doc, entry))])), issues: doc.issues, includedSections: view.includedSections, totalItems: view.totalItems, totalUnpaged: view.totalUnpaged, offset: offset ?? 0, truncated: view.truncated },
195
- });
192
+ const requested = limit ?? DEFAULT_TASK_LIMIT;
193
+ const counts = taskCounts(phrenPath, doc);
194
+ const buildPage = (size) => {
195
+ const page = size < requested ? buildTaskView(filtered, status, size, Math.min(done_limit ?? DEFAULT_DONE_LIMIT, size), offset) : view;
196
+ const sectionCounts = page.includedSections
197
+ .map((s) => `${s}: ${page.doc.items[s].length}/${doc.items[s].length}`)
198
+ .join(", ");
199
+ const budgetNote = size < requested ? ` Cut to ${size} per section to fit the response budget.` : "";
200
+ const paginationNote = page.truncated
201
+ ? `\n\n_${sectionCounts} (offset ${offset ?? 0}).${budgetNote} Use offset/limit to page._`
202
+ : (offset ? `\n\n_Page offset: ${offset}. ${sectionCounts}._` : "");
203
+ return {
204
+ ok: true,
205
+ message: `## ${project}\n${taskMarkdown(page.doc)}${paginationNote}`,
206
+ data: { project, counts, items: Object.fromEntries(TASK_SECTION_ORDER.map(section => [section, page.doc.items[section].map(entry => taskView(phrenPath, doc, entry))])), issues: doc.issues, includedSections: page.includedSections, totalItems: page.totalItems, totalUnpaged: page.totalUnpaged, offset: offset ?? 0, truncated: page.truncated },
207
+ };
208
+ };
209
+ return mcpResponse(shrinkToBudget(requested, buildPage).payload);
196
210
  }
197
211
  // All projects
198
212
  const docs = readTasksAcrossProjects(phrenPath, profile);
199
213
  if (!docs.length)
200
214
  return mcpResponse({ ok: true, message: "No tasks found.", data: { projects: [] } });
201
- const views = docs.map((doc) => ({ project: doc.project, doc, view: buildTaskView(filterTaskDoc(phrenPath, doc, { responsibility, readiness }), status, limit, done_limit, offset), issues: doc.issues }));
202
- const anyTruncated = views.some(({ view }) => view.truncated);
203
- let parts;
204
- if (summary) {
205
- parts = views.map(({ view, doc }) => buildTaskSummary(view.doc, view.includedSections, phrenPath, doc));
206
- }
207
- else {
208
- parts = views.map(({ project, view }) => `## ${project}\n${taskMarkdown(view.doc)}`);
209
- }
210
- const truncationNote = anyTruncated && !summary ? `\n\n_Results capped (Active/Queue: ${limit ?? DEFAULT_TASK_LIMIT}, Done: ${done_limit ?? DEFAULT_DONE_LIMIT}). Pass limit/done_limit to see more._` : "";
211
- const projectData = views.map(({ project, doc, view, issues }) => ({
212
- project,
213
- counts: taskCounts(phrenPath, doc),
214
- items: Object.fromEntries(TASK_SECTION_ORDER.map(section => [section, view.doc.items[section].map(entry => taskView(phrenPath, doc, entry))])),
215
- issues,
216
- includedSections: view.includedSections,
217
- totalItems: view.totalItems,
218
- truncated: view.truncated,
219
- }));
220
- return mcpResponse({ ok: true, message: parts.join("\n\n") + truncationNote, data: { projects: projectData, summary: summary || false } });
215
+ const filteredDocs = docs.map((doc) => ({ doc, filtered: filterTaskDoc(phrenPath, doc, { responsibility, readiness }) }));
216
+ const requested = limit ?? DEFAULT_TASK_LIMIT;
217
+ const buildPage = (size, asSummary, note = "") => {
218
+ const doneCap = size < requested ? Math.min(done_limit ?? DEFAULT_DONE_LIMIT, size) : done_limit ?? DEFAULT_DONE_LIMIT;
219
+ const views = filteredDocs.map(({ doc, filtered }) => ({ project: doc.project, doc, view: buildTaskView(filtered, status, size, doneCap, offset), issues: doc.issues }));
220
+ const anyTruncated = views.some(({ view }) => view.truncated);
221
+ let parts;
222
+ if (asSummary) {
223
+ parts = views.map(({ view, doc }) => buildTaskSummary(view.doc, view.includedSections, phrenPath, doc));
224
+ }
225
+ else {
226
+ parts = views.map(({ project, view }) => `## ${project}\n${taskMarkdown(view.doc)}`);
227
+ }
228
+ const budgetNote = size < requested ? " Cut to fit the response budget; pass project to see one project's tasks." : "";
229
+ const truncationNote = anyTruncated && !asSummary ? `\n\n_Results capped (Active/Queue: ${size}, Done: ${doneCap}).${budgetNote} Pass limit/done_limit to see more._` : "";
230
+ // Summaries are counts and titles only, so they carry no item rows.
231
+ const projectData = views.map(({ project, doc, view, issues }) => ({
232
+ project,
233
+ counts: taskCounts(phrenPath, doc),
234
+ ...(asSummary ? {} : { items: Object.fromEntries(TASK_SECTION_ORDER.map(section => [section, view.doc.items[section].map(entry => taskView(phrenPath, doc, entry))])) }),
235
+ issues,
236
+ includedSections: view.includedSections,
237
+ totalItems: view.totalItems,
238
+ truncated: view.truncated,
239
+ }));
240
+ return { ok: true, message: parts.join("\n\n") + truncationNote + note, data: { projects: projectData, summary: asSummary } };
241
+ };
242
+ if (summary)
243
+ return mcpResponse(buildPage(requested, true));
244
+ const fitted = shrinkToBudget(requested, (size) => buildPage(size, false));
245
+ if (JSON.stringify(fitted.payload, null, 2).length <= LIST_RESPONSE_MAX_CHARS)
246
+ return mcpResponse(fitted.payload);
247
+ // Too many projects to list in full: fall back to per-project summaries.
248
+ return mcpResponse(buildPage(requested, true, "\n\n_Every project's full task list does not fit one response, so this is the summary. Pass project for a project's tasks._"));
221
249
  });
222
250
  server.registerTool("add_task", {
223
251
  title: "◆ phren · add task",
@@ -70,8 +70,12 @@ interface McpToolResult {
70
70
  /**
71
71
  * Convert an McpToolResult into the MCP SDK response format.
72
72
  * Single shared implementation — replaces the per-file jsonResponse() duplicates.
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).
73
75
  */
74
- export declare function mcpResponse(payload: McpToolResult): {
76
+ export declare function mcpResponse(payload: McpToolResult, opts?: {
77
+ unbounded?: boolean;
78
+ }): {
75
79
  content: {
76
80
  type: "text";
77
81
  text: string;
@@ -1,6 +1,7 @@
1
1
  import { parseStoreQualified } from "../store-routing.js";
2
2
  import { describeUnavailableStore, resolveAllStores } from "../store-registry.js";
3
3
  import { logger } from "../logger.js";
4
+ import { MCP_RESPONSE_MAX_CHARS, clipText } from "../response-budget.js";
4
5
  /**
5
6
  * Error raised when a project is claimed by a store that is attached on this
6
7
  * machine but whose directory is missing. Distinct class so callers
@@ -66,7 +67,22 @@ export function resolveStoreForProject(ctx, projectInput, mode = "write") {
66
67
  /**
67
68
  * Convert an McpToolResult into the MCP SDK response format.
68
69
  * Single shared implementation — replaces the per-file jsonResponse() duplicates.
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).
69
72
  */
70
- export function mcpResponse(payload) {
71
- return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
73
+ export function mcpResponse(payload, opts = {}) {
74
+ const text = JSON.stringify(payload, null, 2);
75
+ if (opts.unbounded || text.length <= MCP_RESPONSE_MAX_CHARS)
76
+ return { content: [{ type: "text", text }] };
77
+ // Last resort: a client rejects an oversized result outright, so send a
78
+ // shortened message and say how to narrow the call instead.
79
+ const note = `[Response cut: ${text.length} characters is over the ${MCP_RESPONSE_MAX_CHARS}-character limit. Narrow the request (limit, offset, project, summary) or fetch a single item.]`;
80
+ const shortened = {
81
+ ok: payload.ok,
82
+ ...(payload.error !== undefined ? { error: clipText(payload.error, 2000) } : {}),
83
+ ...(payload.errorCode !== undefined ? { errorCode: payload.errorCode } : {}),
84
+ message: `${clipText(payload.message ?? "", Math.floor(MCP_RESPONSE_MAX_CHARS / 3))}\n\n${note}`,
85
+ data: { truncated: true, originalChars: text.length },
86
+ };
87
+ return { content: [{ type: "text", text: JSON.stringify(shortened, null, 2) }] };
72
88
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.32",
3
+ "version": "0.3.34",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {