import { type Config } from '../config/config.js'; export declare function spoolDir(dataDir: string): string; export declare function spoolQuarantineDir(dataDir: string): string; export interface SpoolStats { /** Cumulative count of envelopes ever written via writeToSpool — the * denominator for the doctor quarantine canary (ADR-015 rule 6: state the * denominator, not a bare count). Never decremented — this is a lifetime * counter, not a current-depth gauge (listSpoolFiles/readdir already give * current depth). */ totalSpooled: number; /** Cumulative count of envelopes ever quarantined. */ totalQuarantined: number; /** * False when `.stats.json` is missing/corrupt AND there is independent * on-disk evidence the spool has actually been used (the spool dir holds * something besides the stats file itself). In that combination the * counter is not "genuinely zero," it is unreadable — ADR-015 rule 6: * "0 of 0" must never render identically to "denominator unknown." A * fresh install (spool dir absent, or present but otherwise empty) is * `true` — a missing counter there IS a real zero, not a broken one. */ statsHealthy: boolean; } /** Best-effort read — a missing/corrupt stats file (e.g. a fresh install, or * a torn write from a killed process — this file is NOT written via the * tmp+rename atomic pattern, since it's observability, not durable content) * reads back as zeros rather than throwing. See `SpoolStats.statsHealthy` * doc for why a corrupt-but-otherwise-empty spool dir still counts as * healthy while a corrupt-and-non-empty one does not. */ export declare function readSpoolStats(dataDir: string): SpoolStats; /** * Recursively redact every STRING VALUE in `value` — any field, any depth, * through arrays and plain objects — leaving object KEYS and non-string * primitives (numbers, booleans, null) untouched. Pure; never mutates * `value`. Used ONLY by `sweepQuarantineRedaction` below — quarantined files * are dead (nothing reads them but this sweep), so redacting every string * indiscriminately, including a high-entropy `session_id`, is safe there. * The live write path (`writeToSpool`) uses the schema-aware * `redactSpooledEnvelope` (src/ingest/spool-schema-guard.ts) instead — see * that module's doc for why a bare walk like this one is NOT safe there. * * Review fix (2026-07-13): the first cut of `sweepQuarantineRedaction` * tried to be shape-agnostic by running `redactIfEnabled` over the fully * SERIALIZED text of a parseable envelope (structural pass + second raw- * text pass). That is unsafe for JSON: `redactIfEnabled`'s entropy detector * tokenizes on whitespace, and a JSON value with no internal whitespace — * e.g. `"session_id": "proxy-",` — tokenizes as `"proxy-",` * INCLUDING the surrounding quotes and trailing comma, since nothing * whitespace-separates them from the value. A high-entropy match on that * token gets replaced WHOLESALE — quotes and comma included — with a bare, * unquoted `[REDACTED:...]` placeholder, corrupting the JSON. Confirmed * reproducible on every real proxy envelope (`session_id: proxy-${randomUUID()}`, * src/capture/proxy.ts `buildProxyEnvelope`) — not an edge case, the common * case. Worse, the sweep still reported `redacted: 1` (success) while having * destroyed the file's structure. * * This function is the fix: it operates on the DECODED value tree, never on * serialized text, so it structurally CANNOT touch a JSON delimiter — * `redactIfEnabled` only ever receives one already-isolated string at a * time, with no surrounding quote/comma/brace characters attached, and * `JSON.stringify` re-quotes/re-escapes the result correctly afterward. * * Over-redaction note (quarantine only): the entropy detector has * pre-existing false positives on legitimate high-entropy identifiers — a * bare `proxy-` session_id, scanned in isolation, often scores above * the threshold and becomes a placeholder. That is tolerable HERE and only * here, because quarantined files are dead. It would NOT be tolerable on the * live write path, where `session_id` is a required identifier the drain * uses for the session upsert — a placeholder still satisfies * `z.string().min(1)`, so the schema would pass and session identity would * be destroyed silently with no error anywhere. `writeToSpool` therefore * does NOT call this function — it calls `redactSpooledEnvelope` instead * (see above). * * Depth: capped at MAX_WALK_DEPTH. Recursion is bounded by a number we chose, * not by whatever the stack happens to allow — a RangeError's threshold varies * with the runtime and with how deep the caller already is, and (crucially) * vitest's worker stack is deeper than the daemon's, so an uncapped walk is * untestable by construction. Exceeding the cap throws WalkTooDeepError, which * the caller must NOT confuse with "this file isn't JSON". */ export declare class WalkTooDeepError extends Error { constructor(depth: number); } /** Bounded well below the ~1.8k depth at which a plain `node` process (how the * daemon actually runs) overflows its stack in this walk. Real envelopes nest * a handful of levels; anything past this is malformed or hostile. */ export declare const MAX_WALK_DEPTH = 200; export declare function redactValuesDeep(value: unknown, config: Config, depth?: number): unknown; /** * Write `body` (a JSON-serializable envelope) to the spool keyed by * `idempotencyKey`, via tmp-file + atomic rename — a reader can never * observe a torn/partial file. Re-writing the same key is a same-path * overwrite, not a duplicate (AC-2). Returns the final spool file path. * * `config` (default `defaultConfig()`, which ships `security.redaction. * enabled: true`) drives `redactSpooledEnvelope` * (src/ingest/spool-schema-guard.ts) — applied BEFORE the bytes are * serialized, so redaction covers every path out of this function, * including one that later fails schema validation and gets quarantined * (see module doc). Real callers (src/cli/capture.ts, src/capture/proxy.ts) * pass the operator's actual resolved config so a custom entropy threshold, * custom patterns, or an explicit opt-out are honored identically to the * daemon's own ingest-time redaction; the default exists so a caller that * forgets to pass one fails safe (redaction ON) rather than silently open. * * `redactSpooledEnvelope` is schema-aware — it protects `session_id` and * every other field `CanonicalIngestSchema` defines as structural, while * still redacting free-text content and anything the schema doesn't * recognize at all. This was NOT always true here: two earlier designs of * this write path's redaction (a bare "redact every string" walk, and * before that a four-field allowlist) each got one half of the problem * right and the other half wrong — see spool-schema-guard.ts's module doc * for the full history before touching this again. */ export declare function writeToSpool(dataDir: string, idempotencyKey: string, body: unknown, config?: Config): string; export interface SpoolFile { path: string; /** The idempotency key — the filename stem (without `.json`). */ key: string; size: number; } /** List drainable spool files — excludes the `.quarantine/` subdir and any * in-flight tmp file (dotfile-prefixed, per writeToSpool above). */ export declare function listSpoolFiles(dataDir: string): SpoolFile[]; /** * Move a poison/oversize spool file into `ingest-spool/.quarantine/` (AC-5), * writing a sibling `.reason.txt` so the reason is auditable on disk. * Best-effort: if the source already vanished (raced another drain tick), * this is a no-op rather than a throw. */ export declare function quarantineSpoolFile(dataDir: string, file: SpoolFile, reason: string): void; /** Delete a successfully-drained spool file. Best-effort — already-gone is fine. */ export declare function deleteSpoolFile(file: SpoolFile): void; /** * 7 days — matches the existing `ingestIdempotency.retentionDays: 7` default * (src/config/config.ts) already used elsewhere in this same ingest * subsystem, rather than the longer 30-day `purge.restoreWindowDays` used * for reversible user-facing deletions. Deliberately shorter: quarantine is * a heightened-risk location by construction (module doc — the selection * effect means it disproportionately holds secrets), and the doctor canary * below (checkSpoolQuarantine, src/doctor/checks.ts) surfaces its age every * run, so an operator has ample warning before a file ever ages out. */ export declare const DEFAULT_QUARANTINE_TTL_MS: number; export interface QuarantinePruneResult { removed: number; remaining: number; } /** * Delete quarantine files (and their `.reason.txt` sidecar) older than * `maxAgeMs`. Called once per spool-drain tick (src/ingest/spool-drain.ts) — * cheap (a readdir + one stat per quarantined key; real installs quarantine * rarely) so running it every tick rather than on a separate timer is fine. * Content is already redacted at spool-write time (see module doc), so this * is purely a retention/hygiene sweep, not a second redaction pass. */ export declare function pruneExpiredQuarantine(dataDir: string, maxAgeMs?: number): QuarantinePruneResult; export interface QuarantineRedactionSweepResult { /** `.json` files inspected. */ scanned: number; /** Files whose on-disk content changed (a redaction was applied and * written back). */ redacted: number; /** Subset of `redacted` that could not be JSON-parsed and were redacted * via the raw-text path instead of the structural per-field walk. */ unparseable: number; /** Files that could not be read or safely rewritten — left untouched, * original content intact (never deleted on a write failure). */ failed: number; /** Valid JSON that exceeded MAX_WALK_DEPTH and so could not be walked. * * These are LEFT UNTOUCHED — deliberately NOT handed to the raw-text path. * Distinct from `unparseable`: that means "not JSON"; this means "JSON we * could not safely process". Collapsing the two is exactly the bug this * counter exists to make visible — see sweepQuarantineRedaction. */ unwalkable: number; } /** * Finding 2 (2026-07-13 fast-follow): #225 redacts everything written to * the spool from that point forward, but content already sitting in * `.quarantine/` from BEFORE #225 was never touched — it keeps its original * unredacted bytes until `pruneExpiredQuarantine` ages it out at the 7-day * TTL, and that prune only runs if a spool-drain tick actually fires. This * is precisely the module doc's "most likely place on disk for a live * credential to sit indefinitely" — the one thing #225 left untouched. * * Called once per daemon boot (src/cli/serve.ts, alongside the existing * spool-drain boot pass) — NOT per drain tick, since re-scanning the same * already-redacted quarantine directory 2880 times a day (30s cadence) buys * nothing once every file in it has already been rewritten once. * * Idempotent by construction, so a repeat run (e.g. a second boot before * anything new was quarantined) is safe: `redactIfEnabled` skips spans * already occupied by a `[REDACTED:...]` placeholder (src/redact/index.ts * `protectedRanges`), so re-redacting already-redacted content is a no-op * and produces byte-identical output — which this function detects and * skips the write for. * * Two branches, deliberately using OPPOSITE redaction strategies — do not * "simplify" them into one: * * - **Parseable** (the common case — see review-fix history below): walk * the DECODED value tree with `redactValuesDeep`, never the serialized * text. This is JSON-safe by construction (see that function's doc for * why a text-blob scan corrupts JSON) and fully shape-agnostic (every * field, any depth — no allowlist to miss a reshaped/debug-augmented * envelope). * - **Unparseable** (can't JSON.parse -> there is no value tree to walk): * apply `redactIfEnabled` directly to the RAW file text instead. This is * the right tool here for the OPPOSITE reason it's wrong above: the file * is already structurally broken, so there are no delimiters left to * protect — corrupting further JSON structure that doesn't exist costs * nothing, while leaving a live credential in an unparseable file costs a * great deal. Chosen over deletion because (a) it reuses the exact same * redactor, not a second implementation; (b) deletion destroys forensic * value (the `.reason.txt` sidecar records WHY the file failed to parse — * losing the file loses the ability to ever diagnose what broke, or * recover it if it turns out to be a false positive rather than a * secret); (c) the module's own selection-effect argument is that * unparseable content disproportionately correlates with secrets — the * population a whole-text regex/entropy pass is best suited to, not * worst. * * Review-fix history (2026-07-13, two rounds): round 1 replaced a four-field * ALLOWLIST (`redactSpoolEnvelope` alone) with that same allowlist plus a * second raw-text `redactIfEnabled` pass over the fully SERIALIZED envelope * — reasoning it was "the same shape-agnostic tool the unparseable branch * already uses." That broke on real input: the entropy detector tokenizes * on whitespace, and a JSON value with no internal whitespace — e.g. * `"session_id": "proxy-",` (every real proxy envelope has one, see * `redactValuesDeep`'s doc) — tokenizes INCLUDING its surrounding quotes and * comma, and a high-entropy match replaced the whole token, corrupting the * JSON while the sweep still reported `redacted: 1` (success). Round 2 (this * version) fixed it by never running the shape-agnostic pass over serialized * text for valid JSON — only over isolated, already-decoded string values. * * Never loses a file on a write failure: writes via the same tmp-file + * atomic rename pattern `writeToSpool` uses, so a crash or an I/O error * mid-write leaves the ORIGINAL file in place (the tmp file is discarded, * not the source) rather than a torn or missing quarantine entry. */ export declare function sweepQuarantineRedaction(dataDir: string, config?: Config): QuarantineRedactionSweepResult;