@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
120 lines (119 loc) • 5.37 kB
JavaScript
// One line per prompt the hook saw, in `.runtime/recall-trace.jsonl`: what recall
// matched and injected, or why it injected nothing. Local runtime state, never synced.
import * as fs from "fs";
import * as path from "path";
import { runtimeDir } from "../phren-paths.js";
import { debugLog } from "../shared.js";
import { errorMessage } from "../utils.js";
const TRACE_FILE = "recall-trace.jsonl";
// About two weeks of prompts on a busy computer; trimmed to the newest lines past the byte cap.
const MAX_TRACE_LINES = 5000;
const ROTATE_BYTES = 4_000_000;
const MAX_FLOOR_ROWS = 12;
const MAX_PROMPT_CHARS = 160;
export function recallTraceFile(phrenPath) {
return path.join(runtimeDir(phrenPath), TRACE_FILE);
}
function storeRelative(phrenPath, file) {
const rel = path.relative(phrenPath, file);
return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel.split(path.sep).join("/") : file;
}
function round(value) {
return Math.round(value * 1000) / 1000;
}
function clampPrompt(prompt) {
const flat = prompt.replace(/\s+/g, " ").trim();
return flat.length <= MAX_PROMPT_CHARS ? flat : `${flat.slice(0, MAX_PROMPT_CHARS - 1)}…`;
}
/** The trace line for a prompt recall ran on. `injected` is what the hook finally printed. */
export function traceEntryFromResult(phrenPath, prompt, result, injected, extra = {}) {
return {
at: new Date().toISOString(),
...(extra.session ? { session: extra.session } : {}),
project: result.detectedProject,
prompt: clampPrompt(prompt),
keywords: result.keywords,
intent: result.intent,
abstained: result.abstained,
candidates: result.candidates.length,
floor: result.floor.slice(0, MAX_FLOOR_ROWS).map((row) => ({
path: storeRelative(phrenPath, row.path),
passed: row.passed,
reason: row.reason,
distinct: row.distinct,
rarity: round(row.rarity),
overlap: round(row.overlap),
matched: row.matched,
})),
injected: injected.map((row) => ({ path: storeRelative(phrenPath, row.path), key: row.key, type: row.type, ...(row.id ? { id: row.id } : {}) })),
suppressedRepeats: result.suppressedRepeats,
tokens: result.usedTokens,
budget: result.tokenBudget,
ms: { ...(extra.indexMs !== undefined ? { index: extra.indexMs } : {}), search: result.stageMs.searchMs, trust: result.stageMs.trustMs, rank: result.stageMs.rankMs, select: result.stageMs.selectMs },
};
}
/** The trace line for a prompt the hook stopped on before recall. */
export function skippedTraceEntry(prompt, skipped, project, session) {
return { at: new Date().toISOString(), ...(session ? { session } : {}), project, prompt: clampPrompt(prompt), skipped };
}
// Best-effort append, trimmed to the newest lines past the byte cap: a log failure never breaks the hook or a tool.
function appendCapped(file, entry, rotateBytes, maxLines) {
try {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.appendFileSync(file, `${JSON.stringify(entry)}\n`);
}
catch (err) {
debugLog(`${path.basename(file)} write failed: ${errorMessage(err)}`);
return;
}
try {
if (fs.statSync(file).size <= rotateBytes)
return;
const kept = fs.readFileSync(file, "utf8").split("\n").filter(Boolean).slice(-maxLines);
const tmp = `${file}.tmp-${process.pid}`;
fs.writeFileSync(tmp, `${kept.join("\n")}\n`);
fs.renameSync(tmp, file);
}
catch (err) {
debugLog(`${path.basename(file)} rotation failed: ${errorMessage(err)}`);
}
}
// Every parsed line with a string `at`, oldest first; a torn line from a concurrent append is skipped.
function readLines(file) {
if (!fs.existsSync(file))
return [];
const out = [];
for (const line of fs.readFileSync(file, "utf8").split("\n")) {
if (!line)
continue;
try {
const parsed = JSON.parse(line);
if (parsed && typeof parsed.at === "string")
out.push(parsed);
}
catch { /* torn line */ }
}
return out;
}
/** Append one entry. Best-effort: a trace failure never breaks the hook. */
export function recordRecallTrace(phrenPath, entry) {
appendCapped(recallTraceFile(phrenPath), entry, ROTATE_BYTES, MAX_TRACE_LINES);
}
/** Every parsed entry, oldest first; malformed lines are skipped. */
export function readRecallTrace(phrenPath) {
return readLines(recallTraceFile(phrenPath));
}
// ── Opens: which ids an agent fetched with get_memory_detail, per session, to pair with clanker injections ──
const OPENS_FILE = "memory-detail-opens.jsonl";
const OPENS_ROTATE_BYTES = 1_000_000;
export function memoryOpensFile(phrenPath) {
return path.join(runtimeDir(phrenPath), OPENS_FILE);
}
/** One get_memory_detail call; Claude Code passes its session id to the MCP server, and without one there is nothing to pair. */
export function recordMemoryOpen(phrenPath, id, session = process.env.CLAUDE_CODE_SESSION_ID) {
if (session)
appendCapped(memoryOpensFile(phrenPath), { at: new Date().toISOString(), session, id }, OPENS_ROTATE_BYTES, MAX_TRACE_LINES);
}
export function readMemoryOpens(phrenPath) {
return readLines(memoryOpensFile(phrenPath));
}