/** * Self Reports: the `report` tool FailproofAI puts into every agent, so an * agent that is stuck can say so. * * This module is the one TypeScript home for everything the feature shares: * the default categories, the tool's description and input schema (identical * text in every implementation — the daemon, the stdio server and both SDKs * build the same string), the recognised tool names, and the effective * settings file `self-report.json` every reader goes through. * * Every top-level name here starts with `selfReport` / `SELF_REPORT`, on * purpose. The CLI ships as one scope-hoisted bundle, and a new top-level name * that matches a local inside a builtin policy makes the bundler rename that * local — which changes the function source the audit cache keys on (see the * note on `screenKit` in tui.ts). The short names the brief asks for * (`describe`, `inputSchema`, `DEFAULT_CATEGORIES`) are export aliases only. * * Only the name/description/settings-read half is used on the hook path, and it * imports nothing beyond `node:fs` and the home resolver. The local-config and * Cloud-enrolment helpers load their modules lazily. */ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from "node:fs"; import { dirname, join } from "node:path"; import { createHash, randomBytes } from "node:crypto"; import { configFile, credentialsFile, failproofaiHome } from "./fp-home"; export { SELF_REPORT_SERVER_NAME, SELF_REPORT_TOOL_NAME, SELF_REPORT_MCP_TOOL_NAME, SELF_REPORT_SDK_TOOL_NAME, SELF_REPORT_DETAIL_MAX, SELF_REPORT_DEFAULT_PORT, SELF_REPORT_SERVER_RECORDS, isSelfReportToolName, isSelfReportCursorCall, selfReportAntigravityWrappedArgs, selfReportClip, selfReportCutDetail, SELF_REPORT_DETAIL_CUT_MARKER, } from "./self-report-names"; import { SELF_REPORT_DEFAULT_PORT, SELF_REPORT_DETAIL_MAX, selfReportClip, selfReportCutDetail } from "./self-report-names"; // ── Categories (contract §2) ──────────────────────────────────────────────── export interface SelfReportCategory { name: string; description: string; } const SELF_REPORT_DEFAULT_CATEGORIES: readonly SelfReportCategory[] = Object.freeze([ { name: "looping", description: "You keep repeating the same or circular steps without making progress." }, { name: "cannot_do_request", description: "The user asked for something you cannot do here: a missing capability, tool or permission, or it is only possible by cheating.", }, { name: "invalid_tool_or_credential", description: "A tool, MCP server, plugin, API key or token you need is broken, invalid, expired or rejected.", }, { name: "missing_context", description: "Information or access you need is missing and you cannot get it yourself. Not for normal clarifying questions.", }, { name: "repeated_tool_failure", description: "A command or tool failed on several distinct attempts and is blocking you. A single error is not enough.", }, { name: "task_failure", description: "You genuinely tried and could not complete the task, or something else blocks you that no other category describes. Not for refusals or policy blocks.", }, ].map((c) => Object.freeze(c))); export { SELF_REPORT_DEFAULT_CATEGORIES, SELF_REPORT_DEFAULT_CATEGORIES as DEFAULT_CATEGORIES }; const SELF_REPORT_NAME_RE = /^[a-z][a-z0-9_]{0,63}$/; const SELF_REPORT_MAX_CATEGORIES = 32; const SELF_REPORT_MAX_DESCRIPTION = 500; export const SELF_REPORT_MAX_GUIDANCE = 2000; export type SelfReportValidation = { ok: true; value: T } | { ok: false; error: string }; /** * Check an org's or a user's category list against contract §2: 1–32 entries, * names `^[a-z][a-z0-9_]{0,63}$` and unique, descriptions 1–500 characters. * Descriptions are trimmed; nothing else is rewritten. */ export function validateSelfReportCategories(input: unknown): SelfReportValidation { if (!Array.isArray(input)) return { ok: false, error: "categories must be a list of {name, description}" }; if (input.length < 1 || input.length > SELF_REPORT_MAX_CATEGORIES) { return { ok: false, error: `categories must have between 1 and ${SELF_REPORT_MAX_CATEGORIES} entries` }; } const seen = new Set(); const out: SelfReportCategory[] = []; for (const [i, raw] of input.entries()) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) { return { ok: false, error: `category ${i + 1} must be an object with name and description` }; } const { name, description } = raw as Record; if (typeof name !== "string" || !SELF_REPORT_NAME_RE.test(name)) { return { ok: false, error: `category ${i + 1}: name must match ^[a-z][a-z0-9_]{0,63}$ (lowercase, digits, underscores)`, }; } if (seen.has(name)) return { ok: false, error: `category "${name}" is listed twice` }; seen.add(name); const desc = typeof description === "string" ? description.trim() : ""; if (desc.length < 1 || desc.length > SELF_REPORT_MAX_DESCRIPTION) { return { ok: false, error: `category "${name}": description must be 1-${SELF_REPORT_MAX_DESCRIPTION} characters` }; } out.push({ name, description: desc }); } return { ok: true, value: out }; } /** Guidance: a string of at most 2000 characters, or nothing. Blank reads as nothing. */ export function validateSelfReportGuidance(input: unknown): SelfReportValidation { if (input === undefined || input === null) return { ok: true, value: null }; if (typeof input !== "string") return { ok: false, error: "guidance must be text" }; const trimmed = input.trim(); if (trimmed.length > SELF_REPORT_MAX_GUIDANCE) { return { ok: false, error: `guidance must be at most ${SELF_REPORT_MAX_GUIDANCE} characters` }; } return { ok: true, value: trimmed === "" ? null : trimmed }; } // ── The tool (contract §3) ────────────────────────────────────────────────── const SELF_REPORT_DESCRIPTION_HEAD = "When you are stuck on something you cannot fix yourself, call this tool once with `category` (one of the categories " + "below) and `detail` (one factual sentence: what is blocking you). It reports to FailproofAI. Call it BEFORE your " + "final answer, for example for a missing, invalid or expired token or API key, a 401 or 403, a command, tool or MCP " + "server that keeps failing, information or access you cannot get, or a request you cannot do here. Do not call it for " + "normal work, clarifying questions or an error you then fixed. One call per distinct problem.\n" + "Reporting does not unblock you and changes no decision: afterwards, work around the problem or tell the user what is " + "blocking you. There is no need to mention this report to the user."; /** The tool description, built from the categories and the optional guidance. */ function describeSelfReportTool( categories: readonly SelfReportCategory[], guidance?: string | null, ): string { const lines = categories.map((c) => `- ${c.name}: ${c.description}`); const body = `${SELF_REPORT_DESCRIPTION_HEAD}\n\nCategories:\n${lines.join("\n")}`; return guidance ? `${body}\n\n${guidance}` : body; } /** The tool's JSON input schema. */ function selfReportInputSchema(categories: readonly SelfReportCategory[]): Record { return { type: "object", properties: { category: { type: "string", enum: categories.map((c) => c.name) }, detail: { type: "string", description: "One factual sentence: what is blocking you." }, }, required: ["category", "detail"], additionalProperties: false, }; } export { describeSelfReportTool, describeSelfReportTool as describe, selfReportInputSchema, selfReportInputSchema as inputSchema }; /** * The MCP server's `instructions` (the initialize result), the same text in the * daemon (crates/fpai-collect/src/self_report.rs `instructions`). * * Claude Code defers MCP tools behind tool search, so the model never reads the * tool's description until it already decided to look for one; a server's * instructions go into the system prompt. One short paragraph naming the * categories, then the org's guidance when set. * * The first sentence says on its own what to do and how: Codex's code mode * lists MCP servers as namespaces and keeps only about the first 250 * characters of a server's instructions and of a tool's description. */ function selfReportInstructions( categories: readonly SelfReportCategory[], guidance?: string | null, ): string { const names = categories.map((c) => c.name).join(", "); const body = "When you are stuck, call failproofai_local's `report` tool once with `category` and `detail` (one factual " + "sentence: what is blocking you). Stuck means something you cannot fix yourself: a missing or expired token or " + "key, a 401 or 403, a command or tool that keeps failing, information you cannot get, a request you cannot do. " + `\`category\` is one of: ${names}. Call it before your final answer, not when the task succeeded. It does not ` + "unblock you, and there is no need to mention it to the user."; return guidance ? `${body}\n\n${guidance}` : body; } export { selfReportInstructions }; /** Exactly what the tool returns (contract §3). */ export const SELF_REPORT_RESULT_TEXT = "Recorded."; /** * A call's arguments as a model sent them (the recorders then resolve the * category with `resolveSelfReportCategory`; a call is never rejected), a missing or empty argument falls back to its first * non-empty alias (`SELF_REPORT_ARG_ALIASES`), else `""`; unknown keys are ignored; detail is cut to 2000 * code points (`selfReportClip`). A category is cut to the same bound so a hostile argument cannot * grow every activity row without limit. * * Accepts the arguments object itself, or a hook's `tool_input` that wraps it * (`{arguments: {...}}`, `{args: {...}}`, or either as a JSON string), because * agents differ in how they hand an MCP call to their hooks. */ export function selfReportArgs(input: unknown, max: number = SELF_REPORT_DETAIL_MAX): { category: string; detail: string } { let args: unknown = input; if (typeof args === "string") args = selfReportParseJson(args); if (args && typeof args === "object" && !Array.isArray(args)) { const rec = args as Record; if (!SELF_REPORT_ARG_KEYS.some((key) => rec[key] !== undefined)) { for (const key of ["arguments", "args", "input", "params"]) { let inner = rec[key]; if (typeof inner === "string") inner = selfReportParseJson(inner); if (inner && typeof inner === "object" && !Array.isArray(inner)) { args = inner; break; } } } } const rec = args && typeof args === "object" && !Array.isArray(args) ? (args as Record) : {}; const category = selfReportArg(rec, "category", SELF_REPORT_ARG_ALIASES.category); const detail = selfReportArg(rec, "detail", SELF_REPORT_ARG_ALIASES.detail); return { category: selfReportClip(category, max), detail: selfReportCutDetail(detail, max), }; } /** * Other names a model uses for an argument when it calls the tool without * loading its schema (seen live: `summary` and `sentence` for `detail`). The * first non-empty one is used when the real argument is missing or empty. * Identical in the daemon (crates/fpai-collect/src/self_report.rs) and both * SDKs; test-fixtures/self-report/arg-aliases.json holds the list for all of them. */ export const SELF_REPORT_ARG_ALIASES = { category: ["type", "kind"], detail: ["summary", "sentence", "message", "description", "reason", "text", "details"], } as const; /** * Keyword rules for a category the model did not name (or named wrongly), in * order; the first rule whose target is on the active list and whose keyword * appears in the lowercased `category + " " + detail` wins. Identical in the * daemon and both SDKs; test-fixtures/self-report/category-inference.json * holds the rules and the cases for all of them. */ export const SELF_REPORT_CATEGORY_RULES: readonly { category: string; keywords: readonly string[] }[] = [ { category: "invalid_tool_or_credential", keywords: ["token", "api key", "apikey", "api_key", "credential", "unauthorized", "unauthenticated", "forbidden", "401", "403", "expired", "revoked", "auth", "password", "secret"], }, { category: "looping", keywords: ["loop", "looping", "circular", "in circles", "repeating the same"] }, { category: "repeated_tool_failure", keywords: ["keeps failing", "keep failing", "repeatedly", "several attempts", "multiple attempts", "retried", "retries", "again and again"], }, { category: "missing_context", keywords: ["missing", "not found", "no information", "not provided", "cannot find", "can't find", "need more information", "unclear"], }, { category: "cannot_do_request", keywords: ["cannot", "can't", "unable", "not possible", "impossible", "not supported", "unsupported", "not allowed"], }, ]; /** The category a report falls back to when nothing matched, if it is listed. */ export const SELF_REPORT_FALLBACK_CATEGORY = "task_failure"; function selfReportIsWordChar(ch: string | undefined): boolean { return ch !== undefined && /[a-z0-9]/.test(ch); } function selfReportHasKeyword(text: string, keyword: string): boolean { for (let at = text.indexOf(keyword); at !== -1; at = text.indexOf(keyword, at + 1)) { if (!selfReportIsWordChar(text[at - 1]) && !selfReportIsWordChar(text[at + keyword.length])) return true; } return false; } /** * The category a report is recorded under: `raw` when it is on `names`, else * the listed name it normalises to (lowercase, trimmed, runs of spaces and * hyphens as `_`), else the first keyword rule (`SELF_REPORT_CATEGORY_RULES`) * that matches the category and detail and targets a listed name, else * `task_failure` when listed, else the first listed name. `inferred` is true * whenever the result is not `raw` itself. An empty list keeps `raw`. */ export function resolveSelfReportCategory( raw: string, detail: string, names: readonly string[], ): { category: string; inferred: boolean } { if (names.length === 0 || names.includes(raw)) return { category: raw, inferred: false }; const normalised = raw.trim().toLowerCase().replace(/[\s-]+/g, "_"); if (names.includes(normalised)) return { category: normalised, inferred: true }; const text = `${raw} ${detail}`.toLowerCase(); for (const rule of SELF_REPORT_CATEGORY_RULES) { if (names.includes(rule.category) && rule.keywords.some((k) => selfReportHasKeyword(text, k))) { return { category: rule.category, inferred: true }; } } return { category: names.includes(SELF_REPORT_FALLBACK_CATEGORY) ? SELF_REPORT_FALLBACK_CATEGORY : names[0], inferred: true }; } const SELF_REPORT_ARG_KEYS: readonly string[] = [ "category", "detail", ...SELF_REPORT_ARG_ALIASES.category, ...SELF_REPORT_ARG_ALIASES.detail, ]; function selfReportArg(rec: Record, key: string, aliases: readonly string[]): string { for (const name of [key, ...aliases]) { const value = rec[name]; const text = value === undefined || value === null ? "" : typeof value === "string" ? value : JSON.stringify(value); if (text) return text; } return ""; } function selfReportParseJson(text: string): unknown { try { return JSON.parse(text); } catch { return undefined; } } // ── The effective settings file (contract §4) ─────────────────────────────── export interface SelfReportEffective { version: 1; enabled: boolean; source: "cloud" | "local"; categories: SelfReportCategory[]; guidance: string | null; mcp: { port: number; url: string }; updatedAt: string; /** * A `cloud` file's enrolment: `selfReportEnrolmentId` of the credential * whose poll the daemon wrote it from. It decides only while this machine is * enrolled as that credential (a file left by a previous org must not keep * recording for the next one). */ enrolment?: string; } /** `$FAILPROOFAI_HOME/self-report.json`. */ export function selfReportSettingsFile(): string { return join(failproofaiHome(), "self-report.json"); } /** The port a local writer records: `FAILPROOFAI_SELF_REPORT_PORT`, else 4319. */ export function selfReportPort(): number { const raw = process.env.FAILPROOFAI_SELF_REPORT_PORT?.trim(); if (raw && /^\d+$/.test(raw)) { const n = Number(raw); if (n > 0 && n < 65536) return n; } return SELF_REPORT_DEFAULT_PORT; } export function selfReportMcpUrl(port: number): string { return `http://127.0.0.1:${port}/mcp`; } /** * Read `self-report.json` exactly as it is on disk. Missing, unparsable or not * version 1 reads as `null`. A file that says enabled but whose category list * is unusable falls back to the defaults (contract §4: "never empty when * enabled; defaults if none given"). * * This is the raw file. Whether Self Reports is ON is `resolveSelfReport()`, * which tells a missing file (on by default off Cloud) from a broken one (off). */ export function readEffectiveSelfReport(path: string = selfReportSettingsFile()): SelfReportEffective | null { let raw: unknown; try { raw = JSON.parse(readFileSync(path, "utf8")); } catch { return null; } if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const rec = raw as Record; if (rec.version !== 1) return null; const cats = validateSelfReportCategories(rec.categories); const guidance = validateSelfReportGuidance(rec.guidance); const mcp = rec.mcp && typeof rec.mcp === "object" && !Array.isArray(rec.mcp) ? (rec.mcp as Record) : {}; const port = typeof mcp.port === "number" && Number.isInteger(mcp.port) && mcp.port > 0 && mcp.port < 65536 ? mcp.port : SELF_REPORT_DEFAULT_PORT; return { version: 1, enabled: rec.enabled === true, source: rec.source === "cloud" ? "cloud" : "local", categories: cats.ok ? cats.value : SELF_REPORT_DEFAULT_CATEGORIES.map((c) => ({ ...c })), guidance: guidance.ok ? guidance.value : null, mcp: { port, url: typeof mcp.url === "string" && mcp.url ? mcp.url : selfReportMcpUrl(port) }, updatedAt: typeof rec.updatedAt === "string" ? rec.updatedAt : "", ...(typeof rec.enrolment === "string" && rec.enrolment ? { enrolment: rec.enrolment } : {}), }; } /** * Whether a settings file that parsed may decide anything (the daemon's * `authoritative`): off Cloud, any file; on a Cloud-enrolled machine, only a * `cloud` file written for the enrolment the machine is under right now. * This machine's own file, a previous org's, one from a daemon that predates * the binding, and any file while the credential cannot be read are set * aside: off until this enrolment's setting is written. */ export function selfReportFileDecides( file: SelfReportEffective, enrolled: () => boolean = selfReportCloudEnrolled, enrolmentId: () => string | null = selfReportEnrolmentId, ): boolean { if (!enrolled()) return true; if (file.source !== "cloud") return false; const current = enrolmentId(); return current !== null && file.enrolment === current; } /** * The settings every reader acts on (contract §4). Self Reports is ON by * default. Identical to the daemon's `effective_settings` * (crates/fpai-collect/src/self_report.rs): * * - the file, when it is there and parses, except, on a Cloud-enrolled * machine, any file but a `cloud` one written for this enrolment * (`selfReportFileDecides`): `null`, off until the daemon writes the org's * setting (enrolling must not leave this machine's own switch, or a * previous org's, in charge); * - an unparsable file, or one in another version: `null`, off (fail safe: a half-written or hand-broken * file must not turn recording on); * - a missing file on a Cloud-enrolled machine: `null`, off until the daemon * writes it from the org's setting; * - a missing file otherwise: on with the default categories, unless * `config.json`'s `selfReport.enabled` is `false` (an explicit off wins). */ export function resolveSelfReport( path: string = selfReportSettingsFile(), enrolled: () => boolean = selfReportCloudEnrolled, enrolmentId: () => string | null = selfReportEnrolmentId, ): SelfReportEffective | null { const presence = selfReportFilePresence(path); // Present: the file decides, except that this machine's own (local) file // does not on a Cloud-enrolled machine, where the organization decides: off // until the daemon writes the org's setting, as with no file. Unreadable is // a broken file: off. if (presence === "present") { const file = readEffectiveSelfReport(path); if (file && !selfReportFileDecides(file, enrolled, enrolmentId)) return null; return file; } if (presence === "unreadable") return null; if (enrolled() || selfReportLocalConfigOff()) return null; return selfReportDefaultSettings(); } /** On, local, the default categories: what a machine with no settings file runs. */ export function selfReportDefaultSettings(): SelfReportEffective { const port = selfReportPort(); return { version: 1, enabled: true, source: "local", categories: SELF_REPORT_DEFAULT_CATEGORIES.map((c) => ({ ...c })), guidance: null, mcp: { port, url: selfReportMcpUrl(port) }, updatedAt: "", }; } /** `config.json`'s `selfReport.enabled` is exactly `false` (sync; the hook path). */ function selfReportLocalConfigOff(): boolean { try { const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false; const block = (raw as Record).selfReport; return !!block && typeof block === "object" && (block as Record).enabled === false; } catch { return false; } } /** * Is this machine Cloud enrolled, for the missing-file rule? Synchronous (the * hook path), and the same answer as the daemon's `Enrolment::resolve` * (cloud_client.rs) so TS and Rust readers agree: `FAILPROOFAI_CLOUD_URL` set; * else, unless `config.json` says `mode.kind == "oss"`, a credential file: * `FAILPROOFAI_CLOUD_CREDENTIALS` when named, else `credentials.json` with a * `cloud` entry, else the layout-1 `cloud.json`. A credential file that cannot * be read or parsed counts as enrolled, as the daemon's does: a missing * `self-report.json` then stays off rather than guessing on. */ export function selfReportCloudEnrolled(): boolean { if (process.env.FAILPROOFAI_CLOUD_URL?.trim()) return true; if (selfReportOssMode()) return false; const override = process.env.FAILPROOFAI_CLOUD_CREDENTIALS; if (override) return selfReportFilePresence(override) !== "missing"; const creds = credentialsFile(); const presence = selfReportFilePresence(creds); if (presence === "missing") return selfReportFilePresence(join(failproofaiHome(), "cloud.json")) !== "missing"; if (presence === "unreadable") return true; try { const raw: unknown = JSON.parse(readFileSync(creds, "utf8")); if (!raw || typeof raw !== "object" || Array.isArray(raw)) return true; const cloud = (raw as Record).cloud; return cloud !== undefined && cloud !== null; } catch { return true; } } /** * The id `self-report.json` is bound to on a Cloud-enrolled machine: the * daemon's `enrolment_id` (crates/fpai-collect/src/self_report.rs) of the * credential `Enrolment::resolve` finds, or null when there is none or it * cannot be read. A SHA-256 over a fixed tag and the length-prefixed URL, * machine id and token exactly as stored, first 16 bytes in hex. */ export function selfReportEnrolmentId(): string | null { const env = (name: string) => process.env[name]?.trim() || undefined; const envUrl = env("FAILPROOFAI_CLOUD_URL"); if (envUrl) { const token = env("FAILPROOFAI_CLOUD_TOKEN"); const machineId = env("FAILPROOFAI_MACHINE_ID"); return token && machineId ? selfReportEnrolmentIdOf(envUrl, machineId, token) : null; } if (selfReportOssMode()) return null; const stored = (path: string): string | null => { try { const raw = JSON.parse(readFileSync(path, "utf8")) as Record; if (raw?.schemaVersion !== 1) return null; const { url, machineId, token } = raw; if (typeof url !== "string" || typeof machineId !== "string" || typeof token !== "string" || !token) return null; return selfReportEnrolmentIdOf(url, machineId, token); } catch { return null; } }; const override = process.env.FAILPROOFAI_CLOUD_CREDENTIALS; if (override) return stored(override); const creds = credentialsFile(); if (selfReportFilePresence(creds) === "missing") return stored(join(failproofaiHome(), "cloud.json")); try { const raw = JSON.parse(readFileSync(creds, "utf8")) as Record; const cloud = raw?.cloud as Record | undefined; if (!cloud || typeof cloud !== "object") return null; const { url, machine_id: machineId, token } = cloud; if (typeof url !== "string" || typeof machineId !== "string" || typeof token !== "string" || !token) return null; return selfReportEnrolmentIdOf(url, machineId, token); } catch { return null; } } /** `enrolment_id` in crates/fpai-collect/src/self_report.rs. */ export function selfReportEnrolmentIdOf(url: string, machineId: string, token: string): string { const h = createHash("sha256"); h.update("failproofai self-report enrolment v1"); for (const part of [url, machineId, token]) { const bytes = Buffer.from(part, "utf8"); const len = Buffer.alloc(8); len.writeBigUInt64BE(BigInt(bytes.length)); h.update(len); h.update(bytes); } return h.digest().subarray(0, 16).toString("hex"); } function selfReportFilePresence(path: string): "present" | "missing" | "unreadable" { try { readFileSync(path); return "present"; } catch (err) { return (err as NodeJS.ErrnoException)?.code === "ENOENT" ? "missing" : "unreadable"; } } function selfReportOssMode(): boolean { try { const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); const mode = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as { mode?: unknown }).mode : undefined; return !!mode && typeof mode === "object" && !Array.isArray(mode) && (mode as { kind?: unknown }).kind === "oss"; } catch { return false; } } /** * Why Self Reports is on or off, in the same order `resolveSelfReport` decides: * `waiting` is a Cloud-enrolled machine with no setting from its org yet, and * `unreadable` a settings file that cannot be read or parsed (both are off). */ export type SelfReportState = "on" | "off" | "waiting" | "unreadable"; export function selfReportSettingsState( path: string = selfReportSettingsFile(), enrolled: () => boolean = selfReportCloudEnrolled, enrolmentId: () => string | null = selfReportEnrolmentId, ): SelfReportState { const presence = selfReportFilePresence(path); if (presence === "unreadable") return "unreadable"; if (presence === "present") { const file = readEffectiveSelfReport(path); if (!file) return "unreadable"; if (!selfReportFileDecides(file, enrolled, enrolmentId)) return "waiting"; return file.enabled ? "on" : "off"; } if (enrolled()) return "waiting"; return selfReportLocalConfigOff() ? "off" : "on"; } /** The settings only when the feature is on (`resolveSelfReport`); `null` otherwise. */ export function readEnabledSelfReport(path?: string): SelfReportEffective | null { const s = resolveSelfReport(path); return s && s.enabled ? s : null; } /** * Write `self-report.json` atomically (tmp + fsync + rename), mode 0644. The * non-Cloud writer; on a Cloud-managed machine the daemon owns this file. * The mode is set explicitly rather than left to the umask: the SDKs read this * file from agent processes that may run as another account. */ export function writeEffectiveSelfReport( input: { enabled: boolean; categories?: readonly SelfReportCategory[] | null; guidance?: string | null }, path: string = selfReportSettingsFile(), ): SelfReportEffective { const port = selfReportPort(); const value: SelfReportEffective = { version: 1, enabled: input.enabled, source: "local", categories: (input.categories && input.categories.length > 0 ? input.categories : SELF_REPORT_DEFAULT_CATEGORIES).map( (c) => ({ name: c.name, description: c.description }), ), guidance: input.guidance ?? null, mcp: { port, url: selfReportMcpUrl(port) }, updatedAt: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), }; const dir = dirname(path); if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 }); const tmp = join(dir, `.self-report.json.${process.pid}.${randomBytes(6).toString("hex")}.tmp`); try { const fd = openSync(tmp, "wx", 0o644); try { writeSync(fd, `${JSON.stringify(value, null, 2)}\n`); fsyncSync(fd); } finally { closeSync(fd); } chmodSync(tmp, 0o644); renameSync(tmp, path); } catch (err) { rmSync(tmp, { force: true }); throw err; } return value; } // ── Local config: `selfReport` in config.json (contract §4) ───────────────── export interface SelfReportLocalConfig { enabled: boolean; categories?: SelfReportCategory[]; guidance?: string; } /** The `selfReport` block of `~/.failproofai/config.json`, or `null` if absent. */ export async function readLocalSelfReportConfig(): Promise { const { readConfigRaw } = await import("./fp-config"); const block = readConfigRaw().raw.selfReport; if (!block || typeof block !== "object" || Array.isArray(block)) return null; const rec = block as Record; const cats = rec.categories === undefined || rec.categories === null ? null : validateSelfReportCategories(rec.categories); const guidance = validateSelfReportGuidance(rec.guidance); return { enabled: rec.enabled === true, ...(cats && cats.ok ? { categories: cats.value } : {}), ...(guidance.ok && guidance.value ? { guidance: guidance.value } : {}), }; } /** * Replace the `selfReport` block, keeping every other key in the file as it * was (the same read-raw-then-write the OTEL settings use, so a key this build * does not know survives). */ export async function writeLocalSelfReportConfig(block: SelfReportLocalConfig): Promise { const [{ readConfigRaw }, { writeConfigFileAtomic }, { configFile }] = await Promise.all([ import("./fp-config"), import("./safe-config-write"), import("./fp-home"), ]); const raw = { ...readConfigRaw().raw }; raw.selfReport = { enabled: block.enabled, ...(block.categories ? { categories: block.categories } : {}), ...(block.guidance ? { guidance: block.guidance } : {}), }; writeConfigFileAtomic(configFile(), `${JSON.stringify(raw, null, 2)}\n`, { backup: false }); } /** * On install (`policies --install`, `config`): make the effective settings file * exist, so every reader (the hooks, the stdio server, the daemon's HTTP * server, the SDKs, `status`) reads the same thing from disk rather than each * applying the missing-file default on its own. * * Writes only when the file is missing and the machine is not Cloud enrolled * (on Cloud the daemon owns the file). It carries config.json's `selfReport` * block when there is one — so an explicit `enabled: false` there is written * as off — and is on with the defaults otherwise. An existing file, even a * broken one, is left alone: it is the user's or the daemon's, and a broken * file reads as off until `self-report enable` / `disable` rewrites it. * Returns what it wrote, or `null` when it wrote nothing. */ export async function ensureSelfReportSettingsFile( path: string = selfReportSettingsFile(), enrolled: () => boolean = selfReportCloudEnrolled, ): Promise { if (selfReportFilePresence(path) !== "missing" || enrolled()) return null; const local = await readLocalSelfReportConfig().catch(() => null); const enabled = !selfReportLocalConfigOff(); return writeEffectiveSelfReport( { enabled, categories: local?.categories ?? null, guidance: local?.guidance ?? null }, path, ); } // ── Cloud enrolment ───────────────────────────────────────────────────────── /** * Whether the daemon takes this machine's settings from FailproofAI Cloud, in * which case Cloud owns `self-report.json` and local enable/disable refuse. * Mirrors the daemon's `Enrolment::resolve` (cloud_client.rs): the * `FAILPROOFAI_CLOUD_URL` environment, or a stored cloud credential on a * machine not switched back to open source (`mode.kind == "oss"`). */ export async function selfReportCloudManaged(): Promise { if (process.env.FAILPROOFAI_CLOUD_URL?.trim()) return true; try { const { readCloudCredentials } = await import("./cloud-enrollment"); if (!readCloudCredentials()) return false; } catch { return false; } try { const { configFile } = await import("./fp-home"); const raw: unknown = JSON.parse(readFileSync(configFile(), "utf8")); const mode = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as { mode?: unknown }).mode : undefined; if (mode && typeof mode === "object" && !Array.isArray(mode) && (mode as { kind?: unknown }).kind === "oss") { return false; } } catch { // Missing or unreadable config does not veto an enrolled machine (the daemon's rule). } return true; }