Files
reverse-engineering-anything/src/cli/analysisViewCommands.ts
T
morluto 2bb554e8b0 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
2026-11-25 21:39:33 +00:00

153 lines
6.3 KiB
TypeScript

import { z } from "zod";
import { ArtifactResourceScope } from "../resources/index.js";
import { ANALYSIS_VIEW_PROVIDER } from "../domain/investigationProviders.js";
import { inspectEvidenceBundleCommand } from "../application/EvidenceBundleCommands.js";
import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "../contracts/analysisViewToolContracts.js";
import {
getEvidenceBundleInputSchema,
importEvidenceBundleInputSchema,
} from "../contracts/sessionToolSchemas.js";
import { CLI_COMMANDS } from "../contracts/cliCommandNames.js";
import { parseCliJsonInput } from "./cliJsonInput.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import type { Logger } from "pino";
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";
import { jsonInputArgument } from "./jsonInputArgument.js";
const inspectEvidenceBundleCliInputSchema =
getEvidenceBundleInputSchema.safeExtend({
path: importEvidenceBundleInputSchema.shape.path,
});
/** Project selected views of completed analysis Evidence through the CLI. */
export const registerAnalysisViewCommands = (
cli: CliInstance,
logger: Logger,
): void => {
registerCliCommand(cli, CLI_COMMANDS.inspectEvidenceBundle, {
description:
"Inspect a local Evidence bundle completely, as optionally paged discovery metadata, as a page of selected complete records, or as direct-link and retained-closure membership and direct referrers.",
args: z.object({
inputJson: jsonInputArgument(
"JSON or JSON file with absolute path, detail, optional source-record filters, summary/records/links offset/limit, and links traversal/linked_evidence_id/link_status (default all with a linked ID, otherwise missing)",
inspectEvidenceBundleCliInputSchema,
),
}),
run: ({ args }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectEvidenceBundle, async () => {
const input = await parseCliJsonInput(
args.inputJson,
CLI_COMMANDS.inspectEvidenceBundle,
signal,
);
if (!input.ok) return input.error;
const parsed = inspectEvidenceBundleCliInputSchema.safeParse(
input.value,
);
if (!parsed.success)
return {
error: "Evidence bundle inspection failed",
...projectAnalysisError(
analysisInputErrorFromIssues(
CLI_COMMANDS.inspectEvidenceBundle,
parsed.error.issues,
input.value,
),
),
};
const result = await inspectEvidenceBundleCommand(
parsed.data,
signal,
);
return result.ok
? result.value
: {
error: "Evidence bundle inspection failed",
...projectAnalysisError(result.error),
};
}),
),
});
registerContractDocumentCommand(
cli,
logger,
contractNamed(ANALYSIS_VIEW_TOOL_CONTRACTS, "inspect_analysis_view"),
{
description:
"Project a selected view of completed Evidence JSON for a supported analysis operation. For inventory rows, use --format csv or --format tsv with --filter-output normalized_result.items and --columns logical_path,artifact_id (if those fields are included in the view).",
document: "Inline workflow JSON or JSON file path",
// An evidence-file path is resolved against the operator's working directory.
callerPaths: [["source", "path"]],
cliOptions: {
evidenceBundle: localPathStringSchema
.optional()
.describe(
"Read the exact retained-evidence source ID from this local Evidence bundle without reopening the target; omit for inline Evidence",
),
},
},
async (document, { signal, operation, cliOptions }) => {
const resources = new ArtifactResourceScope();
const bundlePath = cliOptions.evidenceBundle;
const result = await finishAnalysisCommand(
async () => {
const { inspectAnalysisView } =
await import("../application/analysisView/AnalysisViewService.js");
return inspectAnalysisView(document, undefined, {
signal,
resources,
...(bundlePath === undefined
? {}
: { evidenceBundlePath: bundlePath }),
});
},
resources,
ANALYSIS_VIEW_PROVIDER.id,
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
? result.value
: bundlePath === undefined
? { error: "Application workflow failed", ...result.error }
: result.error;
},
);
};