Files
rea/src/cliJavaScriptRuntimeCommands.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

144 lines
4.8 KiB
TypeScript

import { Cli, z } from "incur";
import {
listJavaScriptRuntimeTargets,
observeJavaScriptRuntime,
} from "./application/JavaScriptRuntimeObservationService.js";
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
import { V8InspectorProvider } from "./browser/V8InspectorProvider.js";
import { CLI_COMMANDS } from "./cliCommandNames.js";
import { logCliCommand } from "./cliLogging.js";
import { parseConfig } from "./config.js";
import {
javascriptRuntimeKindSchema,
listJavaScriptRuntimeTargetsInputSchema,
observeJavaScriptRuntimeInputSchema,
} from "./domain/javascriptRuntimeObservation.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
projectAnalysisError,
} from "./domain/errors.js";
import type { JsonValue } from "./domain/jsonValue.js";
import type { Logger } from "./logger.js";
const observeOptionsSchema = z.object({
runtimeKind: javascriptRuntimeKindSchema
.optional()
.describe(
"Declared target role; Inspector cannot authenticate the Electron role",
),
observationMs: z
.number()
.int()
.min(0)
.default(100)
.describe("Observation window in milliseconds"),
});
/** Register CLI equivalents of passive V8 Inspector tools. */
export const registerJavaScriptRuntimeObservationCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
environment: Readonly<Record<string, string | undefined>> = process.env,
): void => {
cli.command(CLI_COMMANDS.listJavaScriptRuntimeTargets, {
description: "List Node/Electron V8 Inspector targets",
args: z.object({
endpoint: z.string().describe("Literal-loopback Inspector endpoint"),
}),
run: ({ args }) =>
logCliCommand(
logger,
CLI_COMMANDS.listJavaScriptRuntimeTargets,
async () => {
const context = await runtimeContext(
"list_javascript_runtime_targets",
);
if (!context.ok) return context.error;
const parsed = listJavaScriptRuntimeTargetsInputSchema.safeParse({
inspector_endpoint: args.endpoint,
});
if (!parsed.success)
return inputError("list_javascript_runtime_targets");
const result = await listJavaScriptRuntimeTargets(
context.provider,
context.authority,
parsed.data,
);
return result.ok ? result.value : cliError(result.error);
},
),
});
cli.command(CLI_COMMANDS.observeJavaScriptRuntime, {
description: "Passively observe one exact Node/Electron Inspector target",
args: z.object({
endpoint: z.string().describe("Literal-loopback Inspector endpoint"),
targetId: z
.string()
.describe("Target from list-javascript-runtime-targets"),
}),
options: observeOptionsSchema,
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.observeJavaScriptRuntime, async () => {
const context = await runtimeContext(
"observe_javascript_runtime",
environment,
);
if (!context.ok) return context.error;
const parsed = observeJavaScriptRuntimeInputSchema.safeParse({
inspector_endpoint: args.endpoint,
target_id: args.targetId,
runtime_kind: options.runtimeKind,
observation_ms: options.observationMs,
});
if (!parsed.success) return inputError("observe_javascript_runtime");
const result = await observeJavaScriptRuntime(
context.provider,
context.authority,
parsed.data,
);
return result.ok ? result.value : cliError(result.error);
}),
});
};
const runtimeContext = async (
operation: string,
environment: Readonly<Record<string, string | undefined>> = process.env,
) => {
const config = parseConfig(environment);
if (!config.ok) return { ok: false as const, error: cliError(config.error) };
const policy = config.value.v8InspectorObservationPolicy;
if (policy.status === "disabled")
return {
ok: false as const,
error: cliError(
new AnalysisCapabilityUnavailableError(
"rea-v8-inspector",
operation,
"V8 Inspector observation is disabled; enable REA_V8_INSPECTOR_OBSERVE_ENABLED to authorize loopback endpoints",
),
),
};
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok)
return { ok: false as const, error: cliError(authority.error) };
return {
ok: true as const,
authority: authority.value,
provider: new V8InspectorProvider(),
};
};
const inputError = (operation: string): JsonValue =>
cliError(new AnalysisInputError(operation));
const cliError = (
error: Parameters<typeof projectAnalysisError>[0],
): JsonValue => ({
error: "JavaScript runtime observation failed",
...projectAnalysisError(error),
});