src/write.js
// write_report: the only code in this agent that writes. It creates ONE new file inside the workspace's
// reports/ folder, never with a protected name (CLAUDE.md, AGENTS.md, package.json, .claude/... see fsguard.js)
// (exclusive "wx" create: an existing file is never replaced; if_exists "suffix" picks report-2.md
// and so on), creates missing folders one level at a time, never through links, and never deletes.
import { writeFileSync, mkdirSync, lstatSync } from "node:fs";
import { createHash } from "node:crypto";
import { ToolError } from "./errors.js";
import { normalizeRel, inspectTarget, folderChain, absOf, checkWritableName } from "./fsguard.js";
const ALLOWED_EXT = /\.(md|markdown|txt|json)$/i;
export const MAX_REPORT_BYTES = 5 * 1024 * 1024;
function freeName(root, rel, field) {
const t = inspectTarget(root, rel, field);
if (!t.exists) return { rel, target: t };
const slash = rel.lastIndexOf("/");
const dir = slash >= 0 ? rel.slice(0, slash + 1) : "";
const name = rel.slice(slash + 1);
const dot = name.lastIndexOf(".");
for (let n = 2; n <= 99; n++) {
const cand = `${dir}${name.slice(0, dot)}-${n}${name.slice(dot)}`;
const ct = inspectTarget(root, cand, field);
if (!ct.exists) return { rel: cand, target: ct, renamed_from: rel };
}
return null;
}
export const REPORTS_DIR = "reports";
export function writeReport(root, input) {
const field = "path";
const rel = normalizeRel(input.path, field);
// Security review C5: only inside the dedicated reports/ folder, and never a name that AI assistants or
// tools read as instructions or configuration (CLAUDE.md, AGENTS.md, package.json, .claude/, ...).
const segs = rel.split("/");
if (segs.length < 2 || segs[0].toLowerCase() !== REPORTS_DIR) throw new ToolError("invalid_path", `${field}: write_report writes only inside the ${REPORTS_DIR}/ folder of the workspace (for example ${REPORTS_DIR}/test-summary.md); got ${rel}.`);
checkWritableName(rel, field);
if (!ALLOWED_EXT.test(rel)) throw new ToolError("invalid_path", `${field}: reports are written as .md, .markdown, .txt or .json files (got ${rel}).`);
const bytes = Buffer.byteLength(input.content, "utf8");
if (bytes > MAX_REPORT_BYTES) throw new ToolError("limit_exceeded", `content is ${bytes} bytes; the limit is ${MAX_REPORT_BYTES}.`);
const pick = input.if_exists === "suffix" ? freeName(root, rel, field) : { rel, target: inspectTarget(root, rel, field) };
if (!pick) throw new ToolError("file_exists", `${rel} and ${rel.replace(/(\.[^.]+)$/, "-2$1")} to -99 already exist; choose another name.`);
if (pick.target.exists) throw new ToolError("file_exists", `${rel} already exists and is never replaced. Choose another path or pass if_exists: "suffix".`);
const created = [];
if (pick.target.missingFolders.length) {
if (input.create_folders === false) throw new ToolError("invalid_path", `${field}: the folder ${pick.target.missingFolders[0]} does not exist (create_folders is false).`);
for (const folder of pick.target.missingFolders) {
const missing = folderChain(root, folder.split("/").slice(0, -1), field);
if (missing.length) throw new ToolError("invalid_path", `${field}: the folder ${missing[0]} is missing.`);
let st = null;
try {
st = lstatSync(absOf(root, folder));
} catch {
/* missing */
}
if (st?.isSymbolicLink()) throw new ToolError("unsafe_path", `${field}: ${folder} is a link; nothing is written through links.`);
if (!st) {
mkdirSync(absOf(root, folder));
created.push(folder);
} else if (!st.isDirectory()) throw new ToolError("invalid_path", `${field}: ${folder} exists and is not a folder.`);
}
}
const final = inspectTarget(root, pick.rel, field); // re-check just before writing
if (final.exists) throw new ToolError("file_exists", `${pick.rel} appeared just before writing; it was not replaced.`);
writeFileSync(final.abs, input.content, { flag: "wx" });
return { path: pick.rel, renamed_from: pick.renamed_from ?? null, bytes, sha256: createHash("sha256").update(input.content).digest("hex"), created_folders: created, written: true };
}