Files
rea/src/application/ProcessCli.ts
T
morluto 53fe7d6d3b refactor(config): take the environment as an input at every configuration read (#554)
* fix(platform): accept absolute paths for any host and stop blaming the ceiling for a missing grant

Addresses #548 and #545.

#548: processScenarioSchema required a leading "/" for executable,
working_directory and filesystem_roots, so no process scenario could be
expressed on Windows at all. The report suggested node:path's isAbsolute, but
that answers for the host running the check: on Linux `C:\tools` is not
absolute, so a scenario captured on Windows would fail validation when it is
replayed, compared, or asserted in a test on another host. A boundary schema
must not vary with its evaluator, so the check accepts the POSIX form, a
Windows drive path and a UNC share everywhere. The rejection message now names
the constraint instead of leaving the caller to infer it from "invalid request".
The HTTP `path` field inside `checkpoints` is an URL path and is deliberately
left alone.

I checked whether this merely moved the failure downstream: containment is
enforced by isPathWithinRoot, which already uses host-aware path.relative, so
validation really was the only blocker.

#545: when a scope is inside the administrator ceiling but no grant was ever
issued, the denial still pointed at widening the ceiling -- advice that cannot
help, since the ceiling already permits the operation. The `missing` payload is
computed against candidate *grants*, so it describes what a grant must cover,
not a ceiling gap. `PermissionRemediation` gains a `grant` variant saying
exactly that, and PermissionAuthority selects it when the denial is not a
ceiling violation. An explicitly requested remediation is still honoured, and a
genuine ceiling violation still says "configure".

* refactor(config): take the environment as an input at every configuration read

Completes B-2. Every `parseConfig(process.env)` site now reads from an
injected environment, so configuration-driven behaviour is a function of an
argument rather than of the machine running it.

The twelve sites were not equivalent, and treating them as one number would
have hidden the difference:

- **src/application/ (3 sites) were genuine defects.** `runSessionStatus`
  already injected its `logger` but hardcoded `process.env` for config, so the
  MCP path's `dependencies.env` never reached it; `captureProcessScenarioFile`
  and `runAnalysis` had the same problem. `runAnalysis` gained `environment` on
  the options object it already had, which is where its other injected
  dependencies live.

- **The CLI command layer (9 sites) is a documented boundary,** where
  `process.env` is legitimate. Rather than 9 independent ambient reads, they
  now share one seam: `createCli(environment)` passes it to the seven
  registrars that need configuration, and the nested helpers (`electronContext`,
  `runtimeContext`, `loadConfiguredAuthority`, `inspectJavaScriptReplay`) take
  it explicitly.

Every new parameter defaults to `process.env`, so all existing call sites are
unchanged and production behaviour is identical. The point is that the ambient
read is now a documented default at a boundary rather than a hidden dependency
deep inside behaviour.

`process.env` now survives in `src/` only as those default parameters —
nothing reads it at the point of use.

* style(cli): apply prettier formatting to the runtime observation command
2026-10-05 20:00:16 +08:00

212 lines
6.7 KiB
TypeScript

import { projectPermissionFailure } from "./PermissionFailure.js";
import { readFile } from "node:fs/promises";
import { parseConfig } from "../config.js";
import {
AnalysisError,
AnalysisInputError,
projectAnalysisError,
} from "../domain/errors.js";
import { createEvidence, parseEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { processTraceSpecificationSchema } from "../domain/processTraceComparison.js";
import {
compareProcessCaptures,
parseProcessScenario,
parseProcessCapture,
} from "../domain/processCapture.js";
import { captureProcessScenario } from "./ProcessHarness.js";
import { processCapturePermissionRequest } from "./ProcessCapturePermission.js";
import {
PROCESS_PROVIDER,
createProcessCaptureEvidence,
} from "./ProcessEvidence.js";
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
/** Safe process-command failure returned to the CLI adapter. */
export interface ProcessCliErrorOutput {
readonly error: "Process command failed";
readonly category: string;
readonly message: string;
}
/** Capture one JSON scenario through the same policy and evidence contract as MCP. */
export const captureProcessScenarioFile = async (
path: string,
environment: Readonly<Record<string, string | undefined>> = process.env,
) => {
try {
const input = await readJson(path);
let scenario;
try {
scenario = parseProcessScenario(input);
} catch {
throw new ProcessCliFailure(
"invalid_input",
"Process scenario is invalid. Check its required fields and limits, then try again.",
);
}
const config = parseConfig(environment);
if (!config.ok) return cliAnalysisError(config.error);
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) return cliAnalysisError(authority.error);
const authorized = await authority.value.authorize(
processCapturePermissionRequest(scenario),
"read",
);
if (!authorized.ok)
return cliAnalysisError(projectPermissionFailure(authorized.error));
const captured = await captureProcessScenario(
scenario,
config.value.processExecutionPolicy,
);
if (!captured.ok) return cliAnalysisError(captured.error);
return createProcessCaptureEvidence(scenario, captured.value);
} catch (cause: unknown) {
return projectProcessCliError(cause);
}
};
/** Compare two capture Evidence files and emit derived comparison Evidence. */
export const compareProcessEvidenceFiles = async (
leftPath: string,
rightPath: string,
traceSpecPath?: string,
) => {
try {
const left = parseCaptureEvidence(await readJson(leftPath));
const right = parseCaptureEvidence(await readJson(rightPath));
const traceSpecification =
traceSpecPath === undefined
? undefined
: parseTraceSpecification(await readJson(traceSpecPath));
const comparison =
traceSpecification === undefined
? compareProcessCaptures(left.capture, right.capture)
: compareProcessCaptures(left.capture, right.capture, {
traceSpecification,
});
return createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-comparison",
operation: "compare_process_captures",
parameters: {
left_evidence_id: left.id,
right_evidence_id: right.id,
left_normalization: left.capture.normalization,
right_normalization: right.capture.normalization,
...(traceSpecification === undefined
? {}
: { trace_spec: jsonValueSchema.parse(traceSpecification) }),
},
result: jsonValueSchema.parse(comparison),
confidence: "derived",
authority: "analyst-inference",
limitations: comparison.limitations,
locations: [...left.locations, ...right.locations],
evidenceLinks: [left.id, right.id],
});
} catch (cause: unknown) {
return projectProcessCliError(cause);
}
};
const parseCaptureEvidence = (input: unknown) => {
let evidence;
try {
evidence = parseEvidence(input);
} catch {
throw invalidCaptureEvidence();
}
if (
evidence.operation !== "capture_process_scenario" ||
evidence.predicate_type !== "rea.process-capture" ||
evidence.provider.id !== PROCESS_PROVIDER.id ||
evidence.provider.version !== PROCESS_PROVIDER.version
) {
throw new ProcessCliFailure(
"invalid_input",
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
);
}
try {
return {
id: evidence.evidence_id,
capture: parseProcessCapture(evidence.normalized_result),
locations: evidence.locations,
};
} catch {
throw invalidCaptureEvidence();
}
};
const parseTraceSpecification = (input: unknown) => {
const parsed = processTraceSpecificationSchema.safeParse(input);
if (parsed.success) return parsed.data;
throw new AnalysisInputError(
"compare-process-captures",
{ cause: parsed.error },
projectInputIssues(parsed.error.issues, input),
);
};
const invalidCaptureEvidence = (): ProcessCliFailure =>
new ProcessCliFailure(
"invalid_input",
"Capture evidence is malformed. Create new capture evidence, then try again.",
);
const readJson = async (path: string): Promise<unknown> => {
let bytes;
try {
bytes = await readFile(path);
} catch {
throw new ProcessCliFailure(
"invalid_input",
"Process input file could not be read. Check that the path exists and is readable.",
);
}
try {
const parsed: unknown = JSON.parse(bytes.toString("utf8"));
return parsed;
} catch {
throw new ProcessCliFailure(
"invalid_input",
"Process input file is not valid JSON. Repair the file, then try again.",
);
}
};
class ProcessCliFailure extends Error {
constructor(
readonly category: string,
readonly userMessage: string,
) {
super(userMessage);
}
}
const cliAnalysisError = (error: AnalysisError): ProcessCliErrorOutput => ({
error: "Process command failed",
...projectAnalysisError(error),
});
/** Project any process CLI failure without exposing its cause. */
export const projectProcessCliError = (
cause: unknown,
): ProcessCliErrorOutput => {
if (cause instanceof ProcessCliFailure)
return {
error: "Process command failed",
category: cause.category,
message: cause.userMessage,
};
if (cause instanceof AnalysisError) return cliAnalysisError(cause);
return {
error: "Process command failed",
category: "execution_failure",
message:
"Process command could not complete. Check the input files and run `rea doctor`, then try again.",
};
};