feat(cli)!: keep over-budget CLI results recoverable by default (#14610)

* feat(cli)!: keep over-budget CLI results recoverable by default

An over-budget CLI result without --evidence_output now saves its
complete Evidence to a private retained-Evidence cache under the user
cache directory and returns the summary with the file's path, size and
digest, so it pages with inspect-analysis-view without a rerun.

Files are named by the complete record's Evidence ID, created
exclusively as 0600 by the Evidence bundle writer in a 0700 directory
the user owns, reused by repeat runs and never overwritten. Each
retention removes records unused for 7 days, then the least recently
used over delivery.cli_retained_evidence_bytes (REA_CLI_RETAINED_EVIDENCE_BYTES,
default 256 MiB). --no-retain or a 0 setting writes nothing; a record
that cannot be kept falls back to the rerun arguments with the reason.

Fixes #14594

BREAKING CHANGE: An over-budget CLI result without --evidence_output is
now saved to REA's private retained-Evidence cache and reported as
{summary, evidence_bundle, delivery} with delivery.retained cache-file,
instead of writing nothing. Pass --no-retain, or set
REA_CLI_RETAINED_EVIDENCE_BYTES=0, to write nothing as before.

* fix(cli): key retained Evidence by its content and keep its owner's facts

Review fixes for default CLI retention:

- Name files by the SHA-256 of the complete record's exact JSON, since
  the Evidence ID leaves out caller paths; report it as
  evidence_bundle.sha256.
- Remove a bundle that outgrows the cache after the write.
- Renew a record's age when inspect-analysis-view reads it.
- Re-check a record's use time before evicting it.
- Never use a cache whose path holds a value marked sensitive, and
  redact retention failure reasons.
- Report a save that committed but then failed with its receipt and
  cleanup owner, as --evidence_output does.
- Request source records whenever the cache may receive a bundle.
- Refresh the advertised-schema summaries for the new setting.

* fix(cli): withdraw the receipt of a bundle the cache discards

A bundle that outgrew the cache was removed after the writer had already
recorded its publication receipt, so output recovery could name a
missing file. Retention now withdraws that receipt whenever it keeps
nothing, unless the file committed and its failure is reported.

* fix(cli): retain publication receipt when removing an oversized retained bundle fails
This commit is contained in:
morluto authored and GitHub committed 2026-11-25 21:39:33 +00:00
1 parent 88fd8a9df0
commit 2bb554e8b0
45 files changed
+1132 -35

No files matched your search

+40 -7
View File
@@ -352,13 +352,46 @@ not, the work is never refused or truncated:
shows a preview.
- The CLI with `--evidence_output` prints
`{"summary", "evidence_bundle", "delivery"}`, whose `delivery.next` names
the bundle as an `evidence-file` source. Without it, the one-shot CLI
writes nothing to disk, no bundle, cache or spill file: it prints
`{"summary", "delivery"}` with `retained: "not-retained"`, and
`delivery.rerun` gives the arguments to add to the original command as argv
arrays for every invocation: `complete` (`["--detail", "complete"]`) and
`retained` (`["--evidence_output", "<new-bundle-path>"]`). Caller inputs are
never echoed, since they can carry access credentials; the note names both.
the bundle as an `evidence-file` source.
- Without `--evidence_output`, the one-shot CLI keeps the complete Evidence
in its private retained-Evidence cache and prints the same three fields,
with `retained: "cache-file"`. `evidence_bundle` gives the bundle file's path
and size, and `record_sha256`, the digest of the complete record it holds
(the file is the bundle around that record, so its own digest differs). `delivery.next` pages it with
`rea inspect-analysis-view`, so the analysis never has to run again.
Composed commands keep the source records the bundle needs, as they do
for `--evidence_output`.
- **Location:** `rea/evidence` under the user cache directory
(`~/Library/Caches` on macOS, `XDG_CACHE_HOME` or `~/.cache` elsewhere).
The directory is created `0700` and must be a real directory the user
owns, never a symbolic link; files are created exclusively as `0600` by
the Evidence bundle writer.
- **Key and lifetime:** each file is named by the SHA-256 of the complete
record's exact JSON, so it covers every input and caller choice the
record holds, including caller paths the Evidence ID leaves out. A
repeat run reuses the file and never rewrites it. A repeat run, or a
`rea inspect-analysis-view` read of the file, renews its age. Each
retention removes records unused for 7 days, then the least recently
used until the cache fits `delivery.cli_retained_evidence_bytes`
(default 268,435,456 bytes, launch seed
`REA_CLI_RETAINED_EVIDENCE_BYTES`), skipping any record used since it
was listed. A record or bundle larger than the cache is not kept.
- **Opt out:** `--no-retain` for one run, or
`REA_CLI_RETAINED_EVIDENCE_BYTES=0` for every run that environment
reaches. An invalid seed also retains nothing, and settings inspection
reports it. The MCP server ignores this setting: its session retains
over-budget Evidence instead.
- **Fallback:** when nothing is kept (opted out, too large, a cache path
that holds a value marked sensitive, or the save failed), the CLI writes
nothing and prints `{"summary", "delivery"}`
with `retained: "not-retained"`. `delivery.retention_failure` says why a
save failed, and `delivery.rerun` gives the arguments to add to the
original command as argv arrays: `complete` (`["--detail", "complete"]`)
and `retained` (`["--evidence_output", "<new-bundle-path>"]`). The
analysis never fails because of retention. A save that published the
file but then failed (staging cleanup or cancellation) reports that
failure and its cleanup state, as `--evidence_output` does. Caller inputs are never
echoed, since they can carry access credentials; the note names both.
A failure's own facts (code, `failure_kind`, retry, recovery and limits)
are never budgeted. Its `details.partial_observation`, the complete Evidence
+3 -1
View File
@@ -61,9 +61,11 @@ override is `source: "runtime"`. The structured field is `update_mode: "runtime"
| `wasm.command_timeout_ms` | none (`command_timeout_ms`) | `src/domain/wasm/wasmArtifact.ts` | 30000 | 1 | 2147483647 | per operation |
| `native.matching_representation_bytes` | `REA_NATIVE_MATCHING_REPRESENTATION_BYTES` | `src/domain/analysisResourceLimits.ts` | 100663296 | 1 | 1073741824 | per operation |
| `delivery.agent_result_budget_bytes` | `REA_AGENT_RESULT_BUDGET_BYTES` | `src/domain/analysisResourceLimits.ts` | 32768 | 4096 | 10485760 | per operation |
| `delivery.cli_retained_evidence_bytes` | `REA_CLI_RETAINED_EVIDENCE_BYTES` | `src/domain/analysisResourceLimits.ts` | 268435456 | 0 | 68719476736 | per CLI invocation |
See [Agent result budget](limits-and-recovery.md#agent-result-budget) for
`delivery.agent_result_budget_bytes` delivery and recovery behavior.
`delivery.agent_result_budget_bytes` and `delivery.cli_retained_evidence_bytes`
delivery and recovery behavior.
An out-of-range `update_analysis_settings` value is rejected by the setting's
schema. Invalid launch seeds that the global environment parser accepts as
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "d6d7f69220a75505",
"input compact": "c341b2cd7587022a",
"output compact": "b3a429110120aff1"
},
"patterns": {}
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "08ab92d3c25f2d0c",
"input compact": "55d16506fe78a7c5",
"output compact": "39446aa1012006cc"
},
"patterns": {}
+142 -10
View File
@@ -1,5 +1,9 @@
import { explicitValuesOccurIn } from "../domain/explicitSensitiveValues.js";
import {
explicitValuesOccurIn,
redactExplicitText,
} from "../domain/explicitSensitiveValues.js";
import {
clearCliEvidencePublication,
cliPublicationInvocation,
recordCliEvidencePublication,
} from "./cliEvidencePublication.js";
@@ -17,6 +21,8 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { redactExplicitFailure } from "../domain/explicitSensitiveFailure.js";
import { err, ok, type Result } from "../domain/result.js";
import { EvidenceFileError } from "../domain/evidenceErrors.js";
import type { RetentionStop } from "./cliEvidenceRetention.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import {
cliEvidenceDeliveryInputError,
@@ -186,16 +192,15 @@ export const publishCliAnalysisEvidence = async (
return projectFailure(inputError);
}
const overBudget = budgetDelivery(complete, input);
if (evidenceOutput === undefined) {
if (overBudget === undefined) return complete;
const summary = await overBudgetSummary(complete);
return summary === undefined
if (evidenceOutput === undefined)
return overBudget === undefined
? complete
: {
summary,
delivery: deliveryJson(overBudget({ kind: "not-retained" })),
};
}
: deliverRetainedSummary(
complete,
closureInput,
overBudget,
projectFailure,
);
const outputPath = absoluteCallerPath(evidenceOutput);
const published = await publishDeliveredEvidence(
complete,
@@ -227,6 +232,133 @@ export const publishCliAnalysisEvidence = async (
: published.value.delivered;
};
/**
* An over-budget result without --evidence_output: its summary, with the
* complete Evidence kept in the private cache when that is on, and the
* rerun arguments otherwise. An operation without a summary view keeps
* complete delivery.
*/
const deliverRetainedSummary = async (
complete: Evidence,
input: CliEvidencePublication,
overBudget: (recovery: AgentBudgetRecovery) => AgentBudgetDelivery,
projectFailure: (error: AnalysisError) => JsonValue,
): Promise<JsonValue> => {
const summary = await overBudgetSummary(complete);
if (summary === undefined) return complete;
const retained = await retainOverBudgetEvidence(
complete,
input,
overBudget({ kind: "not-retained" }).complete_bytes,
);
// The file was saved, but a later step failed: report that failure and
// its cleanup owner, as a requested --evidence_output bundle does.
if (retained?.ok === false && retained.error.committed !== undefined)
return projectFailure(retained.error.committed);
return retained?.ok === true
? {
summary,
evidence_bundle: retained.value.receipt,
delivery: deliveryJson(
overBudget({ kind: "cache-file", path: retained.value.path }),
),
}
: {
summary,
delivery: deliveryJson(
overBudget({
kind: "not-retained",
...(retained === undefined
? {}
: {
reason: redactExplicitText(
retained.error.reason,
input.sensitiveValues ?? [],
),
}),
}),
),
};
};
/**
* Keep an over-budget result this invocation was not told to save in the
* private retained-Evidence cache, so it pages without a rerun. Undefined
* when retention is off (--no-retain, or the setting is 0); a failure says
* why, and the result falls back to the rerun arguments.
*/
const retainOverBudgetEvidence = async (
complete: Evidence,
input: CliEvidencePublication,
completeBytes: number,
): Promise<
| Result<
{ readonly path: string; readonly receipt: JsonValue },
RetentionStop<AnalysisError>
>
| undefined
> => {
const { retention } = cliPublicationInvocation();
if (retention === undefined) return undefined;
const sensitiveCachePathReason =
"The retained-Evidence cache path contains a value marked sensitive, so nothing was retained.";
// A cache under a path that holds a value marked sensitive is never used,
// so neither its path nor a failure naming it reaches the output.
if (revealsSensitiveValue(retention.directory, input))
return err({ reason: sensitiveCachePathReason });
const { retainCliEvidence, retainedEvidenceDigest } =
await import("./cliEvidenceRetention.js");
const kept = await retainCliEvidence<AnalysisError>({
sha256: retainedEvidenceDigest(complete),
completeBytes,
retention,
rejectResolvedDirectory: (resolved) =>
revealsSensitiveValue(resolved, input)
? sensitiveCachePathReason
: undefined,
write: async (path) => {
// The bundle writer creates the file exclusively and never overwrites.
const published = await publishDeliveredEvidence(
complete,
path,
input,
true,
);
if (published.ok) {
const { bytes } = published.value.receipt as { readonly bytes: number };
return ok({ bytes });
}
const { error, committed } = published.error;
if (error instanceof EvidenceFileError && error.reason === "exists")
return err("exists");
return err({
reason: redactExplicitText(error.message, input.sensitiveValues ?? []),
...(committed ? { committed: error } : {}),
});
},
});
// Clear the recorded receipt only when no published file remains on disk.
if (!kept.ok) {
if (kept.error.committed === undefined && kept.error.fileRemains !== true)
clearCliEvidencePublication();
return err({
...kept.error,
reason: redactExplicitText(
kept.error.reason,
input.sensitiveValues ?? [],
),
});
}
const receipt = {
...bundleReceipt(kept.value.path, kept.value.bytes, input),
// The cache key: the digest of the complete record, not of the file,
// which is the bundle that holds it.
record_sha256: kept.value.sha256,
};
recordCliEvidencePublication(receipt);
return ok({ path: kept.value.path, receipt });
};
/** Delivery facts are plain JSON by construction. */
const deliveryJson = (delivery: AgentBudgetDelivery): JsonValue =>
delivery as unknown as JsonValue;
+24
View File
@@ -18,6 +18,28 @@ import { registerCliCommand } from "./commandRegistry.js";
import type { CliInstance } from "./types.js";
import { localPathStringSchema } from "../domain/localPath.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { cliPublicationInvocation } from "./cliEvidencePublication.js";
import { renewRetainedEvidence } from "./cliEvidenceRetention.js";
/** The Evidence files a successful view read: its file source and bundle. */
const renewReadRetainedEvidence = async (
document: unknown,
bundlePath: string | undefined,
): Promise<void> => {
const { retention } = cliPublicationInvocation();
const source =
typeof document === "object" && document !== null
? (document as { readonly source?: unknown }).source
: undefined;
const sourcePath =
typeof source === "object" &&
source !== null &&
(source as { readonly kind?: unknown }).kind === "evidence-file"
? (source as { readonly path?: unknown }).path
: undefined;
for (const path of [sourcePath, bundlePath])
if (typeof path === "string") await renewRetainedEvidence(path, retention);
};
import { contractNamed } from "./contractCliDescription.js";
import { registerContractDocumentCommand } from "./contractDocumentCommand.js";
import { finishAnalysisCommand } from "./finishAnalysisCommand.js";
@@ -116,6 +138,8 @@ export const registerAnalysisViewCommands = (
operation,
signal,
);
// Reading a retained record renews its age in the private cache.
if (result.ok) await renewReadRetainedEvidence(document, bundlePath);
// Preserve the inline command's existing error label without copying
// the authenticated completed Evidence or its partial observation.
return result.ok
+13
View File
@@ -1,5 +1,6 @@
import { AsyncLocalStorage } from "node:async_hooks";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { CliEvidenceRetention } from "./cliEvidenceRetention.js";
export interface PublishedEvidenceReceipt {
readonly path?: string;
@@ -18,6 +19,12 @@ export interface CliPublicationInvocation {
readonly agentBudgetSeed?: string | undefined;
/** Whether the caller selected specific output fields with `--filter-output`. */
readonly hasFilterOutput?: boolean | undefined;
/**
* Where an over-budget result without --evidence_output is kept, from the
* environment this invocation captured; undefined retains nothing
* (--no-retain, or the setting is 0).
*/
readonly retention?: CliEvidenceRetention | undefined;
}
/** Keep publication state in the invocation that owns delivery and formatting. */
@@ -38,6 +45,12 @@ export const recordCliEvidencePublication = (
if (context !== undefined) context.receipt = receipt;
};
/** Withdraw this invocation's receipt when the file it named was discarded. */
export const clearCliEvidencePublication = (): void => {
const context = publication.getStore();
if (context !== undefined) delete context.receipt;
};
/** Snapshot a receipt for output recovery after the invocation context ends. */
export const cliEvidencePublicationReceipt = ():
| PublishedEvidenceReceipt
+280
View File
@@ -0,0 +1,280 @@
import { createHash } from "node:crypto";
import {
chmod,
lstat,
mkdir,
readdir,
realpath,
rm,
utimes,
} from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
import { CLI_RETAINED_EVIDENCE_MAX_AGE_MS } from "../domain/analysisResourceLimits.js";
import type { Evidence } from "../domain/evidence.js";
import { jsonParts } from "../domain/jsonSerialization.js";
import { err, ok, type Result } from "../domain/result.js";
import { reaCacheDirectory } from "../filesystem/cacheDirectory.js";
import { errorMessage } from "../kernel/errorMessage.js";
/** Where one invocation may retain over-budget Evidence, and how much. */
export interface CliEvidenceRetention {
/** The private per-user directory, `rea/evidence` under the cache root. */
readonly directory: string;
/** Total bytes the directory may hold; above 0. */
readonly capBytes: number;
}
/** The per-run opt-out switch. */
export const NO_RETAIN_FLAG = "--no-retain";
/** The retained-Evidence directory under the platform's per-user cache root. */
export const cliRetainedEvidenceDirectory = (
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): string => reaCacheDirectory(environment, platform, "evidence");
/**
* The cache key: the SHA-256 of the complete record's exact JSON. The
* Evidence ID leaves out caller-input paths and local subject metadata, so
* two runs with the same semantic result can differ in what they record;
* hashing the whole record keeps each invocation's own record.
*/
export const retainedEvidenceDigest = (evidence: Evidence): string => {
const hash = createHash("sha256");
for (const part of jsonParts(evidence)) hash.update(part, "utf8");
return hash.digest("hex");
};
/** A retained bundle is named by its record's digest, so one record has one file. */
const RETAINED_NAME = /^[0-9a-f]{64}\.json$/u;
/** One retained record: its file, size, digest and whether it was already there. */
export interface RetainedEvidenceFile {
readonly path: string;
readonly bytes: number;
readonly sha256: string;
readonly reused: boolean;
}
/**
* Why nothing was retained. `committed` carries the writer's failure when
* the file was published but a later step (staging cleanup, cancellation)
* failed: its caller reports that failure and its cleanup owner.
*/
export interface RetentionStop<Committed> {
readonly reason: string;
readonly committed?: Committed;
/**
* True when the file was published and remains on disk because a post-write
* removal (such as discarding an oversized bundle) failed; the caller must
* retain the published file's receipt.
*/
readonly fileRemains?: true;
}
/** The writer's outcome: the bytes it published, that the name exists, or a stop. */
export type RetentionWrite<Committed> = Result<
{ readonly bytes: number },
"exists" | RetentionStop<Committed>
>;
const isMissing = (cause: unknown): boolean =>
typeof cause === "object" &&
cause !== null &&
(cause as { readonly code?: unknown }).code === "ENOENT";
const isOwnedEntry = (stats: { readonly uid: number }): boolean =>
// Only POSIX hosts expose user IDs; elsewhere the cache root's ACLs apply.
typeof process.getuid !== "function" || stats.uid === process.getuid();
/**
* Create the directory privately (0700), and admit it only when it is a real
* directory this user owns, never a symbolic link. Our own directory is
* tightened to 0700 if something loosened it.
*/
const admitDirectory = async (
directory: string,
): Promise<string | undefined> => {
await mkdir(directory, { recursive: true, mode: 0o700 });
const stats = await lstat(directory);
if (!stats.isDirectory() || stats.isSymbolicLink() || !isOwnedEntry(stats))
return undefined;
if (typeof process.getuid === "function" && (stats.mode & 0o077) !== 0)
await chmod(directory, 0o700);
// The checked directory as the filesystem resolves it, so later paths
// keep its meaning even when the selected spelling holds `..` after a
// symbolic link, which lexical joining would collapse.
return realpath(directory);
};
/** A regular file this user owns at `path`, its size; undefined when absent. */
const ownedFileBytes = async (
path: string,
): Promise<number | "foreign" | undefined> => {
const stats = await lstat(path).catch((cause: unknown) => {
if (isMissing(cause)) return undefined;
throw cause;
});
if (stats === undefined) return undefined;
return stats.isFile() && !stats.isSymbolicLink() && isOwnedEntry(stats)
? stats.size
: "foreign";
};
/** Renew a retained record's age: it was used now. Its bytes never change. */
const renew = async (path: string, now: number): Promise<void> => {
const used = new Date(now);
await utimes(path, used, used);
};
/**
* Remove retained records unused for longer than the maximum age, then the
* least recently used until the directory fits `capBytes`. Only regular files
* named like a retained record are considered, never the record just kept.
* Each removal first checks that the record was not used since it was
* listed, so a concurrent run's renewal keeps it; a file that cannot be
* removed is left for a later run.
*/
const evict = async (
directory: string,
keep: string,
capBytes: number,
now: number,
): Promise<void> => {
const entries: { name: string; bytes: number; used: number }[] = [];
for (const name of await readdir(directory)) {
if (!RETAINED_NAME.test(name)) continue;
const stats = await lstat(join(directory, name)).catch(() => undefined);
if (stats === undefined || !stats.isFile() || !isOwnedEntry(stats))
continue;
entries.push({ name, bytes: stats.size, used: stats.mtimeMs });
}
const remove = async (entry: (typeof entries)[number]): Promise<boolean> => {
const path = join(directory, entry.name);
const current = await lstat(path).catch(() => undefined);
if (current === undefined || current.mtimeMs !== entry.used) return false;
return rm(path, { force: true }).then(
() => true,
() => false,
);
};
let total = 0;
const live: typeof entries = [];
for (const entry of entries) {
const expired =
entry.name !== keep &&
now - entry.used > CLI_RETAINED_EVIDENCE_MAX_AGE_MS;
if (expired && (await remove(entry))) continue;
live.push(entry);
total += entry.bytes;
}
live.sort((left, right) => left.used - right.used);
for (const entry of live) {
if (total <= capBytes) break;
if (entry.name === keep) continue;
if (await remove(entry)) total -= entry.bytes;
}
};
/**
* Keep one over-budget record recoverable in the private cache. A record or
* bundle larger than the cache, an unusable directory, or a failed write
* retains nothing and says why; it never fails the analysis. `write`
* publishes the bundle with the Evidence bundle writer, which creates the
* file exclusively (0600) and refuses an existing name.
*/
export const retainCliEvidence = async <Committed>(input: {
readonly sha256: string;
readonly completeBytes: number;
readonly retention: CliEvidenceRetention;
readonly write: (path: string) => Promise<RetentionWrite<Committed>>;
readonly rejectResolvedDirectory?: (directory: string) => string | undefined;
readonly now?: number;
}): Promise<Result<RetainedEvidenceFile, RetentionStop<Committed>>> => {
const { directory, capBytes } = input.retention;
const { sha256 } = input;
const name = `${sha256}.json`;
if (!RETAINED_NAME.test(name))
return err({ reason: `${sha256} is not a SHA-256 digest.` });
const tooLarge = (bytes: number) => ({
reason: `The complete Evidence (${String(bytes)} bytes) is larger than the retained-Evidence cache (${String(capBytes)} bytes).`,
});
if (input.completeBytes > capBytes) return err(tooLarge(input.completeBytes));
const now = input.now ?? Date.now();
try {
const admitted = await admitDirectory(directory);
if (admitted === undefined)
return err({
reason:
"The retained-Evidence cache directory is not a private directory this user owns.",
});
const rejected = input.rejectResolvedDirectory?.(admitted);
if (rejected !== undefined) return err({ reason: rejected });
const path = join(admitted, name);
const reuse = async (): Promise<
Result<RetainedEvidenceFile, RetentionStop<Committed>> | undefined
> => {
const bytes = await ownedFileBytes(path);
if (bytes === undefined) return undefined;
if (bytes === "foreign")
return err({
reason:
"A file that is not a retained Evidence record holds its name.",
});
await renew(path, now);
return ok({ path, bytes, sha256, reused: true });
};
let kept = await reuse();
if (kept === undefined) {
const written = await input.write(path);
if (written.ok && written.value.bytes > capBytes) {
// The bundle, with the sources it cites, outgrew the cache.
try {
await rm(path, { force: true });
} catch (cause: unknown) {
return err({
reason: `The oversized retained-Evidence bundle could not be removed: ${errorMessage(cause)}`,
fileRemains: true,
});
}
return err(tooLarge(written.value.bytes));
}
// Another run kept the same record between the check and the write.
kept = written.ok
? ok({ path, bytes: written.value.bytes, sha256, reused: false })
: written.error === "exists"
? ((await reuse()) ??
err({ reason: "The retained Evidence file could not be written." }))
: err(written.error);
}
if (kept.ok) await evict(admitted, name, capBytes, now).catch(() => {});
return kept;
} catch (cause: unknown) {
return err({
reason: `The retained-Evidence cache could not be used: ${errorMessage(cause)}`,
});
}
};
/**
* A read through `rea inspect-analysis-view` uses a retained record, so it
* renews the record's age as a repeat run does. Only a record file in this
* invocation's cache directory is touched; anything else is left alone.
*/
export const renewRetainedEvidence = async (
path: string,
retention: CliEvidenceRetention | undefined,
now = Date.now(),
): Promise<void> => {
if (retention === undefined || !RETAINED_NAME.test(basename(path))) return;
// Compare the directories as the filesystem resolves them.
const [parent, cache] = await Promise.all([
realpath(dirname(resolve(path))).catch(() => undefined),
realpath(retention.directory).catch(() => undefined),
]);
if (parent === undefined || parent !== cache) return;
const absolute = join(parent, basename(path));
const bytes = await ownedFileBytes(absolute).catch(() => undefined);
if (typeof bytes === "number") await renew(absolute, now).catch(() => {});
};
+9 -3
View File
@@ -1,3 +1,4 @@
import { cliPublicationInvocation } from "./cliEvidencePublication.js";
import type { Logger } from "pino";
import type { DirectAnalysis } from "../composition/directAnalysis.js";
@@ -185,9 +186,14 @@ export const runDirectOnTarget =
logger,
signal,
...directAnalysisOpening(opening),
...(evidenceOutput === undefined
? {}
: { includeEvidenceSources: true }),
// A bundle needs the sources its record cites: a requested one, or
// the retained-Evidence cache an over-budget result may go to.
...(evidenceOutput !== undefined ||
(delivery !== undefined &&
delivery.detail === undefined &&
cliPublicationInvocation().retention !== undefined)
? { includeEvidenceSources: true }
: {}),
},
);
if (delivery === undefined) return projectCliAnalysisResult(result);
+4
View File
@@ -163,6 +163,10 @@ const globalOptionRows = ({ formats, root }: GlobalOptionsHelp): Row[] =>
description: "Skip first n tokens of output",
},
{ label: "--full-output", description: "Show full output envelope" },
{
label: "--no-retain",
description: "Write no over-budget result to the retained-Evidence cache",
},
...(root === undefined
? []
: [
+53 -6
View File
@@ -1,4 +1,13 @@
import { AGENT_RESULT_BUDGET_ENVIRONMENT } from "../domain/agentResultBudget.js";
import {
AGENT_RESULT_BUDGET_ENVIRONMENT,
CLI_RETAINED_EVIDENCE_ENVIRONMENT,
cliRetainedEvidenceBytes,
} from "../domain/agentResultBudget.js";
import {
cliRetainedEvidenceDirectory,
NO_RETAIN_FLAG,
type CliEvidenceRetention,
} from "./cliEvidenceRetention.js";
import { Writable } from "node:stream";
import {
@@ -19,7 +28,10 @@ import {
} from "./argumentErrors.js";
import { parseCliArgv } from "./argvParser.js";
import { cliCommand, cliCommands } from "./commandRegistry.js";
import { withCliEvidencePublication } from "./cliEvidencePublication.js";
import {
withCliEvidencePublication,
type CliPublicationInvocation,
} from "./cliEvidencePublication.js";
import { rebindLoggedCliFailure } from "../cliLogging.js";
import { RECORDED_CLI_COMMAND_REGISTRATIONS } from "../recordedCliCommandRegistrations.js";
import { projectCliCommandOutput } from "./projectCliAnalysisResult.js";
@@ -67,6 +79,44 @@ const destinationFor = (options: CliServeOptions): Writable => {
return destination;
};
/**
* Where this invocation keeps an over-budget result it was not told to save:
* the private cache, unless --no-retain or a 0 setting turns that off, or the
* environment names no home to put it under.
*/
const invocationRetention = (
global: CliGlobalArguments,
environment: UpdateEnvironment,
): CliEvidenceRetention | undefined => {
if (global.flags.has(NO_RETAIN_FLAG)) return undefined;
const capBytes = cliRetainedEvidenceBytes(
environment.variables[CLI_RETAINED_EVIDENCE_ENVIRONMENT],
);
if (capBytes === 0) return undefined;
try {
return {
directory: cliRetainedEvidenceDirectory(
environment.variables,
environment.platform,
),
capBytes,
};
} catch {
return undefined;
}
};
/** What this invocation's delivery reads from its argv and environment. */
const publicationInvocation = (
global: CliGlobalArguments,
environment: UpdateEnvironment,
controls: ReturnType<typeof readCliOutputArguments>,
): CliPublicationInvocation => ({
agentBudgetSeed: environment.variables[AGENT_RESULT_BUDGET_ENVIRONMENT],
hasFilterOutput: controls.filterOutput !== undefined,
retention: invocationRetention(global, environment),
});
/** Bind, admit and run one registered command, retaining output/publication ownership. */
export const runCliCommand = async (
cli: CliInstance,
@@ -148,10 +198,7 @@ export const runCliCommand = async (
cta,
});
}),
{
agentBudgetSeed: environment.variables[AGENT_RESULT_BUDGET_ENVIRONMENT],
hasFilterOutput: controls.filterOutput !== undefined,
},
publicationInvocation(global, environment, controls),
);
if (output.error !== undefined) exit(options, 1);
} catch (cause: unknown) {
+3
View File
@@ -19,6 +19,8 @@ export const OUTPUT_SWITCHES: ReadonlySet<string> = new Set([
"--full-output",
"--token-count",
"--timings",
// Keeps an over-budget result out of the private retained-Evidence cache.
"--no-retain",
]);
/** Valueless global flags taken out of every position before command parsing. */
@@ -36,6 +38,7 @@ export const CLI_BUILTIN_FLAGS: ReadonlySet<string> = new Set([
"--json",
"--token-count",
"--timings",
"--no-retain",
]);
/** The timing global's spellings: `--timings`, `--no-timings`, `--timings=<text>`. */
+1
View File
@@ -14,6 +14,7 @@ const COMMAND_OUTPUT_FLAGS: ReadonlySet<string> = new Set([
"--token-count",
"--timings",
"--no-timings",
"--no-retain",
]);
/** Global switches that inspect a single known command without listing others. */
+5 -1
View File
@@ -35,7 +35,10 @@ import {
} from "./windowsChangeTimeSettle.js";
import { pwntoolsInputBytesSchema } from "./pwntoolsInputLimit.js";
import { zstandardMaxFramesSchema } from "../domain/compression/zstandardFrameAllowance.js";
import { agentResultBudgetBytesSchema } from "../domain/agentResultBudget.js";
import {
agentResultBudgetBytesSchema,
cliRetainedEvidenceBytesSchema,
} from "../domain/agentResultBudget.js";
const environmentSchemas: Readonly<Record<string, z.ZodType<number, string>>> =
{
REA_ASAR_MAX_HEADER_BYTES: asarMaxHeaderBytesSchema,
@@ -71,6 +74,7 @@ const environmentSchemas: Readonly<Record<string, z.ZodType<number, string>>> =
windowsChangeTimeSettleMaxPollsSchema,
REA_ZSTD_MAX_FRAMES: zstandardMaxFramesSchema,
REA_AGENT_RESULT_BUDGET_BYTES: agentResultBudgetBytesSchema,
REA_CLI_RETAINED_EVIDENCE_BYTES: cliRetainedEvidenceBytesSchema,
};
export const launchAnalysisSetting = (
id: AnalysisSettingId,
+53 -3
View File
@@ -1,8 +1,11 @@
import { z } from "zod";
import {
DEFAULT_AGENT_RESULT_BUDGET_BYTES,
DEFAULT_CLI_RETAINED_EVIDENCE_BYTES,
MAXIMUM_AGENT_RESULT_BUDGET_BYTES,
MAXIMUM_CLI_RETAINED_EVIDENCE_BYTES,
MINIMUM_AGENT_RESULT_BUDGET_BYTES,
MINIMUM_CLI_RETAINED_EVIDENCE_BYTES,
} from "./analysisResourceLimits.js";
import { currentAnalysisSettingOverride } from "./analysisOperationSnapshot.js";
import type { JsonValue } from "./jsonValue.js";
@@ -38,6 +41,40 @@ export const agentResultBudgetBytesSchema = z
.max(MAXIMUM_AGENT_RESULT_BUDGET_BYTES, { error: seedConstraint }),
);
/** Registered setting that bounds the CLI's retained over-budget Evidence. */
export const CLI_RETAINED_EVIDENCE_SETTING =
"delivery.cli_retained_evidence_bytes" as const;
/** Its launch seed; `0` turns CLI retention off. */
export const CLI_RETAINED_EVIDENCE_ENVIRONMENT =
"REA_CLI_RETAINED_EVIDENCE_BYTES";
const retentionConstraint = `${CLI_RETAINED_EVIDENCE_ENVIRONMENT} must be a decimal integer from ${String(MINIMUM_CLI_RETAINED_EVIDENCE_BYTES)} to ${String(MAXIMUM_CLI_RETAINED_EVIDENCE_BYTES)} bytes; 0 turns retention off and the default is ${String(DEFAULT_CLI_RETAINED_EVIDENCE_BYTES)}.`;
/** Launch seed admission for the retained CLI Evidence cache size. */
export const cliRetainedEvidenceBytesSchema = z
.string()
.regex(/^(0|[1-9]\d*)$/u, { error: retentionConstraint })
.transform(Number)
.pipe(
z
.int()
.min(MINIMUM_CLI_RETAINED_EVIDENCE_BYTES, { error: retentionConstraint })
.max(MAXIMUM_CLI_RETAINED_EVIDENCE_BYTES, { error: retentionConstraint }),
);
/**
* Total bytes the CLI may keep in its retained-Evidence cache: the default
* when the seed is unset, and 0 (off) for `0` or an invalid seed, so an
* invalid seed writes nothing, as before retention existed. Settings
* inspection and doctor report an invalid seed.
*/
export const cliRetainedEvidenceBytes = (seed: string | undefined): number => {
if (seed === undefined) return DEFAULT_CLI_RETAINED_EVIDENCE_BYTES;
const parsed = cliRetainedEvidenceBytesSchema.safeParse(seed);
return parsed.success ? parsed.data : 0;
};
/** The budget in force for this operation and where it came from. */
export interface AgentResultBudget {
readonly bytes: number;
@@ -130,7 +167,10 @@ export const failureEnvelopeBytes = (failure: {
export type AgentBudgetRecovery =
| { readonly kind: "session" }
| { readonly kind: "evidence-file"; readonly path: string | undefined }
| { readonly kind: "not-retained" };
/** The CLI's private retained-Evidence cache, by default. */
| { readonly kind: "cache-file"; readonly path: string }
/** Nothing was written; `reason` says why when retention was attempted. */
| { readonly kind: "not-retained"; readonly reason?: string };
/**
* Delivery facts for a result replaced by its summary. They describe the
@@ -166,6 +206,8 @@ export interface AgentBudgetDelivery {
readonly complete: readonly string[];
readonly retained: readonly string[];
};
/** Why the CLI's default retention wrote nothing, when it was attempted. */
readonly retention_failure?: string;
readonly note: string;
}
@@ -183,7 +225,10 @@ const pageSource = (
): Readonly<Record<string, string>> | undefined => {
if (recovery.kind === "session")
return { kind: "retained-evidence", evidence_id: evidenceId };
if (recovery.kind === "evidence-file" && recovery.path !== undefined)
if (
(recovery.kind === "evidence-file" || recovery.kind === "cache-file") &&
recovery.path !== undefined
)
return {
kind: "evidence-file",
path: recovery.path,
@@ -197,7 +242,9 @@ const recoveryNote = (recovery: AgentBudgetRecovery): string => {
return `It is retained in this session: next pages its exact JSON through inspect_analysis_view (follow coverage.next_offset); the producer's own views select facts more cheaply. Pass detail complete for all of it inline, or raise ${AGENT_RESULT_BUDGET_SETTING} with update_analysis_settings.`;
if (recovery.kind === "evidence-file")
return "It is in the --evidence_output bundle: rea inspect-analysis-view with next.arguments pages its exact JSON. Pass --detail complete for all of it inline.";
return `This invocation selected no --evidence_output, so it was not retained and nothing was written: rerun the same command with rerun.complete (--detail complete) for all of it inline, or with rerun.retained (--evidence_output ${EVIDENCE_OUTPUT_PLACEHOLDER}) to save it for inspect-analysis-view.`;
if (recovery.kind === "cache-file")
return `It was saved to REA's private retained-Evidence cache, named by its Evidence ID: rea inspect-analysis-view with next.arguments pages its exact JSON. The cache keeps at most ${CLI_RETAINED_EVIDENCE_SETTING} bytes in total and removes records unused for 7 days. Pass --detail complete for all of it inline, --evidence_output <path> to save it elsewhere, or --no-retain to write nothing.`;
return `This invocation retained nothing and wrote nothing (no --evidence_output, and --no-retain, ${CLI_RETAINED_EVIDENCE_SETTING} 0, or a failed save named by retention_failure): rerun the same command with rerun.complete (--detail complete) for all of it inline, or with rerun.retained (--evidence_output ${EVIDENCE_OUTPUT_PLACEHOLDER}) to save it for inspect-analysis-view.`;
};
/**
@@ -236,6 +283,9 @@ export const agentBudgetDelivery = (input: {
},
}),
...(recovery.kind === "not-retained" ? { rerun: RERUN_ARGUMENTS } : {}),
...(recovery.kind === "not-retained" && recovery.reason !== undefined
? { retention_failure: recovery.reason }
: {}),
note: `Complete ${input.operation} Evidence ${evidenceId} is ${String(completeBytes)} bytes (about ${String(estimatedJsonTokens(completeBytes))} tokens, estimated at ${String(ESTIMATED_JSON_BYTES_PER_TOKEN)} bytes per token), over the agent result budget of ${String(budget.bytes)} bytes (${AGENT_RESULT_BUDGET_SETTING}, source ${budget.source}), so its summary was delivered. Nothing was truncated. ${recoveryNote(recovery)}`,
};
};
+14
View File
@@ -309,3 +309,17 @@ export const DEFAULT_AGENT_RESULT_BUDGET_BYTES = 32_768;
export const MINIMUM_AGENT_RESULT_BUDGET_BYTES = 4_096;
/** The stdio frame floor (10 MiB); the transport limit applies above it. */
export const MAXIMUM_AGENT_RESULT_BUDGET_BYTES = 10 * 1024 * 1024;
/**
* Total size of the per-user cache that keeps over-budget CLI results
* recoverable. A delivery bound, not an admission limit: a result that cannot
* be kept falls back to the rerun arguments, and 0 turns retention off. 256
* MiB keeps dozens of large inventories (a 530 KB assembly's complete
* managed members are 20.8 MB) without growing unbounded.
*/
export const DEFAULT_CLI_RETAINED_EVIDENCE_BYTES = 256 * 1024 * 1024;
/** 0 turns CLI retention off. */
export const MINIMUM_CLI_RETAINED_EVIDENCE_BYTES = 0;
export const MAXIMUM_CLI_RETAINED_EVIDENCE_BYTES = 64 * 1024 * 1024 * 1024;
/** Retained CLI Evidence unused for this long is removed by the next retention. */
export const CLI_RETAINED_EVIDENCE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+16
View File
@@ -64,6 +64,9 @@ import {
MINIMUM_ZSTD_MAX_FRAMES,
MAXIMUM_ZSTD_MAX_FRAMES,
DEFAULT_AGENT_RESULT_BUDGET_BYTES,
DEFAULT_CLI_RETAINED_EVIDENCE_BYTES,
MAXIMUM_CLI_RETAINED_EVIDENCE_BYTES,
MINIMUM_CLI_RETAINED_EVIDENCE_BYTES,
MINIMUM_AGENT_RESULT_BUDGET_BYTES,
MAXIMUM_AGENT_RESULT_BUDGET_BYTES,
} from "./analysisResourceLimits.js";
@@ -664,6 +667,19 @@ export const ANALYSIS_SETTINGS = {
provider: "rea-delivery",
operations: AGENT_BUDGET_OPERATIONS,
},
// One-shot CLI invocations read only the launch seed; MCP retains
// over-budget Evidence in its session instead.
"delivery.cli_retained_evidence_bytes": {
updateMode: "runtime",
environment: "REA_CLI_RETAINED_EVIDENCE_BYTES",
defaultValue: DEFAULT_CLI_RETAINED_EVIDENCE_BYTES,
minimum: MINIMUM_CLI_RETAINED_EVIDENCE_BYTES,
maximum: MAXIMUM_CLI_RETAINED_EVIDENCE_BYTES,
unit: "bytes",
appliesAt: "next_operation",
provider: "rea-delivery",
operations: AGENT_BUDGET_OPERATIONS,
},
} as const satisfies Record<AnalysisSettingId, SettingDefinition>;
export const analysisSettingIds = Object.keys(
ANALYSIS_SETTINGS,
+1
View File
@@ -33,6 +33,7 @@ export interface AnalysisSettingValues {
readonly "windows.change_time_settle_max_polls": number;
readonly "zstd.max_frames": number;
readonly "delivery.agent_result_budget_bytes": number;
readonly "delivery.cli_retained_evidence_bytes": number;
}
export type AnalysisSettingId = keyof AnalysisSettingValues;
export interface AnalysisSettingsSnapshot {
@@ -0,0 +1,440 @@
import { createHash, randomBytes } from "node:crypto";
import {
chmod,
lstat,
mkdir,
readdir,
realpath,
stat,
symlink,
utimes,
writeFile,
} from "node:fs/promises";
import { dirname, join, relative } from "node:path";
import { expect, it } from "vitest";
import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js";
import { createCli } from "../../../src/cli.js";
import { publishCliAnalysisEvidence } from "../../../src/cli/analysisEvidenceDelivery.js";
import {
cliEvidencePublicationReceipt,
withCliEvidencePublication,
} from "../../../src/cli/cliEvidencePublication.js";
import {
cliRetainedEvidenceDirectory,
retainCliEvidence,
retainedEvidenceDigest,
} from "../../../src/cli/cliEvidenceRetention.js";
import { createByteEntropyService } from "../../../src/composition/binaryDiagnostics/byteEntropy.js";
import { CLI_RETAINED_EVIDENCE_MAX_AGE_MS } from "../../../src/domain/analysisResourceLimits.js";
import {
parseEvidence,
withEvidenceCallerInputPath,
} from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
type Output = {
readonly summary: unknown;
readonly evidence_bundle?: {
readonly path: string;
readonly bytes: number;
readonly record_sha256: string;
};
readonly delivery: {
readonly retained: string;
readonly evidence_id: string;
readonly complete_bytes: number;
readonly retention_failure?: string;
readonly rerun?: unknown;
readonly next?: {
readonly arguments: {
readonly source: Record<string, string>;
readonly view: Record<string, unknown>;
};
};
};
};
/** A fresh home and cache, and a 1 MiB target whose entropy is over budget. */
const workspace = async (extra: Record<string, string> = {}) => {
const home = await createTestTempDirectory("rea-retain-home-");
const cache = await createTestTempDirectory("rea-retain-cache-");
const root = await createTestTempDirectory("rea-retain-target-");
const target = join(root, "bytes");
await writeFile(target, randomBytes(1024 * 1024));
// The shipped defaults: no test seed for the budget or the cache size.
const environment: Record<string, string> = {
HOME: home,
XDG_CACHE_HOME: cache,
TMPDIR: root,
PATH: process.env.PATH ?? "/usr/bin:/bin",
...extra,
};
const directory = cliRetainedEvidenceDirectory(environment, process.platform);
const serve = async (argv: readonly string[]): Promise<unknown> => {
let stdout = "";
let exitCode = 0;
await createCli(environment).serve([...argv], {
env: environment,
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
});
expect(exitCode, stdout).toBe(0);
return JSON.parse(stdout) as unknown;
};
const runOn = (spelling: string, ...flags: string[]) =>
serve([
"inspect-byte-entropy",
spelling,
"--block-size",
"256",
"--json",
...flags,
]) as Promise<Output>;
const run = (...flags: string[]) => runOn(target, ...flags);
return { run, runOn, serve, directory, target };
};
const files = (directory: string) =>
readdir(directory).catch((cause: unknown) => {
if ((cause as { code?: string }).code === "ENOENT") return [];
throw cause;
});
it("keeps an over-budget CLI result in the private cache, pages it, and reuses it", async () => {
const { run, runOn, serve, directory, target } = await workspace();
const first = await run();
expect(parseEvidence(first.summary).operation).toBe("inspect_analysis_view");
const id = first.delivery.evidence_id;
const sha256 = first.evidence_bundle!.record_sha256;
// Paths name the cache directory as the filesystem resolves it.
const path = join(await realpath(directory), `${sha256}.json`);
expect(first.delivery).toMatchObject({ retained: "cache-file" });
expect(first.evidence_bundle).toEqual({
path,
bytes: (await stat(path)).size,
record_sha256: sha256,
});
expect(first.delivery.next?.arguments.source).toEqual({
kind: "evidence-file",
path,
evidence_id: id,
});
if (process.platform !== "win32") {
expect((await lstat(directory)).mode & 0o777).toBe(0o700);
expect((await lstat(path)).mode & 0o777).toBe(0o600);
}
// The retained file pages through the existing file source.
const page = await inspectAnalysisView({
...first.delivery.next!.arguments,
view: { kind: "evidence-json", offset: 0, limit: 1_048_576 },
});
if (!page.ok) throw page.error;
const { text } = page.value.normalized_result as unknown as {
readonly text: string;
};
const complete = await run("--detail", "complete");
expect(JSON.parse(text)).toEqual(complete);
// The file is named by the digest of the complete record's exact JSON.
expect(sha256).toBe(
createHash("sha256").update(JSON.stringify(complete)).digest("hex"),
);
expect(Buffer.byteLength(JSON.stringify(complete))).toBe(
first.delivery.complete_bytes,
);
// A repeat run reuses the same file, never rewrites it, and renews its age.
const old = new Date(Date.now() - 60_000);
await utimes(path, old, old);
const before = await stat(path);
const repeat = await run();
expect(repeat.evidence_bundle).toEqual(first.evidence_bundle);
const after = await stat(path);
expect(after.ino).toBe(before.ino);
expect(after.mtimeMs).toBeGreaterThan(before.mtimeMs);
expect(await files(directory)).toEqual([`${sha256}.json`]);
// Paging it through the CLI uses it too, and renews its age again.
await utimes(path, old, old);
const viewed = (await serve([
"inspect-analysis-view",
JSON.stringify(first.delivery.next!.arguments),
"--json",
])) as { readonly evidence_id: string };
expect(viewed.evidence_id).toEqual(expect.any(String));
expect((await stat(path)).mtimeMs).toBeGreaterThan(old.getTime() + 1_000);
// Another spelling of the same target records another caller path, so it
// keeps its own record rather than recovering the first run's.
const spelled = await runOn(relative(process.cwd(), target));
expect(spelled.evidence_bundle!.record_sha256).not.toBe(sha256);
expect((await files(directory)).sort()).toEqual(
[`${sha256}.json`, `${spelled.evidence_bundle!.record_sha256}.json`].sort(),
);
});
it("retains nothing with --no-retain or a zero setting", async () => {
const flagged = await workspace();
const off = await flagged.run("--no-retain");
expect(off.delivery).toMatchObject({ retained: "not-retained" });
expect(off.delivery.rerun).toBeDefined();
expect(off.delivery.retention_failure).toBeUndefined();
expect(off.evidence_bundle).toBeUndefined();
expect(await files(flagged.directory)).toEqual([]);
const seeded = await workspace({ REA_CLI_RETAINED_EVIDENCE_BYTES: "0" });
const zero = await seeded.run();
expect(zero.delivery).toMatchObject({ retained: "not-retained" });
expect(await files(seeded.directory)).toEqual([]);
});
it("falls back to the rerun arguments when the cache cannot be used", async () => {
const blocked = await workspace();
// Something that is not a directory where the cache directory belongs.
await mkdir(dirname(blocked.directory), { recursive: true });
await writeFile(blocked.directory, "not a directory");
const output = await blocked.run();
expect(parseEvidence(output.summary).operation).toBe("inspect_analysis_view");
expect(output.delivery).toMatchObject({ retained: "not-retained" });
expect(output.delivery.rerun).toBeDefined();
expect(output.delivery.retention_failure).toEqual(expect.any(String));
expect(output.evidence_bundle).toBeUndefined();
// A record larger than the cache is not kept either.
const small = await workspace({ REA_CLI_RETAINED_EVIDENCE_BYTES: "1024" });
const capped = await small.run();
expect(capped.delivery.retention_failure).toContain("larger than");
expect(await files(small.directory)).toEqual([]);
});
it("removes records past their age, then the least recently used over the cap", async () => {
const directory = join(
await createTestTempDirectory("rea-retain-evict-"),
"evidence",
);
await mkdir(directory, { mode: 0o700 });
const now = Date.now();
const record = async (digit: string, bytes: number, ageMs: number) => {
const name = `${digit.repeat(64)}.json`;
await writeFile(join(directory, name), "x".repeat(bytes));
const used = new Date(now - ageMs);
await utimes(join(directory, name), used, used);
return name;
};
const expired = await record("a", 10, CLI_RETAINED_EVIDENCE_MAX_AGE_MS + 1);
const oldest = await record("b", 400, 3_000);
const newer = await record("c", 400, 2_000);
// Not a retained record: never removed.
await writeFile(join(directory, "notes.txt"), "keep");
const retain = (digit: string, capBytes: number) =>
retainCliEvidence({
sha256: digit.repeat(64),
completeBytes: 400,
retention: { directory, capBytes },
now,
write: async (path) => {
await writeFile(path, "y".repeat(400), { flag: "wx", mode: 0o600 });
return ok({ bytes: 400 });
},
});
const named = (digit: string) => `${digit.repeat(64)}.json`;
// Within the cap, only the record past its age is removed.
expect(await retain("d", 10_000)).toMatchObject({
ok: true,
value: { reused: false },
});
expect((await files(directory)).sort()).toEqual(
[oldest, newer, named("d"), "notes.txt"].sort(),
);
// Over the cap, the least recently used go first, never the one just kept.
expect(await retain("e", 1_000)).toMatchObject({ ok: true });
expect((await files(directory)).sort()).toEqual(
[named("d"), named("e"), "notes.txt"].sort(),
);
expect(expired).toBe(named("a"));
// A bundle that outgrows the cache with the sources it cites is removed.
const oversized = await retainCliEvidence({
sha256: "f".repeat(64),
completeBytes: 100,
retention: { directory, capBytes: 500 },
now,
write: async (path) => {
await writeFile(path, "z".repeat(600), { flag: "wx", mode: 0o600 });
return ok({ bytes: 600 });
},
});
expect(oversized).toMatchObject({ ok: false });
if (!oversized.ok) expect(oversized.error.fileRemains).toBeUndefined();
expect(await files(directory)).not.toContain(named("f"));
// When removing an oversized bundle fails, retainCliEvidence reports
// `fileRemains: true` so the caller keeps the published file's receipt.
if (process.platform !== "win32" && process.getuid?.() !== 0) {
const stuckDir = join(
await createTestTempDirectory("rea-retain-stuck-"),
"evidence",
);
await mkdir(stuckDir, { mode: 0o700 });
try {
const stuck = await retainCliEvidence({
sha256: "9".repeat(64),
completeBytes: 100,
retention: { directory: stuckDir, capBytes: 500 },
now,
write: async (path) => {
await writeFile(path, "z".repeat(600), { flag: "wx", mode: 0o600 });
await chmod(stuckDir, 0o500);
return ok({ bytes: 600 });
},
});
expect(stuck).toMatchObject({
ok: false,
error: { fileRemains: true },
});
expect(await files(stuckDir)).toContain(named("9"));
} finally {
await chmod(stuckDir, 0o700);
}
}
});
it("keys a retained record by its complete content, not its Evidence ID", async () => {
const root = await createTestTempDirectory("rea-retain-digest-");
const path = join(root, "bytes");
await writeFile(path, randomBytes(4096));
const inspected = await createByteEntropyService().inspect({
path,
block_size: 256,
});
if (!inspected.ok) throw inspected.error;
// The caller's spelling is recorded but is not part of the Evidence ID.
const spelled = withEvidenceCallerInputPath(inspected.value, "./bytes");
expect(spelled.evidence_id).toBe(inspected.value.evidence_id);
expect(retainedEvidenceDigest(spelled)).not.toBe(
retainedEvidenceDigest(inspected.value),
);
expect(retainedEvidenceDigest(spelled)).toBe(
createHash("sha256").update(JSON.stringify(spelled)).digest("hex"),
);
});
it("never uses a cache whose path holds a value marked sensitive", async () => {
const marked = "s3cr3t-token";
const root = await createTestTempDirectory("rea-retain-sensitive-");
const directory = join(root, marked, "evidence");
const target = join(root, "bytes");
await writeFile(target, randomBytes(1024 * 1024));
const inspected = await createByteEntropyService().inspect({
path: target,
block_size: 256,
});
if (!inspected.ok) throw inspected.error;
const output = (await withCliEvidencePublication(
() =>
publishCliAnalysisEvidence(inspected, {
operation: "inspect_byte_entropy",
signal: new AbortController().signal,
detail: undefined,
evidenceOutput: undefined,
sensitiveValues: [marked],
}),
{ retention: { directory, capBytes: 1024 * 1024 * 1024 } },
)) as Output;
expect(output.delivery).toMatchObject({ retained: "not-retained" });
expect(output.delivery.retention_failure).toEqual(expect.any(String));
expect(JSON.stringify(output)).not.toContain(marked);
expect(await files(join(root, marked))).toEqual([]);
// A symlinked cache root whose resolved target holds a marked value is also refused.
const secretRoot = join(root, marked);
const linkRoot = join(root, "cache-link");
await mkdir(secretRoot, { recursive: true, mode: 0o700 });
await symlink(secretRoot, linkRoot);
const linked = (await withCliEvidencePublication(
() =>
publishCliAnalysisEvidence(inspected, {
operation: "inspect_byte_entropy",
signal: new AbortController().signal,
detail: undefined,
evidenceOutput: undefined,
sensitiveValues: [marked],
}),
{
retention: {
directory: join(linkRoot, "evidence"),
capBytes: 1024 * 1024 * 1024,
},
},
)) as Output;
expect(linked.delivery).toMatchObject({ retained: "not-retained" });
expect(linked.delivery.retention_failure).toEqual(expect.any(String));
expect(JSON.stringify(linked)).not.toContain(marked);
expect(await files(join(secretRoot, "evidence"))).toEqual([]);
});
it("withdraws the publication receipt of a bundle the cache discards", async () => {
const root = await createTestTempDirectory("rea-retain-receipt-");
const directory = join(root, "evidence");
const target = join(root, "bytes");
await writeFile(target, randomBytes(1024 * 1024));
const inspected = await createByteEntropyService().inspect({
path: target,
block_size: 256,
});
if (!inspected.ok) throw inspected.error;
// The record fits the cache; its bundle, with the bundle's own fields, does not.
const capBytes = Buffer.byteLength(JSON.stringify(inspected.value)) + 16;
const { output, receipt } = await withCliEvidencePublication(
async () => ({
output: (await publishCliAnalysisEvidence(inspected, {
operation: "inspect_byte_entropy",
signal: new AbortController().signal,
detail: undefined,
evidenceOutput: undefined,
})) as Output,
receipt: cliEvidencePublicationReceipt(),
}),
{ retention: { directory, capBytes } },
);
expect(output.delivery).toMatchObject({ retained: "not-retained" });
expect(output.delivery.retention_failure).toContain("larger than");
expect(receipt).toBeUndefined();
expect(await files(directory)).toEqual([]);
});
// Windows resolves .. lexically; POSIX resolves it after the link.
it.skipIf(HOST_PLATFORM.platform === "win32")(
"keeps the filesystem meaning of a cache path with .. after a symbolic link",
async () => {
const root = await realpath(
await createTestTempDirectory("rea-retain-dotdot-"),
);
await mkdir(join(root, "real", "deep"), { recursive: true });
await symlink(join(root, "real", "deep"), join(root, "link"));
// The kernel resolves link/.. to real; lexical joining would give root.
const directory = join(root, "link") + "/../evidence";
const kept = await retainCliEvidence({
sha256: "e".repeat(64),
completeBytes: 10,
retention: { directory, capBytes: 1_000 },
write: async (path) => {
await writeFile(path, "y".repeat(10), { flag: "wx", mode: 0o600 });
return ok({ bytes: 10 });
},
});
expect(kept).toMatchObject({
ok: true,
value: { path: join(root, "real", "evidence", `${"e".repeat(64)}.json`) },
});
expect(await files(join(root, "evidence"))).toEqual([]);
},
);
+1
View File
@@ -48,6 +48,7 @@ it("renders type placeholders, shown defaults and aliases", () => {
" --help Show help",
" --json Shorthand for --format json",
" --llms, --llms-full Print LLM-readable manifest",
" --no-retain Write no over-budget result to the retained-Evidence cache",
" --schema Show JSON Schema for command",
" --token-count Print token count of output (instead of output)",
" --token-limit <n> Limit output to n tokens",
@@ -418,7 +418,7 @@ it("budgets tools whose SDK schema defers validation to the application", async
});
});
it("writes nothing for CLI overflow without --evidence_output and names both rerun commands", async () => {
it("writes nothing for CLI overflow with --no-retain and names both rerun commands", async () => {
const input = await entropyTarget(1024 * 1024);
// Every location a spill could use is a fresh, empty directory.
const home = await createTestTempDirectory("rea-agent-budget-home-");
@@ -437,6 +437,7 @@ it("writes nothing for CLI overflow without --evidence_output and names both rer
"--block-size",
"256",
"--json",
"--no-retain",
];
let stdout = "";
let exitCode = 0;
+1 -1
View File
@@ -1,6 +1,6 @@
$ COMPLETE=bash rea -- rea setup -
exit: 0
--- stdout
--yes<0x0b>--install-hopper<0x0b>--desktop-build<0x0b>--install-agentenv<0x0b>--client<0x0b>--skill-client<0x0b>--tool-families<0x0b>--tool-catalog-profile<0x0b>--all-detected<0x0b>--skill<0x0b>--dry-run<0x0b>--accessible<0x0b>-y<0x0b>--format<0x0b>--filter-output<0x0b>--columns<0x0b>--token-limit<0x0b>--token-offset<0x0b>--full-output<0x0b>--llms<0x0b>--llms-full<0x0b>--help<0x0b>--schema<0x0b>--json<0x0b>--token-count<0x0b>--timings<0x0b>-h<end>
--yes<0x0b>--install-hopper<0x0b>--desktop-build<0x0b>--install-agentenv<0x0b>--client<0x0b>--skill-client<0x0b>--tool-families<0x0b>--tool-catalog-profile<0x0b>--all-detected<0x0b>--skill<0x0b>--dry-run<0x0b>--accessible<0x0b>-y<0x0b>--format<0x0b>--filter-output<0x0b>--columns<0x0b>--token-limit<0x0b>--token-offset<0x0b>--full-output<0x0b>--llms<0x0b>--llms-full<0x0b>--help<0x0b>--schema<0x0b>--json<0x0b>--token-count<0x0b>--timings<0x0b>--no-retain<0x0b>-h<end>
--- stderr
<end>
@@ -25,6 +25,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -33,6 +33,7 @@ Global Options:
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--mcp Start as MCP stdio server
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -25,6 +25,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -29,6 +29,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -34,6 +34,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -30,6 +30,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -18,6 +18,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -21,6 +21,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -27,6 +27,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -22,6 +22,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -29,6 +29,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -19,6 +19,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -16,6 +16,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -16,6 +16,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -33,6 +33,7 @@ Global Options:
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--mcp Start as MCP stdio server
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -33,6 +33,7 @@ Global Options:
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--mcp Start as MCP stdio server
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -33,6 +33,7 @@ Global Options:
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--mcp Start as MCP stdio server
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -33,6 +33,7 @@ Global Options:
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--mcp Start as MCP stdio server
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -15,6 +15,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
@@ -26,6 +26,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -25,6 +25,7 @@ Global Options:
--help Show help
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+1
View File
@@ -33,6 +33,7 @@ Global Options:
--json Shorthand for --format json
--llms, --llms-full Print LLM-readable manifest
--mcp Start as MCP stdio server
--no-retain Write no over-budget result to the retained-Evidence cache
--schema Show JSON Schema for command
--token-count Print token count of output (instead of output)
--token-limit <n> Limit output to n tokens
+3
View File
@@ -181,6 +181,9 @@ export default defineConfig({
// complete Evidence, as the in-process harness default does. Delivery
// tests set their own budget; this is the largest accepted seed.
REA_AGENT_RESULT_BUDGET_BYTES: String(10 * 1024 * 1024),
// Nothing a test runs writes to the user's retained-Evidence cache;
// retention tests select a temporary cache and their own size.
REA_CLI_RETAINED_EVIDENCE_BYTES: "0",
},
maxWorkers: MAX_TEST_WORKERS,
projects,