@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
148 lines (147 loc) • 7.37 kB
JavaScript
import * as fs from "node:fs";
import * as path from "node:path";
import { atomicWriteText } from "../phren-paths.js";
import { appendAuditLog, phrenErr, phrenOk, PhrenError } from "../shared.js";
import { withFileLock } from "../shared/governance.js";
import { storeAwareProjectPath } from "../store-routing.js";
import { isValidProjectName } from "../utils.js";
const ADDED_DATE = /\s+_\(added (\d{4}-\d{2}-\d{2})\)_$/;
const EXPLICIT_LIMIT = /\b(?:for\s+now|for\s+the\s+time\s+being|until\s+further\s+notice)\b/i;
const TEMPORARY_WORDING = /\b(?:today|tomorrow|yesterday|temporar(?:y|ily)|until|supersedes?|(?:this|next)\s+(?:week|month|quarter|year))\b/i;
const STANDING_WORDING = /\b(?:always|never|every|each)\b|\b(?:wait|hold)\s+until\b/i;
const EXPLICIT_DATE = /\b(?:\d{4}[-/]\d{1,2}[-/]\d{1,2}|\d{1,2}\/\d{1,2}\/\d{2,4})(?!\d)/;
const MONTH_NAME = "(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)";
const NAMED_DATE = new RegExp(String.raw `\b(?:${MONTH_NAME}\.?\s+\d{1,2}(?:st|nd|rd|th)?|\d{1,2}(?:st|nd|rd|th)?\s+${MONTH_NAME})\b`, "i");
function parseTruthText(text) {
const value = text.replace(/\r\n/g, "\n").trim();
const added = ADDED_DATE.exec(value)?.[1];
return { text: value.replace(ADDED_DATE, "").trimEnd(), added };
}
export function temporaryTruthMarker(text) {
return (EXPLICIT_LIMIT.exec(text) ?? TEMPORARY_WORDING.exec(text) ?? EXPLICIT_DATE.exec(text) ?? NAMED_DATE.exec(text))?.[0];
}
function readTruthFile(file) {
try {
return fs.readFileSync(file, "utf8");
}
catch (err) {
if (err.code === "ENOENT")
return undefined;
throw err;
}
}
/** A stamped line ends an entry. Legacy entries can continue on indented lines. */
export function parseTruthEntries(content) {
const lines = content.split(/(?<=\n)/);
let offset = 0;
const offsets = lines.map((line) => {
const start = offset;
offset += line.length;
return start;
});
const entries = [];
for (let i = 0; i < lines.length; i++) {
if (!lines[i].startsWith("- "))
continue;
const start = offsets[i];
let last = i;
let following = i + 1;
while (!ADDED_DATE.test(lines[last].trimEnd()) && following < lines.length) {
const next = lines[following];
if (!next.trim()) {
following++;
continue;
}
if (!/^[ \t]/.test(next))
break;
last = following++;
}
const end = offsets[last + 1] ?? content.length;
const line = content.slice(start, end).replace(/\r?\n$/, "");
const parsed = parseTruthText(line.slice(2));
const next = lines[following];
const ambiguous = !parsed.added && Boolean(next && !/^(?:- |#{1,6}\s)/.test(next));
entries.push({ ...parsed, line, start, end, ambiguous });
i = last;
}
return entries;
}
/** Remove the given spans in file order and preserve all surrounding bytes. */
export function withoutTruthEntries(content, entries) {
let offset = 0;
const kept = entries.map(({ start, end }) => {
const before = content.slice(offset, start);
offset = end;
return before;
});
return kept.join("") + content.slice(offset);
}
export function readTruthEntries(file) {
return parseTruthEntries(readTruthFile(file) ?? "");
}
function resolveTruthFile(phrenPath, project) {
if (!isValidProjectName(project))
return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
const dir = storeAwareProjectPath(phrenPath, project);
if (!dir || !fs.existsSync(dir))
return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
return phrenOk(path.join(dir, "truths.md"));
}
export function upsertCanonical(phrenPath, project, memory) {
const file = resolveTruthFile(phrenPath, project);
if (!file.ok)
return file;
const text = memory.trim().replace(/^-\s+/, "").replace(/\s*[\r\n]+\s*/g, " ").trim();
if (!text || text === "-")
return phrenErr("Supply the standing rule to pin.", PhrenError.EMPTY_INPUT);
const marker = temporaryTruthMarker(text);
if (marker && (EXPLICIT_LIMIT.test(text) || (!STANDING_WORDING.test(text) && marker.toLowerCase() !== "temporary"))) {
return phrenErr(`Truth looks dated or temporary ("${marker}"). Use add_finding (CLI: phren add-finding) instead.`, PhrenError.VALIDATION_ERROR);
}
const saved = withFileLock(file.data, () => {
const existing = readTruthFile(file.data) ?? `# ${project} Truths\n\n## Truths\n`;
if (parseTruthEntries(existing).some((truth) => truth.text === text))
return false;
const eol = existing.includes("\r\n") ? "\r\n" : "\n";
const today = new Date().toISOString().slice(0, 10);
const line = `- ${text} _(added ${today})_`;
const heading = /^## Truths[ \t]*(?=\r?$)/m;
const updated = heading.test(existing)
? existing.replace(heading, (match) => `${match}${eol}${eol}${line}`)
: `${existing.trimEnd()}${eol}${eol}## Truths${eol}${eol}${line}${eol}`;
atomicWriteText(file.data, updated.endsWith("\n") ? updated : updated + eol);
return true;
});
if (saved)
appendAuditLog(phrenPath, "pin_memory", `project=${project} memory=${JSON.stringify(text)}`);
const warning = marker ? ` Warning: "${marker}" may describe temporary wording. Use add_finding if the rule has an expiry.` : "";
return phrenOk(`Truth saved in ${project}.${warning}`);
}
export function unpinCanonical(phrenPath, project, memory) {
const file = resolveTruthFile(phrenPath, project);
if (!file.ok)
return file;
const input = memory.trim();
const wanted = parseTruthText(input);
const unbulleted = input.startsWith("- ") ? parseTruthText(input.slice(2)) : undefined;
if (!wanted.text)
return phrenErr("Supply the exact truth text to unpin.", PhrenError.EMPTY_INPUT);
const removed = withFileLock(file.data, () => {
const existing = readTruthFile(file.data) ?? "";
const matches = (truth, query) => truth.text === query.text && (query.added === undefined || truth.added === query.added);
const entries = parseTruthEntries(existing).filter((truth) => matches(truth, wanted) || (unbulleted && matches(truth, unbulleted)));
if (entries.length === 0)
return phrenErr(`No matching truth in "${project}". Supply its exact text.`, PhrenError.NOT_FOUND);
if (entries.length > 1) {
return phrenErr("Multiple truths match. Use the complete entry from phren truths, including its bullet and pin date where shown.", PhrenError.VALIDATION_ERROR);
}
if (entries[0].ambiguous) {
return phrenErr("Ambiguous legacy truth boundary. Review the entry in truths.md before removing it.", PhrenError.VALIDATION_ERROR);
}
atomicWriteText(file.data, withoutTruthEntries(existing, entries));
return phrenOk(`Truth unpinned from ${project}.`);
});
if (removed.ok)
appendAuditLog(phrenPath, "unpin_memory", `project=${project}`);
return removed;
}