@phren/cli 0.3.33 → 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.
- package/dist/bridge/usage.d.ts +7 -0
- package/dist/bridge/usage.js +15 -1
- package/dist/bridge-hook.mjs +18 -4
- package/dist/cli/search.js +6 -1
- package/dist/index-query.d.ts +6 -1
- package/dist/index-query.js +22 -3
- package/dist/response-budget.d.ts +47 -0
- package/dist/response-budget.js +86 -0
- package/dist/tools/data.js +2 -1
- package/dist/tools/search.js +89 -50
- package/dist/tools/tasks.js +61 -33
- package/dist/tools/types.d.ts +5 -1
- package/dist/tools/types.js +18 -2
- package/package.json +1 -1
package/dist/bridge/usage.d.ts
CHANGED
|
@@ -154,6 +154,9 @@ export declare const CLAUDE_REPORT_MAX_AGE_MS: number;
|
|
|
154
154
|
* phone's cards, rings or widgets.
|
|
155
155
|
*/
|
|
156
156
|
export declare function settleClaudeUsage(usage: AccountUsage, now: number): AccountUsage;
|
|
157
|
+
/** `opencode stats` scans OpenCode's whole database, several CPU-seconds on a
|
|
158
|
+
* busy machine, for a rolling seven-day cost that barely moves in a minute. */
|
|
159
|
+
export declare const OPENCODE_STATS_REUSE_MS: number;
|
|
157
160
|
export declare class AccountUsageReader {
|
|
158
161
|
private readCodex;
|
|
159
162
|
private now;
|
|
@@ -170,6 +173,8 @@ export declare class AccountUsageReader {
|
|
|
170
173
|
private claudePending;
|
|
171
174
|
private spendingCached;
|
|
172
175
|
private spendingPending;
|
|
176
|
+
private openCodeCached?;
|
|
177
|
+
private openCodePending?;
|
|
173
178
|
constructor(readCodex?: typeof readCodexLimits, now?: () => number, readClaudeLive?: (now: Date, home: ClaudeHome) => Promise<AccountUsage | undefined>, readOpenCode?: (now: Date) => Promise<AccountUsage>, readOpenRouter?: (now: Date) => Promise<AccountUsage | undefined>, readOpenCodeGo?: (now: Date) => Promise<AccountUsage>, readCopilot?: (now: Date) => Promise<AccountUsage>, platform?: NodeJS.Platform, readElevenLabs?: (now: Date) => Promise<AccountUsage | undefined>);
|
|
174
179
|
/** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
|
|
175
180
|
* before accounts existed, since older phones refuse two rows of one source. */
|
|
@@ -180,6 +185,8 @@ export declare class AccountUsageReader {
|
|
|
180
185
|
limits(allAccounts?: boolean): Promise<AccountUsage[]>;
|
|
181
186
|
/** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
|
|
182
187
|
private spending;
|
|
188
|
+
/** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
|
|
189
|
+
private openCode;
|
|
183
190
|
/** Live first, so the phone's minute-by-minute poll keeps Claude current
|
|
184
191
|
* even when Claude Code is not running; the local snapshot is the backup.
|
|
185
192
|
* Off macOS a non-default home reads its own credentials file; on macOS it
|
package/dist/bridge/usage.js
CHANGED
|
@@ -727,6 +727,9 @@ export function settleClaudeUsage(usage, now) {
|
|
|
727
727
|
const since = usage.updatedAt?.slice(0, 10);
|
|
728
728
|
return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
|
|
729
729
|
}
|
|
730
|
+
/** `opencode stats` scans OpenCode's whole database, several CPU-seconds on a
|
|
731
|
+
* busy machine, for a rolling seven-day cost that barely moves in a minute. */
|
|
732
|
+
export const OPENCODE_STATS_REUSE_MS = 10 * 60_000;
|
|
730
733
|
export class AccountUsageReader {
|
|
731
734
|
readCodex;
|
|
732
735
|
now;
|
|
@@ -743,6 +746,8 @@ export class AccountUsageReader {
|
|
|
743
746
|
claudePending = new Map();
|
|
744
747
|
spendingCached = new Map();
|
|
745
748
|
spendingPending = new Map();
|
|
749
|
+
openCodeCached;
|
|
750
|
+
openCodePending;
|
|
746
751
|
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage, platform = process.platform, readElevenLabs = liveElevenLabsUsage) {
|
|
747
752
|
this.readCodex = readCodex;
|
|
748
753
|
this.now = now;
|
|
@@ -784,7 +789,7 @@ export class AccountUsageReader {
|
|
|
784
789
|
if (!cached || this.now() - cached.at >= 60_000) {
|
|
785
790
|
const at = this.now();
|
|
786
791
|
if (!this.spendingPending.has(key)) {
|
|
787
|
-
const pending = Promise.all([this.
|
|
792
|
+
const pending = Promise.all([this.openCode(at), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)),
|
|
788
793
|
includeCopilot ? this.readCopilot(new Date(at)) : Promise.resolve(undefined),
|
|
789
794
|
includeElevenLabs ? this.readElevenLabs(new Date(at)).catch(() => undefined) : Promise.resolve(undefined)])
|
|
790
795
|
.then(([openCode, openCodeGo, openRouter, copilot, elevenLabs]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), ...(copilot ? [copilot] : []), ...(elevenLabs ? [elevenLabs] : [])])
|
|
@@ -795,6 +800,15 @@ export class AccountUsageReader {
|
|
|
795
800
|
}
|
|
796
801
|
return this.spendingPending.get(key) ?? cached.value;
|
|
797
802
|
}
|
|
803
|
+
/** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
|
|
804
|
+
openCode(at) {
|
|
805
|
+
if (this.openCodeCached && at - this.openCodeCached.at < OPENCODE_STATS_REUSE_MS)
|
|
806
|
+
return Promise.resolve(this.openCodeCached.value);
|
|
807
|
+
this.openCodePending ??= this.readOpenCode(new Date(at))
|
|
808
|
+
.then(value => { this.openCodeCached = { at, value }; return value; })
|
|
809
|
+
.finally(() => { this.openCodePending = undefined; });
|
|
810
|
+
return this.openCodePending;
|
|
811
|
+
}
|
|
798
812
|
/** Live first, so the phone's minute-by-minute poll keeps Claude current
|
|
799
813
|
* even when Claude Code is not running; the local snapshot is the backup.
|
|
800
814
|
* Off macOS a non-default home reads its own credentials file; on macOS it
|
package/dist/bridge-hook.mjs
CHANGED
|
@@ -37420,7 +37420,7 @@ var init_package_metadata = __esm({
|
|
|
37420
37420
|
__dirname = path37.dirname(fileURLToPath2(import.meta.url));
|
|
37421
37421
|
ROOT = path37.join(__dirname, "..");
|
|
37422
37422
|
PACKAGE_JSON_PATH = path37.join(ROOT, "package.json");
|
|
37423
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
37423
|
+
BUNDLED_VERSION = true ? "0.3.34" : "0.0.0";
|
|
37424
37424
|
PACKAGE_JSON = readPackageJson();
|
|
37425
37425
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
37426
37426
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -38824,7 +38824,7 @@ async function captureClaudeUsage(original) {
|
|
|
38824
38824
|
});
|
|
38825
38825
|
}
|
|
38826
38826
|
}
|
|
38827
|
-
var exec7, claudeFile, safeText, openCodeAuthFile, GO_GATEWAY, GO_KEY_MESSAGE, GO_WINDOWS, openCodeLogDir, refusalScans, FIRST_SCAN_BYTES, clock, goPlanCached, goPlanPending, claudeCredentialsFile, CLAUDE_REPORT_MAX_AGE_MS, AccountUsageReader, quote2;
|
|
38827
|
+
var exec7, claudeFile, safeText, openCodeAuthFile, GO_GATEWAY, GO_KEY_MESSAGE, GO_WINDOWS, openCodeLogDir, refusalScans, FIRST_SCAN_BYTES, clock, goPlanCached, goPlanPending, claudeCredentialsFile, CLAUDE_REPORT_MAX_AGE_MS, OPENCODE_STATS_REUSE_MS, AccountUsageReader, quote2;
|
|
38828
38828
|
var init_usage = __esm({
|
|
38829
38829
|
"src/bridge/usage.ts"() {
|
|
38830
38830
|
"use strict";
|
|
@@ -38856,6 +38856,7 @@ var init_usage = __esm({
|
|
|
38856
38856
|
clock = (iso) => `${iso.slice(11, 16)} UTC`;
|
|
38857
38857
|
claudeCredentialsFile = (home) => path43.join(home?.dir ?? claudeConfigDir(), ".credentials.json");
|
|
38858
38858
|
CLAUDE_REPORT_MAX_AGE_MS = 3 * 864e5;
|
|
38859
|
+
OPENCODE_STATS_REUSE_MS = 10 * 6e4;
|
|
38859
38860
|
AccountUsageReader = class {
|
|
38860
38861
|
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = (now2) => readOpenCodeUsage("opencode", now2), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage, platform = process.platform, readElevenLabs = liveElevenLabsUsage) {
|
|
38861
38862
|
this.readCodex = readCodex;
|
|
@@ -38883,6 +38884,8 @@ var init_usage = __esm({
|
|
|
38883
38884
|
claudePending = /* @__PURE__ */ new Map();
|
|
38884
38885
|
spendingCached = /* @__PURE__ */ new Map();
|
|
38885
38886
|
spendingPending = /* @__PURE__ */ new Map();
|
|
38887
|
+
openCodeCached;
|
|
38888
|
+
openCodePending;
|
|
38886
38889
|
/** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
|
|
38887
38890
|
* before accounts existed, since older phones refuse two rows of one source. */
|
|
38888
38891
|
async read(sources, allAccounts = false) {
|
|
@@ -38920,7 +38923,7 @@ var init_usage = __esm({
|
|
|
38920
38923
|
const at = this.now();
|
|
38921
38924
|
if (!this.spendingPending.has(key4)) {
|
|
38922
38925
|
const pending = Promise.all([
|
|
38923
|
-
this.
|
|
38926
|
+
this.openCode(at),
|
|
38924
38927
|
this.readOpenCodeGo(new Date(at)),
|
|
38925
38928
|
this.readOpenRouter(new Date(at)),
|
|
38926
38929
|
includeCopilot ? this.readCopilot(new Date(at)) : Promise.resolve(void 0),
|
|
@@ -38936,6 +38939,17 @@ var init_usage = __esm({
|
|
|
38936
38939
|
}
|
|
38937
38940
|
return this.spendingPending.get(key4) ?? cached3.value;
|
|
38938
38941
|
}
|
|
38942
|
+
/** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
|
|
38943
|
+
openCode(at) {
|
|
38944
|
+
if (this.openCodeCached && at - this.openCodeCached.at < OPENCODE_STATS_REUSE_MS) return Promise.resolve(this.openCodeCached.value);
|
|
38945
|
+
this.openCodePending ??= this.readOpenCode(new Date(at)).then((value2) => {
|
|
38946
|
+
this.openCodeCached = { at, value: value2 };
|
|
38947
|
+
return value2;
|
|
38948
|
+
}).finally(() => {
|
|
38949
|
+
this.openCodePending = void 0;
|
|
38950
|
+
});
|
|
38951
|
+
return this.openCodePending;
|
|
38952
|
+
}
|
|
38939
38953
|
/** Live first, so the phone's minute-by-minute poll keeps Claude current
|
|
38940
38954
|
* even when Claude Code is not running; the local snapshot is the backup.
|
|
38941
38955
|
* Off macOS a non-default home reads its own credentials file; on macOS it
|
|
@@ -64368,7 +64382,7 @@ async function main() {
|
|
|
64368
64382
|
return askpass2(args[1]);
|
|
64369
64383
|
}
|
|
64370
64384
|
const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
|
|
64371
|
-
return runBridge2(args, "0.3.
|
|
64385
|
+
return runBridge2(args, "0.3.34");
|
|
64372
64386
|
}
|
|
64373
64387
|
main().then((code) => {
|
|
64374
64388
|
process.exitCode = code;
|
package/dist/cli/search.js
CHANGED
|
@@ -7,6 +7,7 @@ import { logger } from "../logger.js";
|
|
|
7
7
|
import { keywordFallbackSearch } from "../core/search.js";
|
|
8
8
|
import { recordLookupEvents } from "../shared/governance.js";
|
|
9
9
|
import { bestFindingNodeId } from "../finding-graph-id.js";
|
|
10
|
+
import { snippetBudget } from "../response-budget.js";
|
|
10
11
|
const MAX_HISTORY = 20;
|
|
11
12
|
const SEARCH_TYPE_ALIASES = {
|
|
12
13
|
skills: "skill",
|
|
@@ -270,10 +271,14 @@ export async function runSearch(opts, phrenPath, profile) {
|
|
|
270
271
|
lines.push("");
|
|
271
272
|
}
|
|
272
273
|
const hits = [];
|
|
274
|
+
// Same per-result budget as search_knowledge: store lines can run to many KB.
|
|
275
|
+
const perResultChars = snippetBudget(rows.length);
|
|
273
276
|
for (const row of rows) {
|
|
274
|
-
const snippet = extractSnippet(row.content, opts.query, 7);
|
|
277
|
+
const snippet = extractSnippet(row.content, opts.query, 7, perResultChars);
|
|
275
278
|
lines.push(`[${row.project}/${row.filename}] (${row.type})`);
|
|
276
279
|
lines.push(snippet);
|
|
280
|
+
if (row.path && snippet !== extractSnippet(row.content, opts.query, 7))
|
|
281
|
+
lines.push(` (shortened; full text: ${row.path})`);
|
|
277
282
|
lines.push("");
|
|
278
283
|
hits.push({ project: row.project, filename: row.filename, type: row.type, snippet, path: row.path, content: row.content });
|
|
279
284
|
}
|
package/dist/index-query.d.ts
CHANGED
|
@@ -30,4 +30,9 @@ export declare function rowToDocWithRowid(row: DbRow): {
|
|
|
30
30
|
export declare function queryRows(db: SqlJsDatabase, sql: string, params: (string | number)[]): DbRow[] | null;
|
|
31
31
|
export declare function queryDocRows(db: SqlJsDatabase, sql: string, params: (string | number)[]): DocRow[] | null;
|
|
32
32
|
export declare function queryDocBySourceKey(db: SqlJsDatabase, phrenPath: string, sourceKey: string): DocRow | null;
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Pick the lines of `content` that best match `query`. With `maxChars`, the
|
|
35
|
+
* result is also held to that many characters: store lines can run to several
|
|
36
|
+
* KB, so a few lines alone do not bound a snippet.
|
|
37
|
+
*/
|
|
38
|
+
export declare function extractSnippet(content: string, query: string, lines?: number, maxChars?: number): string;
|
package/dist/index-query.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as path from "path";
|
|
2
2
|
import { debugLog } from "./shared.js";
|
|
3
3
|
import { logger } from "./logger.js";
|
|
4
|
+
import { clipText, focusText } from "./response-budget.js";
|
|
4
5
|
function describeSqlValue(value) {
|
|
5
6
|
if (value === null)
|
|
6
7
|
return "null";
|
|
@@ -102,14 +103,20 @@ export function queryDocBySourceKey(db, phrenPath, sourceKey) {
|
|
|
102
103
|
return null;
|
|
103
104
|
return rows.find((row) => getDocSourceKey(row, phrenPath) === sourceKey) ?? null;
|
|
104
105
|
}
|
|
105
|
-
|
|
106
|
+
/**
|
|
107
|
+
* Pick the lines of `content` that best match `query`. With `maxChars`, the
|
|
108
|
+
* result is also held to that many characters: store lines can run to several
|
|
109
|
+
* KB, so a few lines alone do not bound a snippet.
|
|
110
|
+
*/
|
|
111
|
+
export function extractSnippet(content, query, lines = 5, maxChars) {
|
|
106
112
|
const terms = query.replace(/\b(AND|OR|NOT|NEAR)\b/gi, "")
|
|
107
113
|
.replace(/['"]/g, "")
|
|
108
114
|
.split(/\s+/)
|
|
109
115
|
.filter((term) => term.length > 1)
|
|
110
116
|
.map((term) => term.toLowerCase());
|
|
111
117
|
if (terms.length === 0) {
|
|
112
|
-
|
|
118
|
+
const head = content.split("\n").slice(0, lines);
|
|
119
|
+
return maxChars === undefined ? head.join("\n") : fitSnippetLines(head, -1, terms, maxChars);
|
|
113
120
|
}
|
|
114
121
|
const contentLines = content.split("\n");
|
|
115
122
|
const headingIndices = [];
|
|
@@ -167,5 +174,17 @@ export function extractSnippet(content, query, lines = 5) {
|
|
|
167
174
|
}
|
|
168
175
|
const start = Math.max(0, bestIdx - 1);
|
|
169
176
|
const end = Math.min(contentLines.length, bestIdx + lines - 1);
|
|
170
|
-
|
|
177
|
+
const picked = contentLines.slice(start, end);
|
|
178
|
+
return maxChars === undefined ? picked.join("\n") : fitSnippetLines(picked, bestIdx - start, terms, maxChars);
|
|
179
|
+
}
|
|
180
|
+
/** Give the matched line most of the budget, centred on the match; clip the context lines. */
|
|
181
|
+
function fitSnippetLines(picked, bestIdx, terms, maxChars) {
|
|
182
|
+
const joined = picked.join("\n");
|
|
183
|
+
if (joined.length <= maxChars)
|
|
184
|
+
return joined;
|
|
185
|
+
const others = picked.length - (bestIdx >= 0 ? 1 : 0);
|
|
186
|
+
const bestBudget = bestIdx >= 0 ? (others > 0 ? Math.ceil(maxChars * 0.6) : maxChars) : 0;
|
|
187
|
+
const otherBudget = others > 0 ? Math.max(40, Math.floor((maxChars - bestBudget - picked.length) / others)) : 0;
|
|
188
|
+
const fitted = picked.map((line, i) => i === bestIdx ? focusText(line, terms, bestBudget) : clipText(line, otherBudget));
|
|
189
|
+
return clipText(fitted.join("\n"), maxChars);
|
|
171
190
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Size budgets for tool output.
|
|
3
|
+
*
|
|
4
|
+
* Claude Code rejects an MCP tool result over about 25k tokens, and the call
|
|
5
|
+
* then fails outright. Store text is long-lined (task Context fields and
|
|
6
|
+
* consolidated reference lines run to several KB), so line-based snippets and
|
|
7
|
+
* per-item limits alone do not bound a response. These budgets are in
|
|
8
|
+
* characters of the serialized result; JSON-escaped markdown is roughly 3–4
|
|
9
|
+
* characters per token.
|
|
10
|
+
*/
|
|
11
|
+
/** Most characters one search result's snippet may use. */
|
|
12
|
+
export declare const SNIPPET_MAX_CHARS = 1200;
|
|
13
|
+
/** Characters shared by all snippets in one search response (each also appears in `data`). */
|
|
14
|
+
export declare const SNIPPETS_TOTAL_CHARS = 6000;
|
|
15
|
+
/** Floor for a snippet when many results split the total. */
|
|
16
|
+
export declare const SNIPPET_MIN_CHARS = 240;
|
|
17
|
+
/** Per-field cap for text shown in list views (task context, truths). */
|
|
18
|
+
export declare const LIST_TEXT_MAX_CHARS = 300;
|
|
19
|
+
/** Most characters of a project's summary.md shown by get_project_summary. */
|
|
20
|
+
export declare const SUMMARY_MAX_CHARS = 6000;
|
|
21
|
+
/** Most truths listed by get_project_summary. */
|
|
22
|
+
export declare const SUMMARY_MAX_TRUTHS = 20;
|
|
23
|
+
/** Target ceiling for a list response before it shrinks its page size. */
|
|
24
|
+
export declare const LIST_RESPONSE_MAX_CHARS = 40000;
|
|
25
|
+
/** Page size for full-document reads (get_memory_detail). */
|
|
26
|
+
export declare const DETAIL_PAGE_CHARS = 16000;
|
|
27
|
+
/** Hard ceiling for any MCP response; past this the payload is replaced, not sent. */
|
|
28
|
+
export declare const MCP_RESPONSE_MAX_CHARS = 60000;
|
|
29
|
+
/** Per-result snippet budget when `count` results share one response. */
|
|
30
|
+
export declare function snippetBudget(count: number): number;
|
|
31
|
+
/** Cut `text` to at most `max` characters, ending with an ellipsis when cut. */
|
|
32
|
+
export declare function clipText(text: string, max: number): string;
|
|
33
|
+
/** Cut `text` to at most `max` characters, keeping the end (for append-only notes). */
|
|
34
|
+
export declare function clipTail(text: string, max: number): string;
|
|
35
|
+
/**
|
|
36
|
+
* Cut `text` to at most `max` characters, keeping a window around the first
|
|
37
|
+
* occurrence of any term (lowercase). Falls back to the start when no term hits.
|
|
38
|
+
*/
|
|
39
|
+
export declare function focusText(text: string, terms: string[], max: number): string;
|
|
40
|
+
/**
|
|
41
|
+
* Build a list payload, halving its page size until the serialized result fits
|
|
42
|
+
* `maxChars` (or the size reaches 1). `build` receives the size to use.
|
|
43
|
+
*/
|
|
44
|
+
export declare function shrinkToBudget<T>(initialSize: number, build: (size: number) => T, maxChars?: number): {
|
|
45
|
+
payload: T;
|
|
46
|
+
size: number;
|
|
47
|
+
};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Size budgets for tool output.
|
|
3
|
+
*
|
|
4
|
+
* Claude Code rejects an MCP tool result over about 25k tokens, and the call
|
|
5
|
+
* then fails outright. Store text is long-lined (task Context fields and
|
|
6
|
+
* consolidated reference lines run to several KB), so line-based snippets and
|
|
7
|
+
* per-item limits alone do not bound a response. These budgets are in
|
|
8
|
+
* characters of the serialized result; JSON-escaped markdown is roughly 3–4
|
|
9
|
+
* characters per token.
|
|
10
|
+
*/
|
|
11
|
+
/** Most characters one search result's snippet may use. */
|
|
12
|
+
export const SNIPPET_MAX_CHARS = 1200;
|
|
13
|
+
/** Characters shared by all snippets in one search response (each also appears in `data`). */
|
|
14
|
+
export const SNIPPETS_TOTAL_CHARS = 6000;
|
|
15
|
+
/** Floor for a snippet when many results split the total. */
|
|
16
|
+
export const SNIPPET_MIN_CHARS = 240;
|
|
17
|
+
/** Per-field cap for text shown in list views (task context, truths). */
|
|
18
|
+
export const LIST_TEXT_MAX_CHARS = 300;
|
|
19
|
+
/** Most characters of a project's summary.md shown by get_project_summary. */
|
|
20
|
+
export const SUMMARY_MAX_CHARS = 6000;
|
|
21
|
+
/** Most truths listed by get_project_summary. */
|
|
22
|
+
export const SUMMARY_MAX_TRUTHS = 20;
|
|
23
|
+
/** Target ceiling for a list response before it shrinks its page size. */
|
|
24
|
+
export const LIST_RESPONSE_MAX_CHARS = 40_000;
|
|
25
|
+
/** Page size for full-document reads (get_memory_detail). */
|
|
26
|
+
export const DETAIL_PAGE_CHARS = 16_000;
|
|
27
|
+
/** Hard ceiling for any MCP response; past this the payload is replaced, not sent. */
|
|
28
|
+
export const MCP_RESPONSE_MAX_CHARS = 60_000;
|
|
29
|
+
/** Per-result snippet budget when `count` results share one response. */
|
|
30
|
+
export function snippetBudget(count) {
|
|
31
|
+
if (count <= 0)
|
|
32
|
+
return SNIPPET_MAX_CHARS;
|
|
33
|
+
return Math.max(SNIPPET_MIN_CHARS, Math.min(SNIPPET_MAX_CHARS, Math.floor(SNIPPETS_TOTAL_CHARS / count)));
|
|
34
|
+
}
|
|
35
|
+
/** Cut `text` to at most `max` characters, ending with an ellipsis when cut. */
|
|
36
|
+
export function clipText(text, max) {
|
|
37
|
+
if (text.length <= max)
|
|
38
|
+
return text;
|
|
39
|
+
if (max <= 1)
|
|
40
|
+
return "…".slice(0, max);
|
|
41
|
+
return `${text.slice(0, max - 1).trimEnd()}…`;
|
|
42
|
+
}
|
|
43
|
+
/** Cut `text` to at most `max` characters, keeping the end (for append-only notes). */
|
|
44
|
+
export function clipTail(text, max) {
|
|
45
|
+
if (text.length <= max)
|
|
46
|
+
return text;
|
|
47
|
+
if (max <= 1)
|
|
48
|
+
return "…".slice(0, max);
|
|
49
|
+
return `…${text.slice(text.length - (max - 1)).trimStart()}`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Cut `text` to at most `max` characters, keeping a window around the first
|
|
53
|
+
* occurrence of any term (lowercase). Falls back to the start when no term hits.
|
|
54
|
+
*/
|
|
55
|
+
export function focusText(text, terms, max) {
|
|
56
|
+
if (text.length <= max)
|
|
57
|
+
return text;
|
|
58
|
+
const lower = text.toLowerCase();
|
|
59
|
+
let hit = -1;
|
|
60
|
+
for (const term of terms) {
|
|
61
|
+
const idx = lower.indexOf(term);
|
|
62
|
+
if (idx !== -1 && (hit === -1 || idx < hit))
|
|
63
|
+
hit = idx;
|
|
64
|
+
}
|
|
65
|
+
if (hit <= 0)
|
|
66
|
+
return clipText(text, max);
|
|
67
|
+
// Leave a third of the window as lead-in before the match.
|
|
68
|
+
const room = max - 2;
|
|
69
|
+
let start = Math.max(0, hit - Math.floor(room / 3));
|
|
70
|
+
const end = Math.min(text.length, start + room);
|
|
71
|
+
start = Math.max(0, end - room);
|
|
72
|
+
return `${start > 0 ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Build a list payload, halving its page size until the serialized result fits
|
|
76
|
+
* `maxChars` (or the size reaches 1). `build` receives the size to use.
|
|
77
|
+
*/
|
|
78
|
+
export function shrinkToBudget(initialSize, build, maxChars = LIST_RESPONSE_MAX_CHARS) {
|
|
79
|
+
let size = initialSize;
|
|
80
|
+
let payload = build(size);
|
|
81
|
+
while (size > 1 && JSON.stringify(payload, null, 2).length > maxChars) {
|
|
82
|
+
size = Math.max(1, Math.floor(size / 2));
|
|
83
|
+
payload = build(size);
|
|
84
|
+
}
|
|
85
|
+
return { payload, size };
|
|
86
|
+
}
|
package/dist/tools/data.js
CHANGED
|
@@ -79,7 +79,8 @@ export function register(server, ctx) {
|
|
|
79
79
|
exported.agentsMd = instructions;
|
|
80
80
|
exported.claudeMd = instructions; // Deprecated export alias for older clients.
|
|
81
81
|
}
|
|
82
|
-
|
|
82
|
+
// An export is only useful whole, so it is exempt from the response cap.
|
|
83
|
+
return mcpResponse({ ok: true, message: `Exported project "${project}".`, data: exported }, { unbounded: true });
|
|
83
84
|
});
|
|
84
85
|
server.registerTool("import_project", {
|
|
85
86
|
title: "◆ phren · import",
|
package/dist/tools/search.js
CHANGED
|
@@ -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${
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
684
|
-
|
|
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
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
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
|
|
760
|
-
"
|
|
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
|
|
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."),
|
package/dist/tools/tasks.js
CHANGED
|
@@ -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
|
|
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
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
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",
|
package/dist/tools/types.d.ts
CHANGED
|
@@ -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;
|
package/dist/tools/types.js
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|