Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
446a1e5799 | ||
|
|
ae0197d160 | ||
|
|
246868232e | ||
|
|
ef7f2f9374 | ||
|
|
6a3fd5b4ce | ||
|
|
f840e70749 | ||
|
|
ae8b1c5ca9 | ||
|
|
31b40f39e4 | ||
|
|
2575b30dfc | ||
|
|
e8ed3073ac |
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "1.4.0"
|
||||
".": "1.5.0"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,39 @@
|
||||
# Changelog
|
||||
|
||||
## [1.5.0](https://github.com/morluto/rea/compare/rea-agents-1.4.0...rea-agents-1.5.0) (2026-07-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add passive website reverse engineering ([9986971](https://github.com/morluto/rea/commit/998697155dcc733be73e75bc77c069638942f111))
|
||||
* add passive website reverse engineering ([2c1ceab](https://github.com/morluto/rea/commit/2c1ceabbf1f117daafe166e1134b47737b38e1f6))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **browser:** drop disallowed redirect evidence ([8481be9](https://github.com/morluto/rea/commit/8481be9c9709b13f572fefefcf8508d9e2605386))
|
||||
* **browser:** scope CDP events and fail closed ([5279d77](https://github.com/morluto/rea/commit/5279d7755c74df579028ce51b4bc53b089bb2749))
|
||||
* **browser:** scope workers and binary frame sizes ([dfc06cf](https://github.com/morluto/rea/commit/dfc06cf0ad4a39719ef74846cb83f05e7b6f6289))
|
||||
* harden PTY events and configured roots ([ae8b1c5](https://github.com/morluto/rea/commit/ae8b1c5ca9c2d122d7fc30ebfa25e08d57ca7a51))
|
||||
* harden PTY events and configured roots ([31b40f3](https://github.com/morluto/rea/commit/31b40f39e4c29a077deebefbe29e90c30e50cd0c))
|
||||
* **permission:** defer cache write grants ([6a3fd5b](https://github.com/morluto/rea/commit/6a3fd5b4cec7569eebfe8a7ca6a7c0c1e3a7340d))
|
||||
* **permission:** defer cache write grants ([f840e70](https://github.com/morluto/rea/commit/f840e70749ffadfe34cf8b7e464b54e8ffebd816))
|
||||
* resolve triaged correctness issues ([2575b30](https://github.com/morluto/rea/commit/2575b30dfcb79c2e26ed16311f780a8723578c6a))
|
||||
* resolve triaged correctness issues ([e8ed307](https://github.com/morluto/rea/commit/e8ed3073ac915e32b5ea630446ed6e14bc788119))
|
||||
* resolve validation and artifact edge cases ([2468682](https://github.com/morluto/rea/commit/246868232e4196394fbc6e67cfae4d3ca214fe60))
|
||||
* resolve validation and artifact edge cases ([ef7f2f9](https://github.com/morluto/rea/commit/ef7f2f93747f0a4d9f70c9fc2e252456d20843f3))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* add Hopper screenshot to README ([a699fdd](https://github.com/morluto/rea/commit/a699fdd6a5cc9c9812c7d78fd98b51469488866f))
|
||||
* add Hopper screenshot to README ([08981a3](https://github.com/morluto/rea/commit/08981a31b5e9b76e15914c0570244158d491e047))
|
||||
|
||||
|
||||
### Tests
|
||||
|
||||
* **cli:** allow cold-start integration timing ([7d5621d](https://github.com/morluto/rea/commit/7d5621dfbc4333f99846cbe52227d3b4f53ee0cd))
|
||||
|
||||
## [1.4.0](https://github.com/morluto/rea/compare/rea-agents-1.3.0...rea-agents-1.4.0) (2026-07-14)
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -31,8 +31,8 @@ lint:dead` rejects unused files, exports, and dependencies.
|
||||
Set `REA_LOG_LEVEL` to `trace`, `debug`, `info`, `warn`, `error`, `fatal`, or
|
||||
`silent` to control structured JSON diagnostics. MCP mode defaults to `info` and
|
||||
always writes logs to stderr so the stdio protocol remains intact. One-shot CLI
|
||||
logging is opt-in and writes to stderr when a level is configured, preserving
|
||||
machine-readable command output. Request arguments, bridge
|
||||
logging is opt-in and writes to stdout when a level is configured, preserving
|
||||
machine-readable command output by default. Request arguments, bridge
|
||||
authentication tokens, and environment data are redacted.
|
||||
|
||||
Changes that claim real Hopper behavior must also be tested against two distinct binaries:
|
||||
|
||||
@@ -431,19 +431,6 @@ Run `npx -y rea-agents --help` for direct decompilation, bounded search and
|
||||
other options. `analyze` and `inspect` share the same overview workflow;
|
||||
`function`, `xrefs`, and `trace` return the same Evidence v2 envelopes as MCP.
|
||||
|
||||
CLI exit status is independent of output format, full output, filtering, and
|
||||
token limits:
|
||||
|
||||
| Status | Meaning |
|
||||
| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `0` | The requested operation completed truthfully. Explicit unknown, bounded, or truncated evidence remains successful when the operation completed under its declared contract. |
|
||||
| `1` | Argument validation, approval or policy, provider or analysis, integrity, cancellation or timeout, serialization, or output failed. Structured output retains the typed category and safe diagnostic details when available. |
|
||||
|
||||
Machine-readable failures remain on stdout in the requested format; incidental
|
||||
diagnostics and progress use stderr. Signal termination retains the conventional
|
||||
status supplied by the shell and runtime. Shell pipelines should enable
|
||||
`pipefail` when the REA status must propagate through later commands.
|
||||
|
||||
Or install the `rea` command globally:
|
||||
|
||||
```bash
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "rea-agents",
|
||||
"version": "1.4.0",
|
||||
"version": "1.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "rea-agents",
|
||||
"version": "1.4.0",
|
||||
"version": "1.5.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "rea-agents",
|
||||
"version": "1.4.0",
|
||||
"version": "1.5.0",
|
||||
"description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -95,11 +95,11 @@ export class AnalysisSnapshotCache {
|
||||
this.#target.architecture !== snapshot.target.architecture)
|
||||
)
|
||||
this.#entries.clear();
|
||||
this.#target = snapshot.target;
|
||||
this.#target = structuredClone(snapshot.target);
|
||||
let imported = 0;
|
||||
for (const entry of snapshot.entries) {
|
||||
if (!this.#entries.has(entry.query_id)) imported += 1;
|
||||
this.#entries.set(entry.query_id, entry);
|
||||
this.#entries.set(entry.query_id, structuredClone(entry));
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
@@ -114,7 +114,7 @@ export class AnalysisSnapshotCache {
|
||||
snapshot_version: 1,
|
||||
target: snapshotTarget(target),
|
||||
entries: this.entries(),
|
||||
evidence_bundle: evidenceBundle,
|
||||
evidence_bundle: structuredClone(evidenceBundle),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -138,9 +138,9 @@ export class AnalysisSnapshotCache {
|
||||
|
||||
/** Return canonical entries for persistence. */
|
||||
entries(): AnalysisSnapshotEntry[] {
|
||||
return [...this.#entries.values()].sort((left, right) =>
|
||||
left.query_id.localeCompare(right.query_id),
|
||||
);
|
||||
return [...this.#entries.values()]
|
||||
.sort((left, right) => left.query_id.localeCompare(right.query_id))
|
||||
.map((entry) => structuredClone(entry));
|
||||
}
|
||||
|
||||
/** Replay an exact provider-specific query, marking its cached provenance. */
|
||||
@@ -159,7 +159,7 @@ export class AnalysisSnapshotCache {
|
||||
const cached = this.#entries.get(queryId);
|
||||
if (cached === undefined) return undefined;
|
||||
const subject = cached.execution.subject;
|
||||
return {
|
||||
return structuredClone({
|
||||
result: cached.execution.result,
|
||||
rawResult: cached.execution.raw_result,
|
||||
provider: cached.execution.provider,
|
||||
@@ -183,7 +183,7 @@ export class AnalysisSnapshotCache {
|
||||
format: subject.format,
|
||||
architecture: subject.architecture,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Record one successful immutable call unless the cache is full. */
|
||||
|
||||
@@ -30,6 +30,17 @@ export interface MutableOccurrence {
|
||||
limitations: string[];
|
||||
}
|
||||
|
||||
/** Index the first occurrence for each canonical logical path. */
|
||||
export const indexOccurrencesByPath = (
|
||||
occurrences: readonly MutableOccurrence[],
|
||||
): ReadonlyMap<string, MutableOccurrence> => {
|
||||
const byPath = new Map<string, MutableOccurrence>();
|
||||
for (const occurrence of occurrences)
|
||||
if (!byPath.has(occurrence.logical_path))
|
||||
byPath.set(occurrence.logical_path, occurrence);
|
||||
return byPath;
|
||||
};
|
||||
|
||||
export const createOccurrence = (
|
||||
entry: ArtifactEntry,
|
||||
path: string,
|
||||
@@ -196,6 +207,7 @@ export const createArtifactEdges = (
|
||||
producer?: ArtifactCommand,
|
||||
): ArtifactEdge[] => {
|
||||
const byId = new Map(occurrences.map((item) => [item.occurrence_id, item]));
|
||||
const byPath = indexOccurrencesByPath(occurrences);
|
||||
const edges: ArtifactEdge[] = [];
|
||||
for (const occurrence of occurrences) {
|
||||
if (
|
||||
@@ -203,11 +215,8 @@ export const createArtifactEdges = (
|
||||
occurrence.artifact_id === null
|
||||
)
|
||||
continue;
|
||||
const mappedSource = occurrence.logical_path.endsWith(".map")
|
||||
? occurrences.find(
|
||||
({ logical_path: path }) =>
|
||||
path === occurrence.logical_path.slice(0, -".map".length),
|
||||
)
|
||||
const mappedSource = occurrence.logical_path.toLowerCase().endsWith(".map")
|
||||
? byPath.get(occurrence.logical_path.slice(0, -".map".length))
|
||||
: undefined;
|
||||
const parentArtifactId =
|
||||
mappedSource?.artifact_id ??
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
createOccurrence,
|
||||
createRootNode,
|
||||
digestCanonical,
|
||||
indexOccurrencesByPath,
|
||||
materializeDirectoryNodes,
|
||||
nearestParent,
|
||||
pageOf,
|
||||
@@ -180,11 +181,10 @@ export const scanCanonicalArtifactInventory = async (
|
||||
const occurrenceById = new Map(
|
||||
occurrences.map((occurrence) => [occurrence.occurrence_id, occurrence]),
|
||||
);
|
||||
const occurrenceByPath = indexOccurrencesByPath(occurrences);
|
||||
const integrityContradictions = pendingContradictions.map(
|
||||
(contradiction): IntegrityContradiction => {
|
||||
const occurrence = occurrences.find(
|
||||
({ logical_path: path }) => path === contradiction.logicalPath,
|
||||
);
|
||||
const occurrence = occurrenceByPath.get(contradiction.logicalPath);
|
||||
if (occurrence === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type ArtifactIntegrityPolicy,
|
||||
type ArtifactInventorySnapshot,
|
||||
} from "./ArtifactInventory.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
/** Resolve, authorize, and scan one artifact without a second path resolution. */
|
||||
export const scanAuthorizedArtifactInventory = async (
|
||||
@@ -24,7 +25,7 @@ export const scanAuthorizedArtifactInventory = async (
|
||||
);
|
||||
const [path, approved] = await Promise.all([
|
||||
realpath(inputPath),
|
||||
Promise.all(roots.map(async (root) => realpath(root))),
|
||||
canonicalizeConfiguredRoots(roots),
|
||||
]);
|
||||
if (!approved.some((root) => withinRoot(root, path)))
|
||||
throw new ArtifactReaderFailure(
|
||||
|
||||
@@ -113,7 +113,7 @@ export class BinarySession implements BinarySessionPort {
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity {
|
||||
if (operation !== undefined) {
|
||||
const exact = this.#capabilities?.get(operation)?.provider;
|
||||
if (exact !== undefined) return exact;
|
||||
if (exact !== undefined) return structuredClone(exact);
|
||||
if (enhancedToolNameSchema.safeParse(operation).success) {
|
||||
const providers = new Map<string, ProviderIdentity>();
|
||||
for (const descriptor of this.#capabilities?.values() ?? [])
|
||||
@@ -124,11 +124,11 @@ export class BinarySession implements BinarySessionPort {
|
||||
providers.set(descriptor.provider.id, descriptor.provider);
|
||||
if (providers.size === 1) {
|
||||
const provider = providers.values().next().value;
|
||||
if (provider !== undefined) return provider;
|
||||
if (provider !== undefined) return structuredClone(provider);
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.#providerIdentity;
|
||||
return structuredClone(this.#providerIdentity);
|
||||
}
|
||||
|
||||
/** Observe runtime provider-health changes that affect discovery metadata. */
|
||||
@@ -223,18 +223,21 @@ export class BinarySession implements BinarySessionPort {
|
||||
workspaceId: string,
|
||||
revision: number,
|
||||
): InvestigationWorkspace | undefined {
|
||||
return this.#investigationWorkspaces.get(
|
||||
const workspace = this.#investigationWorkspaces.get(
|
||||
`${workspaceId}:${String(revision)}`,
|
||||
);
|
||||
return workspace === undefined ? undefined : structuredClone(workspace);
|
||||
}
|
||||
|
||||
/** List retained workspace revisions in canonical identity order. */
|
||||
investigationWorkspaces(): readonly InvestigationWorkspace[] {
|
||||
return [...this.#investigationWorkspaces.values()].sort(
|
||||
(left, right) =>
|
||||
left.workspace_id.localeCompare(right.workspace_id) ||
|
||||
left.revision - right.revision,
|
||||
);
|
||||
return [...this.#investigationWorkspaces.values()]
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.workspace_id.localeCompare(right.workspace_id) ||
|
||||
left.revision - right.revision,
|
||||
)
|
||||
.map((workspace) => structuredClone(workspace));
|
||||
}
|
||||
|
||||
/** Create an approved residual unknown and immutable mutation evidence. */
|
||||
@@ -468,7 +471,9 @@ export class BinarySession implements BinarySessionPort {
|
||||
|
||||
/** Return the immutable artifact identity captured before Hopper launched. */
|
||||
activeTarget(): BinaryTarget | undefined {
|
||||
return this.#active?.target;
|
||||
return this.#active === undefined
|
||||
? undefined
|
||||
: structuredClone(this.#active.target);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,7 +5,9 @@ import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { EvidenceFileError } from "../domain/errors.js";
|
||||
import { isJsonWithinLimits } from "../domain/jsonLimits.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
/** Read bounded JSON data from a regular file beneath an approved root. */
|
||||
export const readBoundedJson = async (
|
||||
@@ -31,8 +33,9 @@ export const readBoundedJson = async (
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "invalid-json", { cause }));
|
||||
}
|
||||
const limits = validateJsonLimits(decoded, policy);
|
||||
return limits.ok ? ok(decoded) : limits;
|
||||
return isJsonWithinLimits(decoded, policy)
|
||||
? ok(decoded)
|
||||
: err(new EvidenceFileError("read", "too-large"));
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "io", { cause }));
|
||||
}
|
||||
@@ -82,8 +85,9 @@ const isApproved = async (
|
||||
candidate: string,
|
||||
roots: readonly string[],
|
||||
): Promise<boolean> => {
|
||||
for (const configuredRoot of roots) {
|
||||
const root = await realpath(resolve(configuredRoot));
|
||||
for (const root of await canonicalizeConfiguredRoots(
|
||||
roots.map((configuredRoot) => resolve(configuredRoot)),
|
||||
)) {
|
||||
const relation = relative(root, candidate);
|
||||
if (
|
||||
relation === "" ||
|
||||
@@ -94,35 +98,6 @@ const isApproved = async (
|
||||
return false;
|
||||
};
|
||||
|
||||
const validateJsonLimits = (
|
||||
root: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Result<null, EvidenceFileError> => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > policy.maxStringLength
|
||||
)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > policy.maxStringLength)
|
||||
return err(new EvidenceFileError("read", "too-large"));
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
/** Canonicalize configured policy roots while ignoring stale missing entries. */
|
||||
export const canonicalizeConfiguredRoots = async (
|
||||
roots: readonly string[],
|
||||
): Promise<string[]> => {
|
||||
const canonical: string[] = [];
|
||||
for (const root of roots) {
|
||||
try {
|
||||
canonical.push(await realpath(root));
|
||||
} catch (cause: unknown) {
|
||||
if (!isMissingPath(cause)) throw cause;
|
||||
}
|
||||
}
|
||||
return canonical;
|
||||
};
|
||||
|
||||
const isMissingPath = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT";
|
||||
@@ -59,6 +59,7 @@ export interface CrossVersionInvestigationExecution {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
readonly integrityContinueEnabled?: boolean;
|
||||
readonly authorizeWorkspaceWrite?: () => Promise<Result<null, AnalysisError>>;
|
||||
}
|
||||
|
||||
/** Run or resume a deterministic cross-version artifact investigation. */
|
||||
@@ -111,6 +112,7 @@ export const runCrossVersionInvestigation = async (
|
||||
session: execution.session,
|
||||
signal: execution.signal,
|
||||
progress: execution.progress,
|
||||
authorizeWorkspaceWrite: execution.authorizeWorkspaceWrite,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -127,6 +129,9 @@ const continueInvestigation = async (context: {
|
||||
readonly session: BinarySessionPort | undefined;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly progress: ProgressReporter | undefined;
|
||||
readonly authorizeWorkspaceWrite:
|
||||
| (() => Promise<Result<null, AnalysisError>>)
|
||||
| undefined;
|
||||
}): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
const left = targetFor(context.snapshots.left);
|
||||
const right = targetFor(context.snapshots.right);
|
||||
@@ -155,6 +160,10 @@ const continueInvestigation = async (context: {
|
||||
);
|
||||
if (context.initial !== null && existing?.status === "complete")
|
||||
return completeOutcome(context.initial, existing, true, context.session);
|
||||
if (context.authorizeWorkspaceWrite !== undefined) {
|
||||
const authorized = await context.authorizeWorkspaceWrite();
|
||||
if (!authorized.ok) return authorized;
|
||||
}
|
||||
const pages = createInventoryEvidencePages(context.input, context.snapshots);
|
||||
if (!pages.ok) return pages;
|
||||
if (isCancelled(context.signal))
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { PermissionCapability } from "../domain/permissionPolicy.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
PermissionPathError,
|
||||
type PermissionAuthority,
|
||||
} from "./PermissionAuthority.js";
|
||||
|
||||
interface RootPermissionRequest {
|
||||
readonly capability: PermissionCapability;
|
||||
readonly roots: readonly string[];
|
||||
readonly access: "read" | "write";
|
||||
readonly operation: string;
|
||||
}
|
||||
|
||||
/** Authorize one root-scoped operation and project policy path failures. */
|
||||
export const authorizeRootPermission = async (
|
||||
authority: PermissionAuthority,
|
||||
request: RootPermissionRequest,
|
||||
): Promise<Result<null, AnalysisError>> => {
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: request.capability,
|
||||
roots: request.roots,
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `${request.operation}:${request.capability}:${request.roots.join(":")}`,
|
||||
},
|
||||
request.access,
|
||||
);
|
||||
return authorized.ok
|
||||
? ok(null)
|
||||
: err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export interface DeferredFileWriteAuthorization {
|
||||
readonly authorizeWrite: () => Promise<Result<null, AnalysisError>>;
|
||||
}
|
||||
|
||||
/** Authorize an existing file read and defer write authority until requested. */
|
||||
export const authorizeFileReadWithDeferredWrite = async (
|
||||
authority: PermissionAuthority,
|
||||
input: {
|
||||
readonly path: string;
|
||||
readonly readCapability: PermissionCapability;
|
||||
readonly writeCapability: PermissionCapability;
|
||||
readonly operation: string;
|
||||
},
|
||||
): Promise<Result<DeferredFileWriteAuthorization, AnalysisError>> => {
|
||||
const read = await authority.authorize(
|
||||
{
|
||||
capability: input.readCapability,
|
||||
roots: [input.path],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `${input.operation}:${input.readCapability}:${input.path}`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
let writeAuthorization: Promise<Result<null, AnalysisError>> | undefined;
|
||||
if (!read.ok) {
|
||||
if (
|
||||
!(read.error instanceof PermissionPathError) ||
|
||||
read.error.reason !== "not_found"
|
||||
)
|
||||
return err(
|
||||
read.error instanceof PermissionRequiredError
|
||||
? read.error
|
||||
: new AnalysisProtocolError(read.error.message, {
|
||||
cause: read.error,
|
||||
}),
|
||||
);
|
||||
writeAuthorization = authorizeRootPermission(authority, {
|
||||
capability: input.writeCapability,
|
||||
roots: [input.path],
|
||||
access: "write",
|
||||
operation: input.operation,
|
||||
});
|
||||
const authorized = await writeAuthorization;
|
||||
if (!authorized.ok) return authorized;
|
||||
}
|
||||
return ok({
|
||||
authorizeWrite: () =>
|
||||
(writeAuthorization ??= authorizeRootPermission(authority, {
|
||||
capability: input.writeCapability,
|
||||
roots: [input.path],
|
||||
access: "write",
|
||||
operation: input.operation,
|
||||
})),
|
||||
});
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { parseConfig } from "../config.js";
|
||||
import { parseConfig, type AppConfig } from "../config.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { createServerIdentity } from "../serverIdentity.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
@@ -30,6 +30,10 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import {
|
||||
authorizeFileReadWithDeferredWrite,
|
||||
type DeferredFileWriteAuthorization,
|
||||
} from "./DeferredFileAuthorization.js";
|
||||
|
||||
const WORKFLOW_PROVIDER = {
|
||||
id: "rea-workflow",
|
||||
@@ -59,6 +63,7 @@ export const runDirectAnalysis = async (
|
||||
readonly logger?: Logger;
|
||||
readonly snapshotPath?: string | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
} = {},
|
||||
): Promise<JsonValue> =>
|
||||
withProcessCancellation(options.signal, (signal) =>
|
||||
@@ -66,6 +71,9 @@ export const runDirectAnalysis = async (
|
||||
logger: options.logger ?? silentLogger,
|
||||
snapshotPath: options.snapshotPath,
|
||||
signal,
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
: { permissionAuthority: options.permissionAuthority }),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -108,23 +116,8 @@ const authorizeAnalysis = async (
|
||||
authority: PermissionAuthority,
|
||||
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
snapshotPath: string | undefined,
|
||||
): Promise<Result<null, AnalysisError>> => {
|
||||
const requests = [];
|
||||
if (snapshotPath !== undefined) {
|
||||
requests.push(
|
||||
{
|
||||
capability: "snapshot_read" as const,
|
||||
path: snapshotPath,
|
||||
access: "write" as const,
|
||||
},
|
||||
{
|
||||
capability: "snapshot_write" as const,
|
||||
path: snapshotPath,
|
||||
access: "write" as const,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (tool === "extract_artifact" && typeof arguments_.output_root === "string")
|
||||
requests.push({
|
||||
capability: "artifact_extract" as const,
|
||||
@@ -181,6 +174,62 @@ const authorizeAnalysis = async (
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const permissionAuthorityFor = (
|
||||
config: AppConfig,
|
||||
supplied: PermissionAuthority | undefined,
|
||||
): ReturnType<typeof loadConfiguredPermissionAuthority> =>
|
||||
supplied === undefined
|
||||
? loadConfiguredPermissionAuthority(config)
|
||||
: Promise.resolve(ok(supplied));
|
||||
|
||||
const authorizeSnapshotAccess = async (
|
||||
authority: PermissionAuthority,
|
||||
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
|
||||
snapshotPath: string | undefined,
|
||||
): Promise<
|
||||
Result<DeferredFileWriteAuthorization | undefined, AnalysisError>
|
||||
> =>
|
||||
snapshotPath === undefined
|
||||
? ok(undefined)
|
||||
: authorizeFileReadWithDeferredWrite(authority, {
|
||||
path: snapshotPath,
|
||||
readCapability: "snapshot_read",
|
||||
writeCapability: "snapshot_write",
|
||||
operation: tool,
|
||||
});
|
||||
|
||||
const authorizeDeferredWrite = (
|
||||
authorization: DeferredFileWriteAuthorization | undefined,
|
||||
): Promise<Result<null, AnalysisError>> =>
|
||||
authorization?.authorizeWrite() ?? Promise.resolve(ok(null));
|
||||
|
||||
const authorizeAnalysisRun = async (input: {
|
||||
readonly config: AppConfig;
|
||||
readonly suppliedAuthority: PermissionAuthority | undefined;
|
||||
readonly tool: NativeToolName | ArtifactToolName | DirectAnalysisTool;
|
||||
readonly arguments: Readonly<Record<string, JsonValue>>;
|
||||
readonly snapshotPath: string | undefined;
|
||||
}): Promise<
|
||||
Result<DeferredFileWriteAuthorization | undefined, AnalysisError>
|
||||
> => {
|
||||
const authority = await permissionAuthorityFor(
|
||||
input.config,
|
||||
input.suppliedAuthority,
|
||||
);
|
||||
if (!authority.ok) return authority;
|
||||
const operation = await authorizeAnalysis(
|
||||
authority.value,
|
||||
input.tool,
|
||||
input.arguments,
|
||||
);
|
||||
if (!operation.ok) return operation;
|
||||
return authorizeSnapshotAccess(
|
||||
authority.value,
|
||||
input.tool,
|
||||
input.snapshotPath,
|
||||
);
|
||||
};
|
||||
|
||||
const runAnalysis = async (
|
||||
path: string,
|
||||
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
|
||||
@@ -189,22 +238,20 @@ const runAnalysis = async (
|
||||
readonly logger: Logger;
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly signal: AbortSignal;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
},
|
||||
): Promise<JsonValue> => {
|
||||
const { logger, signal, snapshotPath } = options;
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const permissionAuthority = await loadConfiguredPermissionAuthority(
|
||||
config.value,
|
||||
);
|
||||
if (!permissionAuthority.ok) return cliError(permissionAuthority.error);
|
||||
const authorized = await authorizeAnalysis(
|
||||
permissionAuthority.value,
|
||||
const authorization = await authorizeAnalysisRun({
|
||||
config: config.value,
|
||||
suppliedAuthority: options.permissionAuthority,
|
||||
tool,
|
||||
arguments_,
|
||||
arguments: arguments_,
|
||||
snapshotPath,
|
||||
);
|
||||
if (!authorized.ok) return cliError(authorized.error);
|
||||
});
|
||||
if (!authorization.ok) return cliError(authorization.error);
|
||||
const unavailable = snapshotUnavailable(
|
||||
snapshotPath,
|
||||
config.value.hopperLoaderArgs,
|
||||
@@ -222,6 +269,8 @@ const runAnalysis = async (
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
if (prepared.value.evidence !== undefined) return prepared.value.evidence;
|
||||
const writable = await authorizeDeferredWrite(authorization.value);
|
||||
if (!writable.ok) return cliError(writable.error);
|
||||
const { snapshot } = prepared.value;
|
||||
const opened = await session.open(
|
||||
path,
|
||||
|
||||
@@ -122,9 +122,11 @@ export class EvidenceLedger {
|
||||
|
||||
/** Export records in deterministic, semantically irrelevant ID order. */
|
||||
export(): EvidenceBundle {
|
||||
return createEvidenceBundle(
|
||||
[...this.#records.values()],
|
||||
[...this.#unknownRevisions.values()],
|
||||
return structuredClone(
|
||||
createEvidenceBundle(
|
||||
[...this.#records.values()],
|
||||
[...this.#unknownRevisions.values()],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -232,7 +234,7 @@ export class EvidenceLedger {
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(unknown);
|
||||
return ok(structuredClone(unknown));
|
||||
}
|
||||
|
||||
/** Apply one approved full-state update using optimistic revision matching. */
|
||||
@@ -277,7 +279,8 @@ export class EvidenceLedger {
|
||||
unknown.severity === filters.severity) &&
|
||||
(filters.domain === undefined || unknown.domain === filters.domain),
|
||||
)
|
||||
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id));
|
||||
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id))
|
||||
.map((unknown) => structuredClone(unknown));
|
||||
}
|
||||
|
||||
/** Return current resolution validity; imported invalid states are rejected. */
|
||||
@@ -295,7 +298,7 @@ export class EvidenceLedger {
|
||||
return ok({
|
||||
valid: unknown.status === "resolved",
|
||||
truthVerified: unknown.resolution?.disposition === "verified",
|
||||
unknown,
|
||||
unknown: structuredClone(unknown),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -331,7 +334,7 @@ export class EvidenceLedger {
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(unknown);
|
||||
return ok(structuredClone(unknown));
|
||||
}
|
||||
|
||||
#validateCandidate(
|
||||
|
||||
@@ -11,6 +11,7 @@ import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { isJsonWithinLimits } from "../domain/jsonLimits.js";
|
||||
import { InvestigationWorkspaceError } from "../domain/errors.js";
|
||||
import {
|
||||
parseInvestigationWorkspace,
|
||||
@@ -132,7 +133,7 @@ const readWorkspaceFile = async (
|
||||
new InvestigationWorkspaceError("read", "invalid-json", { cause }),
|
||||
);
|
||||
}
|
||||
if (!withinJsonLimits(decoded, policy))
|
||||
if (!isJsonWithinLimits(decoded, policy))
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
try {
|
||||
return ok(parseInvestigationWorkspace(decoded));
|
||||
@@ -241,34 +242,6 @@ const validateNextRevision = (
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
};
|
||||
|
||||
const withinJsonLimits = (
|
||||
root: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
): boolean => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > policy.maxNodes || current.depth > policy.maxDepth)
|
||||
return false;
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > policy.maxStringLength
|
||||
)
|
||||
return false;
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > policy.maxStringLength) return false;
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "ENOENT";
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
candidate === root ||
|
||||
@@ -18,17 +19,15 @@ export const assertRealPathAuthority = async (
|
||||
policy: ProcessExecutionPolicy,
|
||||
): Promise<void> => {
|
||||
const executable = await realpath(scenario.executable);
|
||||
const executableRoots = await Promise.all(
|
||||
policy.executableRoots.map((root) => realpath(root)),
|
||||
const executableRoots = await canonicalizeConfiguredRoots(
|
||||
policy.executableRoots,
|
||||
);
|
||||
if (!executableRoots.some((root) => isWithin(executable, root)))
|
||||
throw new ProcessCaptureError(
|
||||
"resolved executable is outside approved roots",
|
||||
);
|
||||
const workingDirectory = await realpath(scenario.working_directory);
|
||||
const workingRoots = await Promise.all(
|
||||
policy.workingRoots.map((root) => realpath(root)),
|
||||
);
|
||||
const workingRoots = await canonicalizeConfiguredRoots(policy.workingRoots);
|
||||
if (!workingRoots.some((root) => isWithin(workingDirectory, root)))
|
||||
throw new ProcessCaptureError(
|
||||
"resolved working directory is outside approved roots",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { IPty } from "node-pty";
|
||||
@@ -338,14 +338,12 @@ export const captureTerminalFrames = (options: {
|
||||
readonly started: number;
|
||||
readonly temporaryRoot: string;
|
||||
readonly onOutput: () => void;
|
||||
readonly onFirstOutput: () => void;
|
||||
readonly renderer: TerminalRenderer;
|
||||
readonly checkpoints: ProcessCheckpoints;
|
||||
}): (() => boolean) => {
|
||||
let outputBytes = 0;
|
||||
let truncated = false;
|
||||
options.terminal.onData((data) => {
|
||||
options.onFirstOutput();
|
||||
options.onOutput();
|
||||
const bytes = Buffer.byteLength(data);
|
||||
if (
|
||||
@@ -401,6 +399,7 @@ export const prepareProcessCapture = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal: AbortSignal | undefined,
|
||||
host: ProcessPreparationHost = systemProcessPreparationHost,
|
||||
): Promise<{
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
@@ -416,11 +415,29 @@ export const prepareProcessCapture = async (
|
||||
await assertRealPathAuthority(scenario, policy);
|
||||
assertNotCancelled(signal);
|
||||
const before = await snapshotRoots(scenario, signal);
|
||||
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
|
||||
const runId = randomUUID();
|
||||
const home = join(temporaryRoot, "home");
|
||||
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
|
||||
return { temporaryRoot, runId, home, before };
|
||||
const temporaryRoot = await host.createTemporaryRoot();
|
||||
try {
|
||||
const runId = randomUUID();
|
||||
const home = join(temporaryRoot, "home");
|
||||
await host.createHome(home);
|
||||
return { temporaryRoot, runId, home, before };
|
||||
} catch (cause: unknown) {
|
||||
await host.cleanup(temporaryRoot);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Filesystem seam for allocating and cleaning a capture's private home. */
|
||||
export interface ProcessPreparationHost {
|
||||
createTemporaryRoot(): Promise<string>;
|
||||
createHome(path: string): Promise<void>;
|
||||
cleanup(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemProcessPreparationHost: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => mkdtemp(join(tmpdir(), "rea-process-")),
|
||||
createHome: (path) => mkdir(path),
|
||||
cleanup: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
|
||||
const processPolicyMessage = (
|
||||
|
||||
@@ -126,7 +126,7 @@ export class ProcessCheckpoints {
|
||||
effects: classifyFilesystemEffects(previous, after.files),
|
||||
truncated: after.truncated,
|
||||
});
|
||||
return this.#captures;
|
||||
return structuredClone(this.#captures);
|
||||
}
|
||||
|
||||
/** Cancel scheduled captures and await any snapshot already in progress. */
|
||||
|
||||
@@ -112,7 +112,12 @@ export const compareProcessEvidenceFiles = async (
|
||||
};
|
||||
|
||||
const parseCaptureEvidence = (input: unknown) => {
|
||||
const evidence = parseEvidence(input);
|
||||
let evidence;
|
||||
try {
|
||||
evidence = parseEvidence(input);
|
||||
} catch {
|
||||
throw invalidCaptureEvidence();
|
||||
}
|
||||
if (
|
||||
evidence.operation !== "capture_process_scenario" ||
|
||||
evidence.predicate_type !== "rea.process-capture/v4" ||
|
||||
@@ -129,12 +134,22 @@ const parseCaptureEvidence = (input: unknown) => {
|
||||
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
id: evidence.evidence_id,
|
||||
capture: parseProcessCapture(evidence.normalized_result),
|
||||
};
|
||||
try {
|
||||
return {
|
||||
id: evidence.evidence_id,
|
||||
capture: parseProcessCapture(evidence.normalized_result),
|
||||
};
|
||||
} catch {
|
||||
throw invalidCaptureEvidence();
|
||||
}
|
||||
};
|
||||
|
||||
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 {
|
||||
|
||||
@@ -130,20 +130,6 @@ const scheduleScenarioEvents = (options: ScenarioEventOptions): void => {
|
||||
}
|
||||
};
|
||||
|
||||
const startScenarioEvents = (options: ScenarioEventOptions): (() => void) => {
|
||||
let eventsStarted = false;
|
||||
return () => {
|
||||
if (eventsStarted) return;
|
||||
eventsStarted = true;
|
||||
scheduleScenarioEvents(options);
|
||||
};
|
||||
};
|
||||
|
||||
const eventsRequireReadiness = (scenario: ProcessScenario): boolean =>
|
||||
scenario.events.some(
|
||||
(event) => event.type === "input" || event.type === "resize",
|
||||
);
|
||||
|
||||
interface StartedCaptureRuntime {
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly renderer: TerminalRenderer;
|
||||
@@ -243,22 +229,20 @@ const startCaptureRuntime = async (options: {
|
||||
rows: scenario.terminal.rows,
|
||||
name: "xterm-256color",
|
||||
});
|
||||
const startEvents = startScenarioEvents({
|
||||
...options,
|
||||
getTerminal: () => terminal,
|
||||
renderer,
|
||||
started,
|
||||
});
|
||||
if (!eventsRequireReadiness(scenario)) startEvents();
|
||||
const framesTruncated = captureTerminalFrames({
|
||||
...options,
|
||||
terminal,
|
||||
started,
|
||||
onOutput: () => (lastOutput = Date.now()),
|
||||
onFirstOutput: startEvents,
|
||||
renderer,
|
||||
checkpoints,
|
||||
});
|
||||
scheduleScenarioEvents({
|
||||
...options,
|
||||
getTerminal: () => terminal,
|
||||
renderer,
|
||||
started,
|
||||
});
|
||||
const stopSampler = startProcessSampler(
|
||||
terminal.pid,
|
||||
started,
|
||||
|
||||
@@ -31,7 +31,7 @@ export const normalizeProcessText = (
|
||||
);
|
||||
}
|
||||
if (scenario.normalization.pids)
|
||||
normalized = normalized.replaceAll(String(pid), "<pid>");
|
||||
normalized = normalizePidTokens(normalized, [pid]);
|
||||
if (scenario.normalization.ports)
|
||||
normalized = normalized.replaceAll(/(?<=[:=])\d{2,5}\b/g, "<port>");
|
||||
for (const pattern of scenario.normalization.patterns)
|
||||
@@ -57,6 +57,17 @@ export const normalizeProcessSamples = (
|
||||
for (const identifier of identifiers)
|
||||
if (identifier > 0 && !mapping.has(identifier))
|
||||
mapping.set(identifier, mapping.size + 1);
|
||||
const normalizeCommand = (command: string): string => {
|
||||
const normalized = normalizeProcessText(
|
||||
command,
|
||||
scenario,
|
||||
"<no-temporary-root>",
|
||||
rootPid,
|
||||
);
|
||||
return scenario.normalization.pids
|
||||
? normalizePidTokens(normalized, identifiers)
|
||||
: normalized;
|
||||
};
|
||||
return samples.map((sample) => ({
|
||||
at_ms:
|
||||
Math.floor(sample.at_ms / scenario.normalization.time_bucket_ms) *
|
||||
@@ -69,15 +80,25 @@ export const normalizeProcessSamples = (
|
||||
: (mapping.get(sample.process_group_id) ?? 0),
|
||||
session_id:
|
||||
sample.session_id === null ? null : (mapping.get(sample.session_id) ?? 0),
|
||||
command: normalizeProcessText(
|
||||
sample.command,
|
||||
scenario,
|
||||
"<no-temporary-root>",
|
||||
rootPid,
|
||||
),
|
||||
command: normalizeCommand(sample.command),
|
||||
}));
|
||||
};
|
||||
|
||||
const normalizePidTokens = (
|
||||
value: string,
|
||||
identifiers: readonly number[],
|
||||
): string => {
|
||||
const tokens = [...new Set(identifiers)]
|
||||
.filter((identifier) => Number.isSafeInteger(identifier) && identifier > 0)
|
||||
.sort((left, right) => right - left)
|
||||
.map(String);
|
||||
if (tokens.length === 0) return value;
|
||||
return value.replace(
|
||||
new RegExp(`(?<!\\d)(?:${tokens.join("|")})(?!\\d)`, "gu"),
|
||||
"<pid>",
|
||||
);
|
||||
};
|
||||
|
||||
export const redactProtocolEvents = (
|
||||
events: readonly ProcessCapture["protocol_events"][number][],
|
||||
scenario: ProcessScenario,
|
||||
|
||||
@@ -40,11 +40,14 @@ export type ProcessGroupObservation =
|
||||
| { readonly state: "alive" }
|
||||
| { readonly state: "unverifiable"; readonly reason: string };
|
||||
|
||||
const parseEnvironment = (value: string): Readonly<Record<string, string>> =>
|
||||
/** Parse the NUL-delimited Linux process environment without nameless keys. */
|
||||
export const parseProcessEnvironment = (
|
||||
value: string,
|
||||
): Readonly<Record<string, string>> =>
|
||||
Object.fromEntries(
|
||||
value
|
||||
.split("\0")
|
||||
.filter((entry) => entry.includes("="))
|
||||
.filter((entry) => entry.indexOf("=") > 0)
|
||||
.map((entry) => {
|
||||
const separator = entry.indexOf("=");
|
||||
return [entry.slice(0, separator), entry.slice(separator + 1)];
|
||||
@@ -72,7 +75,9 @@ const systemHost: ProcessOwnershipHost = {
|
||||
},
|
||||
async environment(pid) {
|
||||
if (process.platform === "linux") {
|
||||
return parseEnvironment(await readFile(`/proc/${pid}/environ`, "utf8"));
|
||||
return parseProcessEnvironment(
|
||||
await readFile(`/proc/${pid}/environ`, "utf8"),
|
||||
);
|
||||
}
|
||||
const { stdout } = await execFileAsync("ps", ["eww", "-p", String(pid)]);
|
||||
const environment: Record<string, string> = {};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import type { ProcessSample } from "../domain/processCapture.js";
|
||||
|
||||
@@ -104,25 +104,79 @@ const readProcessCommand = async (
|
||||
}
|
||||
};
|
||||
|
||||
const readLinuxChildren = async (
|
||||
/** Procfs reads used to enumerate children created by every process thread. */
|
||||
export interface LinuxChildrenHost {
|
||||
taskIds(
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<readonly number[] | undefined>;
|
||||
children(
|
||||
pid: number,
|
||||
taskId: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<string | undefined>;
|
||||
}
|
||||
|
||||
const systemLinuxChildrenHost: LinuxChildrenHost = {
|
||||
async taskIds(pid, signal) {
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
const entries = await readdir(`/proc/${String(pid)}/task`);
|
||||
signal.throwIfAborted();
|
||||
return entries
|
||||
.filter((entry) => /^\d+$/.test(entry))
|
||||
.map(Number)
|
||||
.filter((taskId) => Number.isSafeInteger(taskId) && taskId > 0)
|
||||
.sort((left, right) => left - right);
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
},
|
||||
async children(pid, taskId, signal) {
|
||||
try {
|
||||
return await readFile(
|
||||
`/proc/${String(pid)}/task/${String(taskId)}/children`,
|
||||
{ encoding: "utf8", signal },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/** Read the deduplicated children created by every thread in a Linux process. */
|
||||
export const readLinuxChildren = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
host: LinuxChildrenHost = systemLinuxChildrenHost,
|
||||
): Promise<readonly number[] | undefined> => {
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(`/proc/${String(pid)}/task/${String(pid)}/children`, {
|
||||
encoding: "utf8",
|
||||
signal,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
const taskIds = await host.taskIds(pid, signal);
|
||||
if (taskIds === undefined) return undefined;
|
||||
const children = new Set<number>();
|
||||
let successfulReads = 0;
|
||||
for (
|
||||
let offset = 0;
|
||||
offset < taskIds.length;
|
||||
offset += PROC_READ_CONCURRENCY
|
||||
) {
|
||||
const texts = await Promise.all(
|
||||
taskIds
|
||||
.slice(offset, offset + PROC_READ_CONCURRENCY)
|
||||
.map((taskId) => host.children(pid, taskId, signal)),
|
||||
);
|
||||
for (const text of texts) {
|
||||
if (text === undefined) continue;
|
||||
successfulReads += 1;
|
||||
for (const value of text.trim().split(/\s+/)) {
|
||||
if (!/^\d+$/.test(value)) continue;
|
||||
const child = Number(value);
|
||||
if (Number.isSafeInteger(child) && child > 0) children.add(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
return text
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((value) => /^\d+$/.test(value))
|
||||
.map(Number)
|
||||
.filter((child) => Number.isSafeInteger(child) && child > 0);
|
||||
return successfulReads === 0
|
||||
? undefined
|
||||
: [...children].sort((left, right) => left - right);
|
||||
};
|
||||
|
||||
const inspectProcess = async (
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, realpath, stat } from "node:fs/promises";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
stat,
|
||||
unlink,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { z } from "zod";
|
||||
@@ -49,7 +59,12 @@ export class ProjectPermissionStoreError extends Error {
|
||||
readonly _tag = "ProjectPermissionStoreError" as const;
|
||||
|
||||
constructor(
|
||||
readonly reason: "project_not_found" | "not_owner_only" | "invalid" | "io",
|
||||
readonly reason:
|
||||
| "project_not_found"
|
||||
| "not_owner_only"
|
||||
| "invalid"
|
||||
| "locked"
|
||||
| "io",
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Project permission store failed: ${reason}`, options);
|
||||
@@ -89,9 +104,14 @@ export const readProjectPermissionStore = async (
|
||||
const metadata = await stat(path);
|
||||
if ((metadata.mode & 0o077) !== 0)
|
||||
return err(new ProjectPermissionStoreError("not_owner_only"));
|
||||
const parsed = storeSchema.safeParse(
|
||||
JSON.parse(await readFile(path, "utf8")),
|
||||
);
|
||||
const encoded = await readFile(path, "utf8");
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded);
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("invalid", { cause }));
|
||||
}
|
||||
const parsed = storeSchema.safeParse(decoded);
|
||||
if (
|
||||
!parsed.success ||
|
||||
parsed.data.project_id !== project.value.id ||
|
||||
@@ -143,5 +163,114 @@ export const writeProjectPermissionStore = async (
|
||||
}
|
||||
};
|
||||
|
||||
const isNotFound = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
||||
/** Revoke one grant while serializing the complete read-modify-write cycle. */
|
||||
export const revokeProjectPermissionGrant = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
grantId: string,
|
||||
): Promise<Result<boolean, ProjectPermissionStoreError>> => {
|
||||
let lock: PermissionStoreLock | undefined;
|
||||
try {
|
||||
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const acquired = await acquirePermissionStoreLock(path);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
const current = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!current.ok) return current;
|
||||
const grants = current.value?.grants ?? [];
|
||||
const retained = grants.filter(({ grant_id }) => grant_id !== grantId);
|
||||
if (retained.length === grants.length) return ok(false);
|
||||
const written = await writeProjectPermissionStore(
|
||||
path,
|
||||
projectRoot,
|
||||
retained,
|
||||
);
|
||||
return written.ok ? ok(true) : written;
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await releasePermissionStoreLock(lock);
|
||||
}
|
||||
};
|
||||
|
||||
interface PermissionStoreLock {
|
||||
readonly path: string;
|
||||
readonly handle: FileHandle;
|
||||
}
|
||||
|
||||
const acquirePermissionStoreLock = async (
|
||||
destination: string,
|
||||
): Promise<Result<PermissionStoreLock, ProjectPermissionStoreError>> => {
|
||||
const path = `${destination}.lock`;
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
try {
|
||||
return ok(await createPermissionStoreLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (!isAlreadyExists(cause))
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
if (await removeStalePermissionStoreLock(path)) continue;
|
||||
if (attempt === 99)
|
||||
return err(new ProjectPermissionStoreError("locked", { cause }));
|
||||
await delay(10);
|
||||
}
|
||||
}
|
||||
return err(new ProjectPermissionStoreError("locked"));
|
||||
};
|
||||
|
||||
const createPermissionStoreLock = async (
|
||||
path: string,
|
||||
): Promise<PermissionStoreLock> => {
|
||||
const handle = await open(path, "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
return { path, handle };
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
await unlink(path).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const removeStalePermissionStoreLock = async (
|
||||
path: string,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const metadata = await lstat(path);
|
||||
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 32)
|
||||
return false;
|
||||
const encoded = (await readFile(path, "utf8")).trim();
|
||||
if (!/^[1-9][0-9]{0,9}$/u.test(encoded)) return false;
|
||||
if (processIsAlive(Number(encoded))) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const releasePermissionStoreLock = async (
|
||||
lock: PermissionStoreLock,
|
||||
): Promise<void> => {
|
||||
await lock.handle.close().catch(() => undefined);
|
||||
await unlink(lock.path).catch(() => undefined);
|
||||
};
|
||||
|
||||
const isNotFound = (cause: unknown): boolean => errorCode(cause) === "ENOENT";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "EEXIST";
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type ReferenceSourceImportError,
|
||||
type ReferenceSourceImportOptions,
|
||||
} from "./ReferenceSourceImportTypes.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
/** Validated, authorized inputs ready for filesystem traversal. */
|
||||
export interface PreparedReferenceSourceImport {
|
||||
@@ -66,8 +67,10 @@ const authorizeRoot = async (
|
||||
failure("invalid-root", "Reference source root is not a directory"),
|
||||
);
|
||||
const canonicalRoot = await realpath(resolve(requestedRoot));
|
||||
for (const approvedRoot of approvedRoots) {
|
||||
const canonicalApproved = await realpath(resolve(approvedRoot));
|
||||
const canonicalApprovedRoots = await canonicalizeConfiguredRoots(
|
||||
approvedRoots.map((approvedRoot) => resolve(approvedRoot)),
|
||||
);
|
||||
for (const canonicalApproved of canonicalApprovedRoots) {
|
||||
if (withinRoot(canonicalApproved, canonicalRoot))
|
||||
return ok(canonicalRoot);
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ export class TerminalRenderer {
|
||||
/** Await all queued parsing and return immutable rendered observations. */
|
||||
async frames(): Promise<readonly RenderedTerminalFrame[]> {
|
||||
await this.#pending;
|
||||
return this.#frames;
|
||||
return structuredClone(this.#frames);
|
||||
}
|
||||
|
||||
/** Whether a rendered observation exceeded its independent capture budget. */
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
import {
|
||||
createResidualUnknown,
|
||||
updateResidualUnknown,
|
||||
residualUnknownSchema,
|
||||
type RecordUnknownInput,
|
||||
type ResidualUnknown,
|
||||
type UnknownStatus,
|
||||
type UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import { UnknownRegistryError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
export interface UnknownRegistryLimits {
|
||||
readonly maxRecords: number;
|
||||
readonly maxRelationships: number;
|
||||
}
|
||||
|
||||
type UnknownRegistryMutation = Result<ResidualUnknown, UnknownRegistryError>;
|
||||
|
||||
type UnknownRegistryQuery = Result<
|
||||
readonly ResidualUnknown[],
|
||||
UnknownRegistryError
|
||||
>;
|
||||
|
||||
type UnknownRegistryVerify = Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Persistent, bounded registry of residual unknowns linked to evidence.
|
||||
*
|
||||
* Each unknown carries a stable ID derived from its question and scope,
|
||||
* an immutable revision graph, and evidence-qualified resolution state.
|
||||
*/
|
||||
export class UnknownRegistry {
|
||||
readonly #revisions = new Map<string, ResidualUnknown>();
|
||||
readonly #heads = new Map<string, ResidualUnknown>();
|
||||
|
||||
constructor(private readonly limits: UnknownRegistryLimits) {
|
||||
if (!Number.isSafeInteger(limits.maxRecords) || limits.maxRecords < 1)
|
||||
throw new RangeError("maxRecords must be a positive safe integer");
|
||||
if (
|
||||
!Number.isSafeInteger(limits.maxRelationships) ||
|
||||
limits.maxRelationships < 0
|
||||
)
|
||||
throw new RangeError(
|
||||
"maxRelationships must be a non-negative safe integer",
|
||||
);
|
||||
}
|
||||
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
mutationEvidenceId: string,
|
||||
): UnknownRegistryMutation {
|
||||
let unknown: ResidualUnknown;
|
||||
try {
|
||||
unknown = createResidualUnknown(input, mutationEvidenceId, null);
|
||||
} catch (cause: unknown) {
|
||||
return err(new UnknownRegistryError("invalid-transition", { cause }));
|
||||
}
|
||||
if (this.#heads.has(unknown.unknown_id))
|
||||
return err(new UnknownRegistryError("already-exists"));
|
||||
return this.#append(unknown);
|
||||
}
|
||||
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
mutationEvidenceId: string,
|
||||
): UnknownRegistryMutation {
|
||||
const current = this.#heads.get(input.unknown_id);
|
||||
if (current === undefined)
|
||||
return err(new UnknownRegistryError("not-found"));
|
||||
if (current.revision !== input.expected_revision)
|
||||
return err(new UnknownRegistryError("revision-conflict"));
|
||||
let updated: ResidualUnknown;
|
||||
try {
|
||||
updated = updateResidualUnknown(current, input, mutationEvidenceId);
|
||||
} catch (cause: unknown) {
|
||||
return err(new UnknownRegistryError("invalid-transition", { cause }));
|
||||
}
|
||||
return this.#append(updated);
|
||||
}
|
||||
|
||||
listUnknowns(
|
||||
filters: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
} = {},
|
||||
): UnknownRegistryQuery {
|
||||
return ok(
|
||||
[...this.#heads.values()]
|
||||
.filter(
|
||||
(unknown) =>
|
||||
(filters.status === undefined ||
|
||||
unknown.status === filters.status) &&
|
||||
(filters.severity === undefined ||
|
||||
unknown.severity === filters.severity) &&
|
||||
(filters.domain === undefined || unknown.domain === filters.domain),
|
||||
)
|
||||
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id)),
|
||||
);
|
||||
}
|
||||
|
||||
verifyUnknownResolution(unknownId: string): UnknownRegistryVerify {
|
||||
const unknown = this.#heads.get(unknownId);
|
||||
if (unknown === undefined)
|
||||
return err(new UnknownRegistryError("not-found"));
|
||||
return ok({
|
||||
valid: unknown.status === "resolved",
|
||||
truthVerified: unknown.resolution?.disposition === "verified",
|
||||
unknown,
|
||||
});
|
||||
}
|
||||
|
||||
get(unknownId: string): ResidualUnknown | undefined {
|
||||
const unknown = this.#heads.get(unknownId);
|
||||
return unknown === undefined ? undefined : structuredClone(unknown);
|
||||
}
|
||||
|
||||
has(unknownId: string): boolean {
|
||||
return this.#heads.has(unknownId);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.#revisions.clear();
|
||||
this.#heads.clear();
|
||||
}
|
||||
|
||||
#append(unknown: ResidualUnknown): UnknownRegistryMutation {
|
||||
const pending = this.#revisions.size + 1;
|
||||
if (pending > this.limits.maxRecords)
|
||||
return err(new UnknownRegistryError("limit"));
|
||||
if (unknown.relationships.length > this.limits.maxRelationships)
|
||||
return err(new UnknownRegistryError("limit"));
|
||||
try {
|
||||
residualUnknownSchema.parse(unknown);
|
||||
} catch (cause: unknown) {
|
||||
return err(new UnknownRegistryError("integrity", { cause }));
|
||||
}
|
||||
this.#revisions.set(
|
||||
`${unknown.unknown_id}:${String(unknown.revision)}`,
|
||||
unknown,
|
||||
);
|
||||
this.#heads.set(unknown.unknown_id, unknown);
|
||||
return ok(unknown);
|
||||
}
|
||||
}
|
||||
@@ -94,7 +94,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
provenance(): readonly ArtifactCommand[] {
|
||||
return this.#command === undefined ? [] : [this.#command];
|
||||
return this.#command === undefined ? [] : [structuredClone(this.#command)];
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
|
||||
@@ -103,7 +103,7 @@ export class NativeDmgArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
provenance(): readonly ArtifactCommand[] {
|
||||
return this.#provenance;
|
||||
return structuredClone(this.#provenance);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
|
||||
@@ -107,7 +107,7 @@ export class SafeOutputTree {
|
||||
}
|
||||
|
||||
get cleanup(): SafeOutputCleanup {
|
||||
return this.#cleanup;
|
||||
return structuredClone(this.#cleanup);
|
||||
}
|
||||
|
||||
/** Stream one selected regular file with exact byte and digest verification. */
|
||||
@@ -205,7 +205,7 @@ export class SafeOutputTree {
|
||||
|
||||
/** Remove only this operation's unsealed tree and verify absence. */
|
||||
async rollback(): Promise<SafeOutputCleanup> {
|
||||
if (this.#published) return this.#cleanup;
|
||||
if (this.#published) return structuredClone(this.#cleanup);
|
||||
await rm(this.#stagingRoot, { recursive: true, force: true });
|
||||
const absent = await isAbsent(this.#stagingRoot);
|
||||
this.#cleanup = {
|
||||
@@ -218,7 +218,7 @@ export class SafeOutputTree {
|
||||
"integrity",
|
||||
"Extraction output cleanup could not be verified",
|
||||
);
|
||||
return this.#cleanup;
|
||||
return structuredClone(this.#cleanup);
|
||||
}
|
||||
|
||||
async #prepareParent(relativePath: string): Promise<string> {
|
||||
|
||||
+1
-8
@@ -19,8 +19,6 @@ import { importReferenceSource } from "./application/ReferenceSourceImport.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
import { registerProcessCommands } from "./cliProcessCommands.js";
|
||||
import { registerInvestigationCommands } from "./cliInvestigationCommands.js";
|
||||
import { registerUnknownCommands } from "./cliUnknownCommands.js";
|
||||
import { registerBrowserCommands } from "./cliBrowserCommands.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
@@ -29,7 +27,7 @@ import {
|
||||
import { projectReferenceSourceImportError } from "./application/ReferenceSourceImportTypes.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { registerPolicyCommands } from "./cliPolicyCommands.js";
|
||||
import { UnknownRegistry } from "./application/UnknownRegistry.js";
|
||||
import { registerBrowserCommands } from "./cliBrowserCommands.js";
|
||||
|
||||
/**
|
||||
* Build the one-shot Incur CLI without starting Hopper at import time.
|
||||
@@ -73,11 +71,6 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
registerArtifactCommands(cli, logger);
|
||||
registerInvestigationCommands(cli, logger);
|
||||
registerEvidenceCommands(cli, logger);
|
||||
registerUnknownCommands(
|
||||
cli,
|
||||
logger,
|
||||
new UnknownRegistry({ maxRecords: 1_000, maxRelationships: 100 }),
|
||||
);
|
||||
registerReferenceSourceCommand(cli, logger);
|
||||
registerProcessCommands(cli, logger);
|
||||
registerPolicyCommands(cli, logger);
|
||||
|
||||
@@ -3,14 +3,13 @@ import { Cli, z } from "incur";
|
||||
import { runCrossVersionInvestigation } from "./application/CrossVersionInvestigation.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
projectAnalysisError,
|
||||
type AnalysisError,
|
||||
} from "./domain/errors.js";
|
||||
import { projectAnalysisError, type AnalysisError } from "./domain/errors.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import {
|
||||
authorizeFileReadWithDeferredWrite,
|
||||
authorizeRootPermission,
|
||||
} from "./application/DeferredFileAuthorization.js";
|
||||
|
||||
const investigationOptionsSchema = z.object({
|
||||
yes: z
|
||||
@@ -90,44 +89,23 @@ const runInvestigation = async (
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) return cliError(authority.error);
|
||||
for (const scope of [
|
||||
const workspaceAuthorization = await authorizeFileReadWithDeferredWrite(
|
||||
authority.value,
|
||||
{
|
||||
capability: "investigation_workspace_read" as const,
|
||||
roots: [args.workspacePath],
|
||||
access: "write" as const,
|
||||
path: args.workspacePath,
|
||||
readCapability: "investigation_workspace_read",
|
||||
writeCapability: "investigation_workspace_write",
|
||||
operation: "investigate_versions",
|
||||
},
|
||||
{
|
||||
capability: "investigation_workspace_write" as const,
|
||||
roots: [args.workspacePath],
|
||||
access: "write" as const,
|
||||
},
|
||||
{
|
||||
capability: "investigation_input" as const,
|
||||
roots: [args.leftPath, args.rightPath],
|
||||
access: "read" as const,
|
||||
},
|
||||
]) {
|
||||
const authorized = await authority.value.authorize(
|
||||
{
|
||||
capability: scope.capability,
|
||||
roots: scope.roots,
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `investigate_versions:${scope.capability}:${scope.roots.join(":")}`,
|
||||
},
|
||||
scope.access,
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return cliError(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
}
|
||||
);
|
||||
if (!workspaceAuthorization.ok) return cliError(workspaceAuthorization.error);
|
||||
const inputAuthorization = await authorizeRootPermission(authority.value, {
|
||||
capability: "investigation_input",
|
||||
roots: [args.leftPath, args.rightPath],
|
||||
access: "read",
|
||||
operation: "investigate_versions",
|
||||
});
|
||||
if (!inputAuthorization.ok) return cliError(inputAuthorization.error);
|
||||
const investigated = await runCrossVersionInvestigation(
|
||||
{
|
||||
approved: true,
|
||||
@@ -156,6 +134,7 @@ const runInvestigation = async (
|
||||
{
|
||||
inputRoots: config.value.investigationInputRoots,
|
||||
integrityContinueEnabled: config.value.artifactIntegrityContinueEnabled,
|
||||
authorizeWorkspaceWrite: workspaceAuthorization.value.authorizeWrite,
|
||||
},
|
||||
);
|
||||
return investigated.ok
|
||||
|
||||
+16
-14
@@ -3,7 +3,7 @@ import { Cli, z } from "incur";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import {
|
||||
readProjectPermissionStore,
|
||||
writeProjectPermissionStore,
|
||||
revokeProjectPermissionGrant,
|
||||
} from "./application/ProjectPermissionStore.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { parseConfig, type AppConfig } from "./config.js";
|
||||
@@ -68,24 +68,26 @@ export const registerPolicyCommands = (
|
||||
if (args.action === "revoke") {
|
||||
if (args.value === undefined)
|
||||
return { error: "Grant ID is required for policy revoke" };
|
||||
const result = await readProjectGrants(config.value);
|
||||
if (!result.ok) return result.error;
|
||||
const retained = result.grants.filter(
|
||||
({ grant_id }) => grant_id !== args.value,
|
||||
const { permissionProjectRoot, permissionProjectStore } =
|
||||
config.value;
|
||||
if (
|
||||
permissionProjectRoot === undefined ||
|
||||
permissionProjectStore === undefined
|
||||
)
|
||||
return { error: "Project policy is not configured" };
|
||||
const revoked = await revokeProjectPermissionGrant(
|
||||
permissionProjectStore,
|
||||
permissionProjectRoot,
|
||||
args.value,
|
||||
);
|
||||
if (retained.length === result.grants.length)
|
||||
return { error: "Grant was not found", grant_id: args.value };
|
||||
const written = await writeProjectPermissionStore(
|
||||
result.path,
|
||||
result.root,
|
||||
retained,
|
||||
);
|
||||
return written.ok
|
||||
return revoked.ok && revoked.value
|
||||
? {
|
||||
revoked: args.value,
|
||||
reload: "Send SIGHUP to the REA MCP process",
|
||||
}
|
||||
: { error: written.error.message };
|
||||
: revoked.ok
|
||||
? { error: "Grant was not found", grant_id: args.value }
|
||||
: { error: revoked.error.message };
|
||||
}
|
||||
const capability = capabilitySchema.safeParse(args.value);
|
||||
if (!capability.success)
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
import { Cli, z } from "incur";
|
||||
|
||||
import type { UnknownRegistry } from "./application/UnknownRegistry.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
UpdateUnknownInput,
|
||||
} from "./domain/residualUnknown.js";
|
||||
|
||||
/** Register residual-unknown registry CLI commands. */
|
||||
export const registerUnknownCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
_logger: Logger,
|
||||
registry: UnknownRegistry,
|
||||
): void => {
|
||||
cli.command("unknowns", {
|
||||
description: "List recorded residual unknowns with optional filters",
|
||||
options: z.object({
|
||||
status: z
|
||||
.enum(["open", "investigating", "blocked", "contradicted", "resolved"])
|
||||
.optional()
|
||||
.describe("Filter by status"),
|
||||
severity: z
|
||||
.enum(["low", "medium", "high", "critical"])
|
||||
.optional()
|
||||
.describe("Filter by severity"),
|
||||
domain: z.string().optional().describe("Filter by domain"),
|
||||
}),
|
||||
run: ({ options }): ReturnType<typeof registry.listUnknowns> => {
|
||||
const filters: {
|
||||
status?:
|
||||
| "open"
|
||||
| "investigating"
|
||||
| "blocked"
|
||||
| "contradicted"
|
||||
| "resolved";
|
||||
severity?: "low" | "medium" | "high" | "critical";
|
||||
domain?: string;
|
||||
} = {};
|
||||
if (options.status !== undefined) filters.status = options.status;
|
||||
if (options.severity !== undefined) filters.severity = options.severity;
|
||||
if (options.domain !== undefined) filters.domain = options.domain;
|
||||
return registry.listUnknowns(filters);
|
||||
},
|
||||
});
|
||||
|
||||
cli.command("unknown-record", {
|
||||
description: "Record one approved residual unknown question",
|
||||
options: z.object({
|
||||
question: z.string().min(1).max(1_000).describe("The bounded question"),
|
||||
severity: z
|
||||
.enum(["low", "medium", "high", "critical"])
|
||||
.describe("Severity of the unknown"),
|
||||
domain: z.string().min(1).max(100).describe("Domain of the unknown"),
|
||||
authority: z
|
||||
.enum([
|
||||
"shipped-artifact",
|
||||
"controlled-replay",
|
||||
"historical-reference",
|
||||
"external-service",
|
||||
"analyst-inference",
|
||||
])
|
||||
.describe("Required authority to resolve"),
|
||||
confidence: z
|
||||
.enum(["observed", "derived", "inferred"])
|
||||
.describe("Required confidence level"),
|
||||
evidence: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Mutation evidence ID for this record operation"),
|
||||
}),
|
||||
run: ({ options }) =>
|
||||
registry.recordUnknown(
|
||||
{
|
||||
question: options.question,
|
||||
severity: options.severity,
|
||||
domain: options.domain,
|
||||
required_authority: options.authority,
|
||||
required_confidence: options.confidence,
|
||||
required_environment: null,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
approved: true,
|
||||
} as RecordUnknownInput,
|
||||
options.evidence,
|
||||
),
|
||||
});
|
||||
|
||||
cli.command("unknown-update", {
|
||||
description: "Update one residual unknown with new evidence or status",
|
||||
options: z.object({
|
||||
id: z.string().describe("Unknown ID (unk_…)"),
|
||||
revision: z.number().int().min(1).describe("Expected current revision"),
|
||||
status: z
|
||||
.enum(["open", "investigating", "blocked", "contradicted", "resolved"])
|
||||
.describe("New status"),
|
||||
severity: z
|
||||
.enum(["low", "medium", "high", "critical"])
|
||||
.describe("New severity"),
|
||||
evidence: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Mutation evidence ID for this update operation"),
|
||||
}),
|
||||
run: ({ options }) =>
|
||||
registry.updateUnknown(
|
||||
{
|
||||
unknown_id: options.id,
|
||||
expected_revision: options.revision,
|
||||
approved: true,
|
||||
status: options.status,
|
||||
severity: options.severity,
|
||||
required_authority: null,
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
resolution: null,
|
||||
} as unknown as UpdateUnknownInput,
|
||||
options.evidence,
|
||||
),
|
||||
});
|
||||
|
||||
cli.command("unknown-verify", {
|
||||
description: "Verify the resolution state of one residual unknown",
|
||||
options: z.object({
|
||||
id: z.string().describe("Unknown ID (unk_…)"),
|
||||
}),
|
||||
run: ({ options }) => registry.verifyUnknownResolution(options.id),
|
||||
});
|
||||
};
|
||||
@@ -5,6 +5,8 @@ import { evidenceSchema, parseEvidence, type Evidence } from "./evidence.js";
|
||||
import { functionComparisonResultSchema } from "./functionComparison.js";
|
||||
import {
|
||||
comparisonStatusSchema,
|
||||
deriveProcessComparisonStatus,
|
||||
PROCESS_COMPARISON_DIMENSIONS,
|
||||
processCaptureComparisonSchema,
|
||||
} from "./processCapture.js";
|
||||
import {
|
||||
@@ -205,20 +207,9 @@ const parseResult = (evidence: Evidence): void => {
|
||||
const result = processCaptureComparisonSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
const dimensions = [
|
||||
result.terminal,
|
||||
result.exit,
|
||||
result.filesystem,
|
||||
result.protocol,
|
||||
result.process,
|
||||
];
|
||||
const expected = dimensions.includes("truncated")
|
||||
? "truncated"
|
||||
: dimensions.some(isChange)
|
||||
? "changed"
|
||||
: dimensions.includes("unknown")
|
||||
? "unknown"
|
||||
: "unchanged";
|
||||
const expected = deriveProcessComparisonStatus(
|
||||
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => result[dimension]),
|
||||
);
|
||||
if (result.status !== expected)
|
||||
throw new TypeError(
|
||||
"Process comparison status contradicts its dimensions",
|
||||
@@ -273,10 +264,12 @@ const processFindings = (evidence: Evidence): Finding[] => {
|
||||
);
|
||||
const dimensions = [
|
||||
["terminal", result.terminal, "runtime"],
|
||||
["interaction", result.interaction, "runtime"],
|
||||
["exit", result.exit, "runtime"],
|
||||
["filesystem", result.filesystem, "resource"],
|
||||
["protocol", result.protocol, "protocol"],
|
||||
["process", result.process, "runtime"],
|
||||
["shim", result.shim, "protocol"],
|
||||
] as const;
|
||||
return dimensions.flatMap(([dimension, status, scope]) =>
|
||||
status === "unchanged"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Structural limits applied while traversing an unknown JSON value. */
|
||||
export interface JsonLimits {
|
||||
readonly maxDepth: number;
|
||||
readonly maxStringLength: number;
|
||||
readonly maxNodes: number;
|
||||
}
|
||||
|
||||
/** Return whether every node, key, and string fits within the supplied limits. */
|
||||
export const isJsonWithinLimits = (
|
||||
root: unknown,
|
||||
limits: JsonLimits,
|
||||
): boolean => {
|
||||
const pending: Array<{ readonly value: unknown; readonly depth: number }> = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
let nodes = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodes += 1;
|
||||
if (nodes > limits.maxNodes || current.depth > limits.maxDepth)
|
||||
return false;
|
||||
if (
|
||||
typeof current.value === "string" &&
|
||||
current.value.length > limits.maxStringLength
|
||||
)
|
||||
return false;
|
||||
if (typeof current.value !== "object" || current.value === null) continue;
|
||||
for (const [key, value] of Object.entries(current.value)) {
|
||||
if (key.length > limits.maxStringLength) return false;
|
||||
pending.push({ value, depth: current.depth + 1 });
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
@@ -165,10 +165,7 @@ export const evaluatePermission = (
|
||||
reason:
|
||||
coveringGrant !== undefined && isExpired(coveringGrant, now)
|
||||
? "grant_expired"
|
||||
: candidates.length === 0 &&
|
||||
policy.grants.some(
|
||||
(grant) => grant.capability === normalized.capability,
|
||||
)
|
||||
: coveringGrant !== undefined
|
||||
? "grant_revoked_or_consumed"
|
||||
: "grant_required",
|
||||
missing: missingFromScopes(normalized, candidates),
|
||||
|
||||
@@ -156,10 +156,12 @@ export interface ProcessCapture {
|
||||
readonly residual_unknowns: readonly {
|
||||
readonly scope:
|
||||
| "terminal"
|
||||
| "interaction"
|
||||
| "exit"
|
||||
| "process"
|
||||
| "filesystem"
|
||||
| "protocol"
|
||||
| "shim"
|
||||
| "cleanup"
|
||||
| "network";
|
||||
readonly reason: string;
|
||||
@@ -309,10 +311,12 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
|
||||
z.object({
|
||||
scope: z.enum([
|
||||
"terminal",
|
||||
"interaction",
|
||||
"exit",
|
||||
"process",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"shim",
|
||||
"cleanup",
|
||||
"network",
|
||||
]),
|
||||
@@ -349,5 +353,7 @@ export const parseProcessCapture = (input: unknown): ProcessCapture => {
|
||||
export {
|
||||
compareProcessCaptures,
|
||||
comparisonStatusSchema,
|
||||
deriveProcessComparisonStatus,
|
||||
PROCESS_COMPARISON_DIMENSIONS,
|
||||
processCaptureComparisonSchema,
|
||||
} from "./processComparison.js";
|
||||
|
||||
@@ -16,6 +16,31 @@ export const comparisonStatusSchema = z.enum([
|
||||
]);
|
||||
type ComparisonStatus = z.infer<typeof comparisonStatusSchema>;
|
||||
|
||||
/** Canonical ordered dimensions that contribute to an overall process status. */
|
||||
export const PROCESS_COMPARISON_DIMENSIONS = [
|
||||
"terminal",
|
||||
"interaction",
|
||||
"exit",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"process",
|
||||
"shim",
|
||||
] as const;
|
||||
|
||||
/** Derive the overall comparison status from every process dimension. */
|
||||
export const deriveProcessComparisonStatus = (
|
||||
dimensions: readonly ComparisonStatus[],
|
||||
): ComparisonStatus => {
|
||||
if (dimensions.includes("truncated")) return "truncated";
|
||||
if (
|
||||
dimensions.some((status) =>
|
||||
["changed", "added", "removed"].includes(status),
|
||||
)
|
||||
)
|
||||
return "changed";
|
||||
return dimensions.includes("unknown") ? "unknown" : "unchanged";
|
||||
};
|
||||
|
||||
/** Pure normalized comparison between two captures. */
|
||||
export const processCaptureComparisonSchema = z
|
||||
.object({
|
||||
@@ -51,24 +76,9 @@ export const processCaptureComparisonSchema = z
|
||||
limitations: z.array(z.string()),
|
||||
})
|
||||
.superRefine((comparison, context) => {
|
||||
const dimensions = [
|
||||
comparison.terminal,
|
||||
comparison.interaction,
|
||||
comparison.exit,
|
||||
comparison.filesystem,
|
||||
comparison.protocol,
|
||||
comparison.process,
|
||||
comparison.shim,
|
||||
];
|
||||
const expected = dimensions.includes("truncated")
|
||||
? "truncated"
|
||||
: dimensions.some((status) =>
|
||||
["added", "removed", "changed"].includes(status),
|
||||
)
|
||||
? "changed"
|
||||
: dimensions.includes("unknown")
|
||||
? "unknown"
|
||||
: "unchanged";
|
||||
const expected = deriveProcessComparisonStatus(
|
||||
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => comparison[dimension]),
|
||||
);
|
||||
if (comparison.status !== expected)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
@@ -118,18 +128,6 @@ const hasUnknown = (
|
||||
scope: ProcessCapture["residual_unknowns"][number]["scope"],
|
||||
): boolean => capture.residual_unknowns.some((item) => item.scope === scope);
|
||||
|
||||
const comparisonStatus = (
|
||||
dimensions: readonly ComparisonStatus[],
|
||||
): ComparisonStatus => {
|
||||
if (
|
||||
dimensions.some((status) =>
|
||||
["changed", "added", "removed"].includes(status),
|
||||
)
|
||||
)
|
||||
return "changed";
|
||||
return dimensions.includes("unknown") ? "unknown" : "unchanged";
|
||||
};
|
||||
|
||||
type DivergenceDimension = Exclude<
|
||||
ProcessCaptureComparison["first_divergence"],
|
||||
{ readonly status: "none" | "unknown" }
|
||||
@@ -277,7 +275,7 @@ const compareDimensions = (
|
||||
terminalObservations(right),
|
||||
),
|
||||
interaction: classify(
|
||||
"terminal",
|
||||
"interaction",
|
||||
left.interaction_events,
|
||||
right.interaction_events,
|
||||
),
|
||||
@@ -295,9 +293,7 @@ const compareDimensions = (
|
||||
),
|
||||
protocol: classify("protocol", left.protocol_events, right.protocol_events),
|
||||
process: classify("process", left.process_samples, right.process_samples),
|
||||
shim: sameNormalization
|
||||
? classifyCollection(left.shim_events, right.shim_events)
|
||||
: "unknown",
|
||||
shim: classify("shim", left.shim_events, right.shim_events),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -367,15 +363,9 @@ export const compareProcessCaptures = (
|
||||
} as const)
|
||||
: observedFirstDivergence;
|
||||
return {
|
||||
status: comparisonStatus([
|
||||
dimensions.terminal,
|
||||
dimensions.interaction,
|
||||
dimensions.exit,
|
||||
dimensions.filesystem,
|
||||
dimensions.protocol,
|
||||
dimensions.process,
|
||||
dimensions.shim,
|
||||
]),
|
||||
status: deriveProcessComparisonStatus(
|
||||
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => dimensions[dimension]),
|
||||
),
|
||||
...dimensions,
|
||||
first_divergence: firstDivergence,
|
||||
limitations: [
|
||||
|
||||
@@ -10,6 +10,8 @@ import { parseEvidenceBundle } from "./evidenceBundle.js";
|
||||
import { functionComparisonResultSchema } from "./functionComparison.js";
|
||||
import { functionDossierSchema } from "./hopperValues.js";
|
||||
import {
|
||||
deriveProcessComparisonStatus,
|
||||
PROCESS_COMPARISON_DIMENSIONS,
|
||||
processCaptureComparisonSchema,
|
||||
processCaptureSchema,
|
||||
} from "./processCapture.js";
|
||||
@@ -319,22 +321,9 @@ const observedStatus = (claim: Claim, evidence: Evidence): ObservedStatus => {
|
||||
const validateProcessStatus = (
|
||||
result: z.infer<typeof processCaptureComparisonSchema>,
|
||||
): void => {
|
||||
const dimensions = [
|
||||
result.terminal,
|
||||
result.exit,
|
||||
result.filesystem,
|
||||
result.protocol,
|
||||
result.process,
|
||||
];
|
||||
const expected = dimensions.includes("truncated")
|
||||
? "truncated"
|
||||
: dimensions.some((status) =>
|
||||
["added", "removed", "changed"].includes(status),
|
||||
)
|
||||
? "changed"
|
||||
: dimensions.includes("unknown")
|
||||
? "unknown"
|
||||
: "unchanged";
|
||||
const expected = deriveProcessComparisonStatus(
|
||||
PROCESS_COMPARISON_DIMENSIONS.map((dimension) => result[dimension]),
|
||||
);
|
||||
if (result.status !== expected)
|
||||
throw new TypeError("Process comparison status contradicts its dimensions");
|
||||
};
|
||||
|
||||
@@ -20,10 +20,12 @@ const behavioralClaimSchema = z.object({
|
||||
dimension: z.enum([
|
||||
"overall",
|
||||
"terminal",
|
||||
"interaction",
|
||||
"exit",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"process",
|
||||
"shim",
|
||||
]),
|
||||
});
|
||||
const functionClaimSchema = z.object({
|
||||
|
||||
@@ -25,10 +25,12 @@ const functionDimensionSchema = z.enum([
|
||||
]);
|
||||
const runtimeDimensionSchema = z.enum([
|
||||
"terminal",
|
||||
"interaction",
|
||||
"exit",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"process",
|
||||
"shim",
|
||||
]);
|
||||
const expectedPatternSchema = z.enum([
|
||||
"cochanged",
|
||||
|
||||
@@ -26,11 +26,8 @@ export const discoverObjcClasses = (
|
||||
): JsonValue => {
|
||||
const classes = uniqueByName(
|
||||
names
|
||||
.filter(
|
||||
({ name }) =>
|
||||
["OBJC_CLASS", "OBJC_$_CLASS"].some((marker) =>
|
||||
name.includes(marker),
|
||||
) || name.startsWith("_OBJC_"),
|
||||
.filter(({ name }) =>
|
||||
["OBJC_CLASS", "OBJC_$_CLASS"].some((marker) => name.includes(marker)),
|
||||
)
|
||||
.filter(({ name }) => pattern.length === 0 || name.includes(pattern)),
|
||||
);
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ const logLevelSchema = z
|
||||
export const parseLogLevel = (value: unknown): LogLevel =>
|
||||
logLevelSchema.parse(value);
|
||||
|
||||
/** Create a JSON logger whose stderr destination cannot corrupt structured output. */
|
||||
/** Create a JSON logger on stderr so protocol and CLI result stdout stay valid. */
|
||||
export const createLogger = (mode: "mcp" | "cli", level: LogLevel): Logger =>
|
||||
pino(
|
||||
{
|
||||
|
||||
@@ -52,6 +52,11 @@ export interface NativeCommandRunner {
|
||||
): Promise<Result<NativeCommandCapture, NativeCommandFailure>>;
|
||||
}
|
||||
|
||||
/** Resolve one allowlisted native tool to an immutable executable identity. */
|
||||
export type NativeToolResolver = (
|
||||
tool: string,
|
||||
) => Promise<Result<ResolvedTool, NativeCommandFailure>>;
|
||||
|
||||
/** Run allowlisted Xcode tools directly with bounded output and no shell. */
|
||||
export class XcrunCommandRunner implements NativeCommandRunner {
|
||||
readonly #resolved = new Map<
|
||||
@@ -59,6 +64,11 @@ export class XcrunCommandRunner implements NativeCommandRunner {
|
||||
Promise<Result<ResolvedTool, NativeCommandFailure>>
|
||||
>();
|
||||
|
||||
constructor(
|
||||
private readonly resolveTool: NativeToolResolver = (tool) =>
|
||||
resolveXcrunTool(tool),
|
||||
) {}
|
||||
|
||||
run(
|
||||
tool: string,
|
||||
arguments_: readonly string[],
|
||||
@@ -96,16 +106,22 @@ export class XcrunCommandRunner implements NativeCommandRunner {
|
||||
});
|
||||
}
|
||||
|
||||
#resolve(tool: string): Promise<Result<ResolvedTool, NativeCommandFailure>> {
|
||||
async #resolve(
|
||||
tool: string,
|
||||
): Promise<Result<ResolvedTool, NativeCommandFailure>> {
|
||||
const existing = this.#resolved.get(tool);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = resolveTool(tool);
|
||||
const pending = this.resolveTool(tool);
|
||||
this.#resolved.set(tool, pending);
|
||||
return pending;
|
||||
const resolved = await pending;
|
||||
if (!resolved.ok && this.#resolved.get(tool) === pending)
|
||||
this.#resolved.delete(tool);
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
interface ResolvedTool {
|
||||
/** Immutable executable identity returned by native tool discovery. */
|
||||
export interface ResolvedTool {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
}
|
||||
@@ -124,7 +140,7 @@ const ALLOWED_TOOLS = new Set([
|
||||
"vtool",
|
||||
]);
|
||||
|
||||
const resolveTool = async (
|
||||
const resolveXcrunTool = async (
|
||||
tool: string,
|
||||
): Promise<Result<ResolvedTool, NativeCommandFailure>> => {
|
||||
const found = await captureProcess(
|
||||
|
||||
@@ -31,13 +31,14 @@ import {
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
} from "../domain/errors.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { runDerivedOperation } from "./runDerivedOperation.js";
|
||||
import {
|
||||
authorizeFileReadWithDeferredWrite,
|
||||
authorizeRootPermission,
|
||||
type DeferredFileWriteAuthorization,
|
||||
} from "../application/DeferredFileAuthorization.js";
|
||||
|
||||
/** Register Evidence-composed differential investigation workflows. */
|
||||
export const registerInvestigationTools = (
|
||||
@@ -94,59 +95,53 @@ const registerChangedBehavior = (
|
||||
const parsed = changedBehaviorInputSchema.parse(input);
|
||||
if (parsed.investigation_run !== undefined) {
|
||||
const progress = mcpProgressReporter(context);
|
||||
let workspaceAuthorization: DeferredFileWriteAuthorization | undefined;
|
||||
if (policies.permissionAuthority !== undefined) {
|
||||
const scopes = [
|
||||
const authorizedWorkspace = await authorizeFileReadWithDeferredWrite(
|
||||
policies.permissionAuthority,
|
||||
{
|
||||
capability: "investigation_workspace_read" as const,
|
||||
roots: [parsed.investigation_run.workspace_path],
|
||||
path: parsed.investigation_run.workspace_path,
|
||||
readCapability: "investigation_workspace_read",
|
||||
writeCapability: "investigation_workspace_write",
|
||||
operation: contract.name,
|
||||
},
|
||||
);
|
||||
if (!authorizedWorkspace.ok)
|
||||
return toCallToolResult(authorizedWorkspace, contract);
|
||||
workspaceAuthorization = authorizedWorkspace.value;
|
||||
const authorizedInput = await authorizeRootPermission(
|
||||
policies.permissionAuthority,
|
||||
{
|
||||
capability: "investigation_workspace_write" as const,
|
||||
roots: [parsed.investigation_run.workspace_path],
|
||||
},
|
||||
{
|
||||
capability: "investigation_input" as const,
|
||||
capability: "investigation_input",
|
||||
roots: [
|
||||
parsed.investigation_run.left_path,
|
||||
parsed.investigation_run.right_path,
|
||||
],
|
||||
access: "read",
|
||||
operation: contract.name,
|
||||
},
|
||||
];
|
||||
for (const scope of scopes) {
|
||||
const authorized = await policies.permissionAuthority.authorize(
|
||||
{
|
||||
...scope,
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `${contract.name}:${scope.capability}:${scope.roots.join(":")}`,
|
||||
},
|
||||
scope.capability === "investigation_input" ? "read" : "write",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return toCallToolResult(
|
||||
err(
|
||||
authorized.error instanceof PermissionRequiredError
|
||||
? authorized.error
|
||||
: new AnalysisProtocolError(authorized.error.message, {
|
||||
cause: authorized.error,
|
||||
}),
|
||||
),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
);
|
||||
if (!authorizedInput.ok)
|
||||
return toCallToolResult(authorizedInput, contract);
|
||||
}
|
||||
const investigated = await runCrossVersionInvestigation(
|
||||
parsed.investigation_run,
|
||||
policies.evidenceFiles,
|
||||
investigationExecution(
|
||||
session,
|
||||
context.mcpReq.signal,
|
||||
policies.inputRoots,
|
||||
policies.integrityContinueEnabled?.() ?? false,
|
||||
progress,
|
||||
),
|
||||
{
|
||||
...investigationExecution(
|
||||
session,
|
||||
context.mcpReq.signal,
|
||||
policies.inputRoots,
|
||||
policies.integrityContinueEnabled?.() ?? false,
|
||||
progress,
|
||||
),
|
||||
...(workspaceAuthorization === undefined
|
||||
? {}
|
||||
: {
|
||||
authorizeWorkspaceWrite:
|
||||
workspaceAuthorization.authorizeWrite,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!investigated.ok) return toCallToolResult(investigated, contract);
|
||||
const workspace = investigated.value.workspace;
|
||||
|
||||
@@ -150,10 +150,12 @@ const comparisonUnknownInput = (
|
||||
return undefined;
|
||||
const differingScopes = [
|
||||
["terminal", comparison.terminal],
|
||||
["interaction", comparison.interaction],
|
||||
["exit", comparison.exit],
|
||||
["filesystem", comparison.filesystem],
|
||||
["protocol", comparison.protocol],
|
||||
["process", comparison.process],
|
||||
["shim", comparison.shim],
|
||||
]
|
||||
.filter(([, status]) => status !== "unchanged")
|
||||
.map(([scope]) => scope)
|
||||
|
||||
@@ -303,6 +303,7 @@ const registerEvidenceTools = ({
|
||||
const loaded = await readEvidenceBundle(path, filePolicy);
|
||||
if (!loaded.ok) return toCallToolResult(loaded, importContract);
|
||||
const imported = session.importEvidenceBundle(loaded.value);
|
||||
if (imported.ok && imported.value > 0) server.sendResourceListChanged();
|
||||
return imported.ok
|
||||
? toCallToolResult(
|
||||
ok({
|
||||
@@ -378,11 +379,13 @@ const registerUnknownTools = ({
|
||||
outputSchema: recordContract.outputSchema,
|
||||
annotations: recordContract.annotations,
|
||||
},
|
||||
(input) =>
|
||||
toCallToolResult(
|
||||
session.recordUnknown(recordUnknownInputSchema.parse(input)),
|
||||
recordContract,
|
||||
),
|
||||
(input) => {
|
||||
const recorded = session.recordUnknown(
|
||||
recordUnknownInputSchema.parse(input),
|
||||
);
|
||||
if (recorded.ok) server.sendResourceListChanged();
|
||||
return toCallToolResult(recorded, recordContract);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
updateContract.name,
|
||||
@@ -392,11 +395,13 @@ const registerUnknownTools = ({
|
||||
outputSchema: updateContract.outputSchema,
|
||||
annotations: updateContract.annotations,
|
||||
},
|
||||
(input) =>
|
||||
toCallToolResult(
|
||||
session.updateUnknown(updateUnknownInputSchema.parse(input)),
|
||||
updateContract,
|
||||
),
|
||||
(input) => {
|
||||
const updated = session.updateUnknown(
|
||||
updateUnknownInputSchema.parse(input),
|
||||
);
|
||||
if (updated.ok) server.sendResourceListChanged();
|
||||
return toCallToolResult(updated, updateContract);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
verifyContract.name,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
|
||||
import { AnalysisCancelledError } from "../domain/errors.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
|
||||
@@ -25,7 +28,7 @@ export const runDerivedOperation = async <Value>(
|
||||
context: DerivedOperationContext,
|
||||
operation: string,
|
||||
compute: () => Value,
|
||||
): Promise<Result<Value, AnalysisCancelledError>> => {
|
||||
): Promise<Result<Value, AnalysisCancelledError | AnalysisInputError>> => {
|
||||
const progress = mcpProgressReporter(context);
|
||||
await progress.report({
|
||||
phase: "prepare",
|
||||
@@ -36,7 +39,16 @@ export const runDerivedOperation = async <Value>(
|
||||
await setImmediate();
|
||||
if (context.mcpReq.signal.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const value = compute();
|
||||
let value: Value;
|
||||
try {
|
||||
value = compute();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
cause instanceof AnalysisCancelledError
|
||||
? cause
|
||||
: new AnalysisInputError(operation, { cause }),
|
||||
);
|
||||
}
|
||||
await progress.report({
|
||||
phase: "compute",
|
||||
completed: 1,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
readAnalysisSnapshot,
|
||||
writeAnalysisSnapshot,
|
||||
} from "../src/application/AnalysisSnapshotFiles.js";
|
||||
import { AnalysisSnapshotCache } from "../src/application/AnalysisSnapshotCache.js";
|
||||
import {
|
||||
createAnalysisSnapshotEntry,
|
||||
parseAnalysisSnapshot,
|
||||
@@ -27,6 +28,49 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("analysis snapshots", () => {
|
||||
it("returns detached cache entries and evidence bundles", () => {
|
||||
const cache = new AnalysisSnapshotCache();
|
||||
const target = {
|
||||
path: "/tmp/app",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "mach-o",
|
||||
architecture: "arm64",
|
||||
loaderArgs: [],
|
||||
} as const;
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
cache.record(
|
||||
target,
|
||||
"address_name",
|
||||
{ address: "0x1000", document: "fixture" },
|
||||
createAnalysisExecution("main", provider),
|
||||
);
|
||||
const exported = cache.export(target, createEvidenceBundle([]));
|
||||
expect(exported.ok).toBe(true);
|
||||
if (!exported.ok) return;
|
||||
const entry = exported.value.entries[0];
|
||||
if (entry !== undefined) {
|
||||
Reflect.set(entry.execution, "provider", {
|
||||
id: "forged",
|
||||
name: "Forged",
|
||||
version: "9",
|
||||
});
|
||||
(entry.execution.limitations as string[]).push("forged");
|
||||
}
|
||||
|
||||
expect(
|
||||
cache.lookup(
|
||||
target,
|
||||
"address_name",
|
||||
{ address: "0x1000", document: "fixture" },
|
||||
provider,
|
||||
),
|
||||
).toMatchObject({
|
||||
provider,
|
||||
limitations: [expect.stringContaining("local REA analysis snapshot")],
|
||||
});
|
||||
});
|
||||
|
||||
it("finds exact CLI evidence for provider-free replay", () => {
|
||||
const target = {
|
||||
path: "/tmp/app",
|
||||
|
||||
@@ -53,7 +53,7 @@ describe("artifact graph provider", () => {
|
||||
machO,
|
||||
);
|
||||
await writeFile(join(app, "Contents", "Resources", "main.js"), "main();\n");
|
||||
await writeFile(join(app, "Contents", "Resources", "main.js.map"), "{}\n");
|
||||
await writeFile(join(app, "Contents", "Resources", "main.js.MAP"), "{}\n");
|
||||
await symlink("/etc/passwd", join(app, "Contents", "Resources", "outside"));
|
||||
const client = new ArtifactProvider().createClient(
|
||||
target(app, "directory"),
|
||||
@@ -88,7 +88,7 @@ describe("artifact graph provider", () => {
|
||||
path.endsWith("main.js"),
|
||||
);
|
||||
const sourceMap = left.occurrences.items.find(({ logical_path: path }) =>
|
||||
path.endsWith("main.js.map"),
|
||||
path.endsWith("main.js.MAP"),
|
||||
);
|
||||
expect(left.edges.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
@@ -382,6 +382,10 @@ describe("artifact graph provider", () => {
|
||||
expect(reader.provenance()).toEqual([
|
||||
expect.objectContaining({ tool: "lipo", effects: ["read"] }),
|
||||
]);
|
||||
const provenance = reader.provenance();
|
||||
if (provenance[0] !== undefined)
|
||||
Reflect.set(provenance[0], "tool", "forged");
|
||||
expect(reader.provenance()[0]?.tool).toBe("lipo");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { scanAuthorizedArtifactInventory } from "../src/application/AuthorizedArtifactInventory.js";
|
||||
|
||||
const LIMITS = {
|
||||
maxEntries: 100,
|
||||
maxTotalBytes: 1024 * 1024,
|
||||
maxEntryBytes: 1024 * 1024,
|
||||
maxCompressionRatio: 100,
|
||||
maxDepth: 10,
|
||||
maxPathBytes: 1024,
|
||||
} as const;
|
||||
|
||||
describe("authorized artifact inventory", () => {
|
||||
it("uses a valid input root when another configured root is missing", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-artifact-roots-"));
|
||||
try {
|
||||
const path = join(root, "artifact.js");
|
||||
await writeFile(path, "export const value = 1;\n");
|
||||
const inventory = await scanAuthorizedArtifactInventory(
|
||||
path,
|
||||
[join(root, "missing"), root],
|
||||
LIMITS,
|
||||
);
|
||||
expect(inventory.manifest.root_format).toBe("javascript-bundle");
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
ProviderAdapterError,
|
||||
} from "../src/domain/errors.js";
|
||||
import { err } from "../src/domain/result.js";
|
||||
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
|
||||
import { createInvestigationWorkspace } from "../src/domain/investigationWorkspace.js";
|
||||
import { observed as ok } from "./fixtures/analysisExecution.js";
|
||||
|
||||
let directory: string | undefined;
|
||||
@@ -24,6 +26,35 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("binary session", () => {
|
||||
it("returns detached provider, target, and workspace metadata", async () => {
|
||||
const [first] = await targets();
|
||||
const session = new BinarySession(cacheProvider([]));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
const identity = session.providerIdentity();
|
||||
Reflect.set(identity, "id", "forged");
|
||||
expect(session.providerIdentity().id).toBe("fixture");
|
||||
|
||||
const active = session.activeTarget();
|
||||
expect(active).toBeDefined();
|
||||
if (active !== undefined) Reflect.set(active, "path", "/tmp/forged");
|
||||
expect(session.activeTarget()?.path).toBe(first);
|
||||
|
||||
const workspace = createInvestigationWorkspace(
|
||||
"Detached workspace",
|
||||
createEvidenceBundle([]),
|
||||
[],
|
||||
);
|
||||
expect(session.retainInvestigationWorkspace(workspace)).toBe("added");
|
||||
const direct = session.investigationWorkspace(workspace.workspace_id, 1);
|
||||
if (direct !== undefined) Reflect.set(direct, "revision", 999);
|
||||
const listed = session.investigationWorkspaces()[0];
|
||||
if (listed !== undefined) Reflect.set(listed, "workspace_id", "forged");
|
||||
expect(
|
||||
session.investigationWorkspace(workspace.workspace_id, 1),
|
||||
).toMatchObject({ revision: 1, workspace_id: workspace.workspace_id });
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("runs through a non-Hopper analysis provider", async () => {
|
||||
const [first] = await targets();
|
||||
const operations: string[] = [];
|
||||
|
||||
@@ -53,17 +53,19 @@ const processResult = (
|
||||
overrides: Partial<{
|
||||
status: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
terminal: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
interaction: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
exit: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
shim: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
}> = {},
|
||||
): JsonValue => ({
|
||||
status: overrides.status ?? "unchanged",
|
||||
terminal: overrides.terminal ?? "unchanged",
|
||||
interaction: "unchanged",
|
||||
interaction: overrides.interaction ?? "unchanged",
|
||||
exit: overrides.exit ?? "unchanged",
|
||||
filesystem: "unchanged",
|
||||
protocol: "unchanged",
|
||||
process: "unchanged",
|
||||
shim: "unchanged",
|
||||
shim: overrides.shim ?? "unchanged",
|
||||
first_divergence:
|
||||
overrides.status === "changed"
|
||||
? {
|
||||
@@ -121,6 +123,31 @@ const artifactResult = (
|
||||
});
|
||||
|
||||
describe("changed behavior", () => {
|
||||
it("reports interaction and shim-only process changes", () => {
|
||||
const evidence = comparison(
|
||||
"compare_process_captures",
|
||||
processResult({
|
||||
status: "changed",
|
||||
interaction: "changed",
|
||||
shim: "changed",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(findChangedBehavior([evidence], 0, 100)).toMatchObject({
|
||||
behavior_status: "observed_changed",
|
||||
summary: { observed_changes: 2 },
|
||||
findings: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
dimension: "interaction",
|
||||
scope: "runtime",
|
||||
}),
|
||||
expect.objectContaining({ dimension: "shim", scope: "protocol" }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies runtime changes as observed and cites both observations", () => {
|
||||
const evidence = comparison(
|
||||
"compare_process_captures",
|
||||
|
||||
@@ -69,4 +69,22 @@ describe("derived MCP operation boundary", () => {
|
||||
expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]);
|
||||
expect(notifications.every(({ params }) => params?.total === 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("projects synchronous computation failures into a typed result", async () => {
|
||||
const result = await runDerivedOperation(
|
||||
context(new AbortController()),
|
||||
"compare_artifacts",
|
||||
() => {
|
||||
throw new TypeError("malformed comparison evidence");
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
operation: "compare_artifacts",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { writeAnalysisSnapshot } from "../src/application/AnalysisSnapshotFiles.js";
|
||||
import { runDirectAnalysis } from "../src/application/DirectAnalysis.js";
|
||||
import type { AnalysisSnapshot } from "../src/domain/analysisSnapshot.js";
|
||||
import { parseBinaryTarget } from "../src/domain/binaryTarget.js";
|
||||
import { createEvidence } from "../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
|
||||
import { permissionAuthorityForRoot } from "./fixtures/permissionAuthority.js";
|
||||
|
||||
let directory: string | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
describe("direct analysis snapshot permissions", () => {
|
||||
it("replays a cache hit with snapshot read authority only", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-direct-snapshot-"));
|
||||
const snapshotPath = join(directory, "analysis.json");
|
||||
const target = await parseBinaryTarget(process.execPath);
|
||||
if (!target.ok) throw target.error;
|
||||
const provider = {
|
||||
id: "rea-workflow",
|
||||
name: "REA composed investigation workflow",
|
||||
version: "1",
|
||||
} as const;
|
||||
const evidence = createEvidence(target.value, provider, {
|
||||
operation: "binary_overview",
|
||||
parameters: {},
|
||||
result: { cached: true },
|
||||
});
|
||||
const snapshot: AnalysisSnapshot = {
|
||||
snapshot_version: 1,
|
||||
target: {
|
||||
sha256: target.value.sha256,
|
||||
format: target.value.format,
|
||||
architecture: target.value.architecture ?? null,
|
||||
loader_args: [...target.value.loaderArgs],
|
||||
},
|
||||
entries: [],
|
||||
evidence_bundle: createEvidenceBundle([evidence]),
|
||||
};
|
||||
const policy = {
|
||||
roots: [directory],
|
||||
maxBytes: 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024,
|
||||
maxNodes: 10_000,
|
||||
};
|
||||
expect(
|
||||
(await writeAnalysisSnapshot(snapshot, snapshotPath, false, policy)).ok,
|
||||
).toBe(true);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
directory,
|
||||
["snapshot_read", "snapshot_write"],
|
||||
["snapshot_read"],
|
||||
);
|
||||
vi.stubEnv("REA_ANALYSIS_SNAPSHOT_ROOTS_JSON", JSON.stringify([directory]));
|
||||
|
||||
await expect(
|
||||
runDirectAnalysis(
|
||||
process.execPath,
|
||||
"binary_overview",
|
||||
{},
|
||||
{
|
||||
snapshotPath,
|
||||
permissionAuthority: authority,
|
||||
},
|
||||
),
|
||||
).resolves.toEqual(evidence);
|
||||
});
|
||||
});
|
||||
@@ -215,8 +215,7 @@ describe("enhanced MCP tools", () => {
|
||||
);
|
||||
}
|
||||
expect(results[0]).toMatchObject({ count: 1 });
|
||||
// Legacy behavior treats any `_OBJC_` label, including protocol labels, as a class.
|
||||
expect(results[1]).toMatchObject({ count: 2 });
|
||||
expect(results[1]).toMatchObject({ count: 1 });
|
||||
expect(results[2]).toMatchObject({ count: 1 });
|
||||
expect(results[3]).toEqual({
|
||||
items: [
|
||||
|
||||
@@ -93,6 +93,21 @@ describe("evidence bundle filesystem adapter", () => {
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("uses valid evidence roots when another configured root is missing", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-evidence-roots-"));
|
||||
const path = join(directory, "bundle.json");
|
||||
const configured = {
|
||||
...policy(directory),
|
||||
roots: [join(directory, "missing"), directory],
|
||||
};
|
||||
expect(
|
||||
await writeEvidenceBundle(bundle(), path, false, configured),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await readEvidenceBundle(path, configured)).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects traversal and symlink escape from approved roots", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-evidence-"));
|
||||
const root = join(directory, "approved");
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
createPermissionAuthority,
|
||||
type PermissionAuthority,
|
||||
} from "../../src/application/PermissionAuthority.js";
|
||||
import type {
|
||||
PermissionCapability,
|
||||
PermissionCeiling,
|
||||
PermissionGrant,
|
||||
} from "../../src/domain/permissionPolicy.js";
|
||||
|
||||
/** Build a canonical root-scoped authority with selected administrator grants. */
|
||||
export const permissionAuthorityForRoot = async (
|
||||
root: string,
|
||||
capabilities: readonly PermissionCapability[],
|
||||
grantedCapabilities: readonly PermissionCapability[],
|
||||
): Promise<PermissionAuthority> => {
|
||||
const ceilings = capabilities.map((capability) => scope(capability, root));
|
||||
const grants = ceilings
|
||||
.filter(({ capability }) => grantedCapabilities.includes(capability))
|
||||
.map(administratorGrant);
|
||||
const authority = await createPermissionAuthority(ceilings, grants);
|
||||
if (!authority.ok) throw authority.error;
|
||||
return authority.value;
|
||||
};
|
||||
|
||||
const scope = (
|
||||
capability: PermissionCapability,
|
||||
root: string,
|
||||
): PermissionCeiling => ({
|
||||
capability,
|
||||
roots: [root],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
});
|
||||
|
||||
const administratorGrant = (ceiling: PermissionCeiling): PermissionGrant => ({
|
||||
...ceiling,
|
||||
grant_id: `administrator:${ceiling.capability}`,
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
Vendored
+7
@@ -18,6 +18,13 @@ if (mode === "interactive") {
|
||||
process.stdin.on("data", (value) => {
|
||||
process.stdout.write(`input:${value.toString()} unicode:雪\n`);
|
||||
});
|
||||
} else if (mode === "silent-interactive") {
|
||||
process.stdin.setRawMode?.(true);
|
||||
process.stdin.resume();
|
||||
process.stdin.on("data", (value) => {
|
||||
process.stdout.write(`input:${value.toString()}\n`);
|
||||
process.exit(0);
|
||||
});
|
||||
} else if (mode === "partial") {
|
||||
process.stdout.write("partial-");
|
||||
setTimeout(() => {
|
||||
|
||||
@@ -290,7 +290,27 @@ describe("full MCP integration with multi-tool sequences", () => {
|
||||
const left = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const right = processCaptureSchema.parse({
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
exit: { code: 1, signal: null, reason: "exited" },
|
||||
interaction_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 0,
|
||||
dispatched_at_ms: 0,
|
||||
type: "input",
|
||||
data: "fixture",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
],
|
||||
shim_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
command: "fixture",
|
||||
route_index: null,
|
||||
arguments: [],
|
||||
working_directory: "/tmp",
|
||||
outcome: "unmatched",
|
||||
},
|
||||
],
|
||||
});
|
||||
const captureEvidence = (capture: typeof left) =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
@@ -347,6 +367,7 @@ describe("full MCP integration with multi-tool sequences", () => {
|
||||
{
|
||||
status: "contradicted",
|
||||
domain: "process-comparison",
|
||||
question: "Process captures disagree across: interaction, shim",
|
||||
contradicting_evidence_ids: [rightEvidence.evidence_id],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -20,6 +20,8 @@ import { createServer } from "../src/server/createServer.js";
|
||||
import { observed } from "./fixtures/analysisExecution.js";
|
||||
import { readInvestigationWorkspace } from "../src/application/InvestigationWorkspaceStore.js";
|
||||
import type { EvidenceFilePolicy } from "../src/domain/evidenceBundle.js";
|
||||
import type { PermissionAuthority } from "../src/application/PermissionAuthority.js";
|
||||
import { permissionAuthorityForRoot } from "./fixtures/permissionAuthority.js";
|
||||
|
||||
describe("investigation MCP workflows", () => {
|
||||
it("never retains derived evidence after request cancellation", async () => {
|
||||
@@ -147,6 +149,71 @@ describe("investigation MCP workflows", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("replays a complete workspace without write authority", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-investigation-read-"));
|
||||
const left = join(directory, "left");
|
||||
const right = join(directory, "right");
|
||||
const workspace = join(directory, "workspace.json");
|
||||
await Promise.all([mkdir(left), mkdir(right)]);
|
||||
await Promise.all([
|
||||
writeFile(join(left, "feature.txt"), "old\n"),
|
||||
writeFile(join(right, "feature.txt"), "new\n"),
|
||||
]);
|
||||
const filePolicy = evidencePolicy(directory);
|
||||
const arguments_ = {
|
||||
investigation_run: {
|
||||
approved: true,
|
||||
workspace_path: workspace,
|
||||
workspace_name: "read-only-replay",
|
||||
left_path: left,
|
||||
right_path: right,
|
||||
options: { page_size: 500, change_limit: 100 },
|
||||
},
|
||||
};
|
||||
const writer = await investigationAuthority(directory, true);
|
||||
const initial = await connected(filePolicy, [directory], writer);
|
||||
try {
|
||||
const created = await initial.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(created.isError, JSON.stringify(created)).not.toBe(true);
|
||||
} finally {
|
||||
await close(initial.session, initial.server, initial.client);
|
||||
}
|
||||
|
||||
const reader = await investigationAuthority(directory, false);
|
||||
const replay = await connected(filePolicy, [directory], reader);
|
||||
try {
|
||||
const cached = await replay.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(cached.isError, JSON.stringify(cached)).not.toBe(true);
|
||||
expect(
|
||||
await readInvestigationWorkspace(workspace, filePolicy),
|
||||
).toMatchObject({ ok: true, value: { revision: 3 } });
|
||||
|
||||
await writeFile(join(right, "feature.txt"), "changed again\n");
|
||||
const denied = await replay.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: arguments_,
|
||||
});
|
||||
expect(denied).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: {
|
||||
code: "permission_required",
|
||||
details: { capability: "investigation_workspace_write" },
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await close(replay.session, replay.server, replay.client);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses automatic artifact reads outside operator-approved roots", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-investigation-mcp-"));
|
||||
const approvedInputs = join(directory, "approved-inputs");
|
||||
@@ -492,22 +559,22 @@ describe("investigation MCP workflows", () => {
|
||||
const connected = async (
|
||||
evidenceFilePolicy?: EvidenceFilePolicy,
|
||||
investigationInputRoots: readonly string[] = evidenceFilePolicy?.roots ?? [],
|
||||
permissionAuthority?: PermissionAuthority,
|
||||
) => {
|
||||
const session = new BinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(
|
||||
session,
|
||||
session,
|
||||
evidenceFilePolicy === undefined
|
||||
const server = createServer(session, session, {
|
||||
...(evidenceFilePolicy === undefined
|
||||
? {}
|
||||
: {
|
||||
evidenceFilePolicy,
|
||||
investigationInputRoots,
|
||||
},
|
||||
);
|
||||
}),
|
||||
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
|
||||
});
|
||||
const client = new Client({ name: "investigation-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
@@ -524,6 +591,24 @@ const evidencePolicy = (root: string): EvidenceFilePolicy => ({
|
||||
maxNodes: 1_000_000,
|
||||
});
|
||||
|
||||
const investigationAuthority = async (
|
||||
root: string,
|
||||
includeWrite: boolean,
|
||||
): Promise<PermissionAuthority> =>
|
||||
permissionAuthorityForRoot(
|
||||
root,
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"investigation_input",
|
||||
],
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_input",
|
||||
...(includeWrite ? (["investigation_workspace_write"] as const) : []),
|
||||
],
|
||||
);
|
||||
|
||||
const close = async (
|
||||
session: BinarySession,
|
||||
server: Awaited<ReturnType<typeof createServer>>,
|
||||
|
||||
@@ -239,6 +239,27 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("enforces shared JSON depth limits while reading workspaces", async () => {
|
||||
const { path, input } = await fixture();
|
||||
if (directory === undefined) throw new Error("missing fixture root");
|
||||
const completed = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
);
|
||||
if (!completed.ok) throw completed.error;
|
||||
|
||||
await expect(
|
||||
readInvestigationWorkspace(path, {
|
||||
...policy(directory),
|
||||
maxDepth: 1,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "InvestigationWorkspaceError", reason: "too-large" },
|
||||
});
|
||||
});
|
||||
|
||||
it("resumes from a comparison checkpoint without recomputing its identity", async () => {
|
||||
const { input } = await fixture();
|
||||
if (directory === undefined) throw new Error("missing fixture root");
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isJsonWithinLimits } from "../src/domain/jsonLimits.js";
|
||||
|
||||
const limits = {
|
||||
maxDepth: 3,
|
||||
maxStringLength: 8,
|
||||
maxNodes: 6,
|
||||
};
|
||||
|
||||
describe("JSON limits", () => {
|
||||
it("traverses nested object and array values", () => {
|
||||
expect(isJsonWithinLimits({ one: ["two", { three: 3 }] }, limits)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
isJsonWithinLimits({ one: ["two", { three: "too-long-value" }] }, limits),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("enforces depth, node, and object-key limits", () => {
|
||||
expect(
|
||||
isJsonWithinLimits(
|
||||
{ one: { two: { three: null } } },
|
||||
{
|
||||
...limits,
|
||||
maxDepth: 2,
|
||||
},
|
||||
),
|
||||
).toBe(false);
|
||||
expect(isJsonWithinLimits([1, 2, 3], { ...limits, maxNodes: 3 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isJsonWithinLimits({ "too-long-key": true }, limits)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -41,6 +41,10 @@ describe("native DMG artifact reader", () => {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry.path);
|
||||
expect(entries).toContain("image.dmg/Fixture/hello.txt");
|
||||
const provenance = reader.provenance();
|
||||
if (provenance[0] !== undefined)
|
||||
Reflect.set(provenance[0], "tool", "forged");
|
||||
expect(reader.provenance()[0]?.tool).toBe("hdiutil");
|
||||
await reader.close();
|
||||
expect(calls).toContainEqual(["verify", "/tmp/image.dmg"]);
|
||||
expect(calls).toContainEqual(["detach", "/dev/disk-fixture"]);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { NativeMacOSProvider } from "../src/native/NativeMacOSProvider.js";
|
||||
import {
|
||||
NativeCommandFailure,
|
||||
XcrunCommandRunner,
|
||||
type NativeCommandCapture,
|
||||
type NativeCommandRunner,
|
||||
} from "../src/native/CommandRunner.js";
|
||||
@@ -22,6 +23,24 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("native macOS provider", () => {
|
||||
it("retries a failed native tool resolution and caches only success", async () => {
|
||||
let resolutions = 0;
|
||||
const runner = new XcrunCommandRunner((tool) => {
|
||||
resolutions += 1;
|
||||
return Promise.resolve(
|
||||
resolutions === 1
|
||||
? err(new NativeCommandFailure(tool, "unavailable"))
|
||||
: ok({ path: "/bin/true", sha256: "a".repeat(64) }),
|
||||
);
|
||||
});
|
||||
const options = { timeoutMs: 1_000, maxOutputBytes: 1_024 };
|
||||
|
||||
expect((await runner.run("file", [], options)).ok).toBe(false);
|
||||
expect((await runner.run("file", [], options)).ok).toBe(true);
|
||||
expect((await runner.run("file", [], options)).ok).toBe(true);
|
||||
expect(resolutions).toBe(2);
|
||||
});
|
||||
|
||||
it("normalizes comprehensive Mach-O inspection with exact bounded provenance", async () => {
|
||||
const runner = new FixtureRunner();
|
||||
const client = new NativeMacOSProvider(runner, "darwin").createClient(
|
||||
|
||||
@@ -176,6 +176,42 @@ describe("permission policy", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a missing scope when revoked grants cover a different root", () => {
|
||||
const ceiling = {
|
||||
capability: "evidence_write" as const,
|
||||
roots: ["/workspace"],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
};
|
||||
const granted = grantPermission(createPermissionPolicy([ceiling]), {
|
||||
...ceiling,
|
||||
roots: ["/workspace/first"],
|
||||
grant_id: "revoked-other-root",
|
||||
lifetime: "project",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
expect(granted.ok).toBe(true);
|
||||
if (!granted.ok) return;
|
||||
|
||||
expect(
|
||||
evaluatePermission(
|
||||
revokePermission(granted.value, "revoked-other-root"),
|
||||
{
|
||||
...ceiling,
|
||||
roots: ["/workspace/second"],
|
||||
operation_identity: "write:report.json",
|
||||
},
|
||||
),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "grant_required",
|
||||
missing: { roots: ["/workspace/second"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("expires grants, removes session authority on disconnect, and never combines partial grants", () => {
|
||||
const ceiling = {
|
||||
capability: "process_capture" as const,
|
||||
|
||||
@@ -13,6 +13,14 @@ import {
|
||||
ProcessCaptureError,
|
||||
} from "../src/application/ProcessHarness.js";
|
||||
import { snapshotRoots } from "../src/application/FilesystemSnapshot.js";
|
||||
import {
|
||||
prepareProcessCapture,
|
||||
type ProcessPreparationHost,
|
||||
} from "../src/application/ProcessCaptureLifecycle.js";
|
||||
import { ProcessCheckpoints } from "../src/application/ProcessCheckpoints.js";
|
||||
import { normalizeProcessSamples } from "../src/application/ProcessNormalization.js";
|
||||
import { readLinuxChildren } from "../src/application/ProcessSampling.js";
|
||||
import { TerminalRenderer } from "../src/application/TerminalRenderer.js";
|
||||
import {
|
||||
authorizeProcessScenario,
|
||||
compareProcessCaptures,
|
||||
@@ -106,6 +114,132 @@ describe("process capture domain", () => {
|
||||
working_directory: "/tmp",
|
||||
};
|
||||
|
||||
it("returns detached terminal and filesystem checkpoint observations", async () => {
|
||||
const renderer = new TerminalRenderer({
|
||||
columns: 40,
|
||||
rows: 12,
|
||||
scrollback: 100,
|
||||
maxFrames: 10,
|
||||
maxBytes: 10_000,
|
||||
normalize: (value) => value,
|
||||
});
|
||||
renderer.write("A", 0);
|
||||
const frames = await renderer.frames();
|
||||
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
|
||||
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
|
||||
await renderer.dispose();
|
||||
|
||||
const scenario = parseProcessScenario(base);
|
||||
const checkpoints = new ProcessCheckpoints(
|
||||
scenario,
|
||||
Date.now(),
|
||||
{ files: [], truncated: false },
|
||||
undefined,
|
||||
);
|
||||
const first = await checkpoints.finish({ files: [], truncated: false });
|
||||
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
|
||||
const second = await checkpoints.finish({ files: [], truncated: false });
|
||||
expect(second[0]?.name).toBe("before");
|
||||
await checkpoints.dispose();
|
||||
});
|
||||
|
||||
it("cleans the temporary root when capture home creation fails", async () => {
|
||||
const cleaned: string[] = [];
|
||||
const host: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
|
||||
createHome: () => Promise.reject(new Error("mkdir failed")),
|
||||
cleanup: (path) => {
|
||||
cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
prepareProcessCapture(
|
||||
parseProcessScenario(base),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
undefined,
|
||||
host,
|
||||
),
|
||||
).rejects.toThrow("mkdir failed");
|
||||
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
|
||||
});
|
||||
|
||||
it("normalizes every sampled process identifier in command text", () => {
|
||||
const samples = normalizeProcessSamples(
|
||||
[
|
||||
{
|
||||
at_ms: 0,
|
||||
pid: 101,
|
||||
parent_pid: 0,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "root 101",
|
||||
},
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 202,
|
||||
parent_pid: 101,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "child 202 peer=101 unrelated 1202",
|
||||
},
|
||||
],
|
||||
parseProcessScenario(base),
|
||||
101,
|
||||
);
|
||||
|
||||
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
|
||||
});
|
||||
|
||||
it("collects and deduplicates children from every Linux thread", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
expect(
|
||||
await readLinuxChildren(100, signal, {
|
||||
taskIds: () => Promise.resolve([100, 101, 102]),
|
||||
children: (_pid, taskId) =>
|
||||
Promise.resolve(
|
||||
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
|
||||
),
|
||||
}),
|
||||
).toEqual([201, 202, 203]);
|
||||
});
|
||||
|
||||
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
|
||||
const baseCapture = emptyCapture();
|
||||
const interaction = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "interaction", reason: "Interaction capture was partial." },
|
||||
],
|
||||
});
|
||||
const shim = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "shim", reason: "Shim capture was partial." },
|
||||
],
|
||||
});
|
||||
|
||||
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unknown",
|
||||
shim: "unchanged",
|
||||
});
|
||||
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unchanged",
|
||||
shim: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels filesystem snapshots before traversing declared roots", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
@@ -933,6 +1067,47 @@ describe("process capture adapter", () => {
|
||||
expect(result.value.exit.code).toBe(0);
|
||||
});
|
||||
|
||||
it("dispatches scheduled events before a silent PTY produces output", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
approved: true,
|
||||
executable: process.execPath,
|
||||
arguments: [processFixture, "silent-interactive"],
|
||||
working_directory: dirname(processFixture),
|
||||
events: [
|
||||
{ type: "resize", at_ms: 25, columns: 100, rows: 40 },
|
||||
{ type: "input", at_ms: 50, data: "answer" },
|
||||
],
|
||||
timeout_ms: 2_000,
|
||||
idle_timeout_ms: 2_000,
|
||||
}),
|
||||
{
|
||||
enabled: true,
|
||||
executableRoots: [
|
||||
join(dirname(process.execPath), "missing"),
|
||||
dirname(process.execPath),
|
||||
],
|
||||
workingRoots: [
|
||||
join(dirname(processFixture), "missing"),
|
||||
dirname(processFixture),
|
||||
],
|
||||
allowedEnvironment: [],
|
||||
allowExternalNetwork: true,
|
||||
},
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.frames.map(({ data }) => data).join("")).toContain(
|
||||
"input:answer",
|
||||
);
|
||||
expect(result.value.interaction_events).toMatchObject([
|
||||
{ type: "resize", outcome: "dispatched" },
|
||||
{ type: "input", outcome: "dispatched" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("samples and cleans a source-owned child and grandchild process tree", async () => {
|
||||
const capability = await probeProcessCaptureCapability();
|
||||
if (!capability.available) return;
|
||||
|
||||
@@ -175,4 +175,17 @@ describe("process CLI errors", () => {
|
||||
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies malformed capture evidence as invalid input", async () => {
|
||||
const root = await fixture();
|
||||
const malformed = join(root, "malformed-evidence.json");
|
||||
await writeFile(malformed, "{}");
|
||||
|
||||
expect(await compareProcessEvidenceFiles(malformed, malformed)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
message:
|
||||
"Capture evidence is malformed. Create new capture evidence, then try again.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
parseProcessEnvironment,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../src/application/ProcessOwnership.js";
|
||||
|
||||
@@ -36,6 +37,12 @@ const host = (
|
||||
};
|
||||
|
||||
describe("owned process-group cleanup", () => {
|
||||
it("drops nameless Linux environment entries", () => {
|
||||
expect(
|
||||
parseProcessEnvironment("=ignored\0REA_PROCESS_RUN_ID=owned\0EMPTY=\0"),
|
||||
).toEqual({ REA_PROCESS_RUN_ID: "owned", EMPTY: "" });
|
||||
});
|
||||
|
||||
it("signals only a group whose every member carries the run token", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { chmod, mkdtemp, stat } from "node:fs/promises";
|
||||
import { chmod, mkdtemp, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readProjectPermissionStore,
|
||||
revokeProjectPermissionGrant,
|
||||
writeProjectPermissionStore,
|
||||
} from "../src/application/ProjectPermissionStore.js";
|
||||
|
||||
@@ -60,4 +61,54 @@ describe("project permission store", () => {
|
||||
error: { reason: "invalid" },
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies malformed JSON as an invalid store", async () => {
|
||||
const project = await mkdtemp(join(tmpdir(), "rea-policy-invalid-"));
|
||||
const path = join(project, "permissions.json");
|
||||
await writeFile(path, "{", { mode: 0o600 });
|
||||
|
||||
expect(await readProjectPermissionStore(path, project)).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "invalid" },
|
||||
});
|
||||
});
|
||||
|
||||
it("serializes concurrent grant revocations without losing an update", async () => {
|
||||
const project = await mkdtemp(join(tmpdir(), "rea-policy-revoke-"));
|
||||
const path = join(project, ".rea", "permissions.json");
|
||||
const grant = (grantId: string) => ({
|
||||
grant_id: grantId,
|
||||
capability: "evidence_read" as const,
|
||||
roots: [project],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
lifetime: "project" as const,
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await writeProjectPermissionStore(path, project, [
|
||||
grant("grant-one"),
|
||||
grant("grant-two"),
|
||||
])
|
||||
).ok,
|
||||
).toBe(true);
|
||||
|
||||
const revoked = await Promise.all([
|
||||
revokeProjectPermissionGrant(path, project, "grant-one"),
|
||||
revokeProjectPermissionGrant(path, project, "grant-two"),
|
||||
]);
|
||||
|
||||
expect(revoked).toEqual([
|
||||
{ ok: true, value: true },
|
||||
{ ok: true, value: true },
|
||||
]);
|
||||
expect(await readProjectPermissionStore(path, project)).toMatchObject({
|
||||
ok: true,
|
||||
value: { grants: [] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -161,6 +161,62 @@ const artifactComparison = (
|
||||
);
|
||||
|
||||
describe("reconstruction verification", () => {
|
||||
it("accepts interaction and shim behavioral claim dimensions", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
const result = {
|
||||
status: "changed",
|
||||
terminal: "unchanged",
|
||||
interaction: "changed",
|
||||
exit: "unchanged",
|
||||
filesystem: "unchanged",
|
||||
protocol: "unchanged",
|
||||
process: "unchanged",
|
||||
shim: "unchanged",
|
||||
first_divergence: {
|
||||
status: "found",
|
||||
dimension: "interaction",
|
||||
index: 0,
|
||||
left_at_ms: 0,
|
||||
right_at_ms: 0,
|
||||
left: "left",
|
||||
right: "right",
|
||||
},
|
||||
limitations: [],
|
||||
} satisfies JsonValue;
|
||||
const comparison = processComparison(left, right, result);
|
||||
|
||||
expect(
|
||||
verifyReconstruction(
|
||||
{
|
||||
schema_version: 1,
|
||||
name: "Interaction reconstruction",
|
||||
claims: [
|
||||
{
|
||||
kind: "behavioral",
|
||||
claim_id: "interaction",
|
||||
title: "Interaction remains equivalent",
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
dimension: "interaction",
|
||||
},
|
||||
{
|
||||
kind: "behavioral",
|
||||
claim_id: "shim",
|
||||
title: "Shim remains equivalent",
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
dimension: "shim",
|
||||
},
|
||||
],
|
||||
},
|
||||
createEvidenceBundle([comparison, right, left]),
|
||||
0,
|
||||
100,
|
||||
),
|
||||
).toMatchObject({
|
||||
summary: { total: 2, passed: 1, failed: 1, unknown: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("passes a complete authoritative claim with two-sided citations", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
|
||||
@@ -34,12 +34,16 @@ const fixture = async (parent: string, name: string): Promise<string> => {
|
||||
return root;
|
||||
};
|
||||
|
||||
const importTree = (root: string, approvedRoot: string, signal?: AbortSignal) =>
|
||||
const importTree = (
|
||||
root: string,
|
||||
approvedRoot: string | readonly string[],
|
||||
signal?: AbortSignal,
|
||||
) =>
|
||||
importReferenceSource({
|
||||
root,
|
||||
caller: "reference-import-test",
|
||||
policy: {
|
||||
roots: [approvedRoot],
|
||||
roots: typeof approvedRoot === "string" ? [approvedRoot] : approvedRoot,
|
||||
secretPatterns: [".env", ".env.*"],
|
||||
...limits,
|
||||
},
|
||||
@@ -153,6 +157,20 @@ describe("reference source import", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("uses a valid reference root when another configured root is missing", async () => {
|
||||
const parent = await mkdtemp(join(tmpdir(), "rea-reference-roots-"));
|
||||
try {
|
||||
const root = await fixture(parent, "tree");
|
||||
const imported = await importTree(root, [
|
||||
join(parent, "missing"),
|
||||
parent,
|
||||
]);
|
||||
expect(imported).toMatchObject({ ok: true });
|
||||
} finally {
|
||||
await rm(parent, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("records bounded local Git state without invoking Git", async () => {
|
||||
const parent = await mkdtemp(join(tmpdir(), "rea-reference-git-"));
|
||||
try {
|
||||
|
||||
@@ -78,6 +78,38 @@ const update = (
|
||||
});
|
||||
|
||||
describe("residual unknown registry", () => {
|
||||
it("returns detached unknowns and evidence bundles from every read surface", () => {
|
||||
const store = ledger();
|
||||
expect(store.record(evidence("detached-record")).ok).toBe(true);
|
||||
const created = store.recordUnknown(
|
||||
input("Does detached state remain intact?"),
|
||||
mutation("detached-unknown"),
|
||||
);
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
|
||||
Reflect.set(created.value, "status", "resolved");
|
||||
const listed = store.listUnknowns();
|
||||
expect(listed[0]?.status).toBe("open");
|
||||
if (listed[0] !== undefined) Reflect.set(listed[0], "status", "resolved");
|
||||
const verified = store.verifyUnknownResolution(created.value.unknown_id);
|
||||
expect(verified).toMatchObject({ ok: true, value: { valid: false } });
|
||||
if (verified.ok) Reflect.set(verified.value.unknown, "status", "resolved");
|
||||
|
||||
const exported = store.export();
|
||||
const exportedRecord = exported.records.find(
|
||||
({ operation }) => operation === "detached-record",
|
||||
);
|
||||
if (exportedRecord !== undefined)
|
||||
Reflect.set(exportedRecord, "operation", "forged");
|
||||
expect(store.export().records.map(({ operation }) => operation)).toContain(
|
||||
"detached-record",
|
||||
);
|
||||
expect(
|
||||
store.verifyUnknownResolution(created.value.unknown_id),
|
||||
).toMatchObject({ ok: true, value: { valid: false } });
|
||||
});
|
||||
|
||||
it("requires approval, derives stable IDs, filters heads, and rejects duplicate creation", () => {
|
||||
expect(() =>
|
||||
recordUnknownInputSchema.parse({
|
||||
|
||||
@@ -56,4 +56,14 @@ describe("safe artifact output tree", () => {
|
||||
"visible before seal",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns detached cleanup reports", async () => {
|
||||
const parent = await mkdtemp(join(tmpdir(), "rea-safe-output-"));
|
||||
const tree = await SafeOutputTree.create(join(parent, "published"), LIMITS);
|
||||
const cleanup = await tree.rollback();
|
||||
(cleanup.residualPaths as string[]).push("/forged/path");
|
||||
|
||||
expect(tree.cleanup.residualPaths).toEqual([]);
|
||||
expect((await tree.rollback()).residualPaths).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,11 @@ import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
|
||||
import { probeProcessCaptureCapability } from "../src/application/ProcessHarness.js";
|
||||
import { observed as ok } from "./fixtures/analysisExecution.js";
|
||||
import { createServer } from "../src/server/createServer.js";
|
||||
import { evidenceBundleSchema } from "../src/domain/evidenceBundle.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
evidenceBundleSchema,
|
||||
} from "../src/domain/evidenceBundle.js";
|
||||
import { createEvidence } from "../src/domain/evidence.js";
|
||||
import { silentLogger } from "../src/logger.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
@@ -54,6 +58,10 @@ describe("target-free MCP lifecycle", () => {
|
||||
},
|
||||
});
|
||||
const mcp = new Client({ name: "session-test", version: "1.0.0" });
|
||||
let resourceListChanges = 0;
|
||||
mcp.setNotificationHandler("notifications/resources/list_changed", () => {
|
||||
resourceListChanges += 1;
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(mcp, server);
|
||||
@@ -116,6 +124,31 @@ describe("target-free MCP lifecycle", () => {
|
||||
}),
|
||||
).result,
|
||||
).toEqual({ imported: 0, total: 1 });
|
||||
const externalEvidencePath = join(directory, "external-evidence.json");
|
||||
await writeFile(
|
||||
externalEvidencePath,
|
||||
JSON.stringify(
|
||||
createEvidenceBundle([
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "external_observation", parameters: {}, result: true },
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
let changesBeforeMutation = resourceListChanges;
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path: externalEvidencePath },
|
||||
}),
|
||||
).result,
|
||||
).toEqual({ imported: 1, total: 2 });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(resourceListChanges).toBe(changesBeforeMutation + 1);
|
||||
changesBeforeMutation = resourceListChanges;
|
||||
const recordedUnknown = z
|
||||
.object({
|
||||
result: z.object({
|
||||
@@ -142,6 +175,8 @@ describe("target-free MCP lifecycle", () => {
|
||||
),
|
||||
).result;
|
||||
expect(recordedUnknown.revision).toBe(1);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(resourceListChanges).toBe(changesBeforeMutation + 1);
|
||||
expect(
|
||||
z
|
||||
.object({ result: z.array(z.unknown()) })
|
||||
@@ -174,6 +209,8 @@ describe("target-free MCP lifecycle", () => {
|
||||
},
|
||||
});
|
||||
expect(resolved.isError).not.toBe(true);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(resourceListChanges).toBe(changesBeforeMutation + 2);
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
|
||||
@@ -88,7 +88,7 @@ const processComparison = (
|
||||
const mapping = (
|
||||
runtime: Evidence,
|
||||
expected: "cochanged" | "static_only" | "runtime_only" | "both_unchanged",
|
||||
dimension: "terminal" | "exit" = "terminal",
|
||||
dimension: "terminal" | "interaction" | "exit" | "shim" = "terminal",
|
||||
) => ({
|
||||
static_comparisons: [staticComparison],
|
||||
runtime_comparisons: [runtime],
|
||||
@@ -115,6 +115,16 @@ const mapping = (
|
||||
});
|
||||
|
||||
describe("static/runtime correlation", () => {
|
||||
it("accepts interaction and shim runtime dimensions", () => {
|
||||
const runtime = processComparison("unchanged");
|
||||
expect(
|
||||
correlateStaticAndRuntime(mapping(runtime, "static_only", "interaction")),
|
||||
).toMatchObject({ status: "correlated" });
|
||||
expect(
|
||||
correlateStaticAndRuntime(mapping(runtime, "static_only", "shim")),
|
||||
).toMatchObject({ status: "correlated" });
|
||||
});
|
||||
|
||||
it("keeps consistent cochange as a hypothesis with complete citations", () => {
|
||||
const runtime = processComparison("changed");
|
||||
const result = correlateStaticAndRuntime(mapping(runtime, "cochanged"));
|
||||
|
||||
@@ -39,6 +39,24 @@ describe("symbol analysis", () => {
|
||||
expect(discoverObjcProtocols(names)).toMatchObject({ count: 1 });
|
||||
});
|
||||
|
||||
it("excludes Objective-C ivars, metaclasses, properties, and protocols from classes", () => {
|
||||
const result = discoverObjcClasses(
|
||||
[
|
||||
{ address: "0x1", name: "_OBJC_IVAR_$_Fixture.value" },
|
||||
{ address: "0x2", name: "_OBJC_METACLASS_$_Fixture" },
|
||||
{ address: "0x3", name: "_OBJC_PROP_$_Fixture.value" },
|
||||
{ address: "0x4", name: "_OBJC_PROTOCOL_$_FixtureProtocol" },
|
||||
{ address: "0x5", name: "_OBJC_CLASS_$_Fixture" },
|
||||
],
|
||||
"",
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
count: 1,
|
||||
classes: [{ address: "0x5", name: "_OBJC_CLASS_$_Fixture" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("categorizes every Swift mangling family and deduplicates names", () => {
|
||||
const result = categorizeSwiftTypes([
|
||||
{ address: "1", name: "_TtCClass" },
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { UnknownRegistry } from "../src/application/UnknownRegistry.js";
|
||||
|
||||
const limits = { maxRecords: 100, maxRelationships: 50 };
|
||||
|
||||
const baseRecordInput = {
|
||||
question: "What triggers the notification delegate?",
|
||||
severity: "high" as const,
|
||||
domain: "notifications",
|
||||
required_authority: "shipped-artifact" as const,
|
||||
required_confidence: "observed" as const,
|
||||
required_environment: null,
|
||||
supporting_evidence_ids: [] as string[],
|
||||
contradicting_evidence_ids: [] as string[],
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
approved: true as const,
|
||||
};
|
||||
|
||||
describe("UnknownRegistry", () => {
|
||||
it("creates a registry entry with deterministic ID and revision 1", () => {
|
||||
const registry = new UnknownRegistry(limits);
|
||||
const result = registry.recordUnknown(
|
||||
baseRecordInput,
|
||||
"ev_a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
const unk = result.value;
|
||||
expect(unk.unknown_id).toMatch(/^unk_[a-f0-9]{64}$/u);
|
||||
expect(unk.revision).toBe(1);
|
||||
expect(unk.status).toBe("open");
|
||||
expect(unk.previous_revision_digest).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects duplicate creation with already-exists", () => {
|
||||
const registry = new UnknownRegistry(limits);
|
||||
const first = registry.recordUnknown(
|
||||
baseRecordInput,
|
||||
"ev_a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",
|
||||
);
|
||||
expect(first.ok).toBe(true);
|
||||
const second = registry.recordUnknown(
|
||||
baseRecordInput,
|
||||
"ev_b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2",
|
||||
);
|
||||
expect(second.ok).toBe(false);
|
||||
if (second.ok) return;
|
||||
expect(second.error.reason).toBe("already-exists");
|
||||
});
|
||||
|
||||
it("updates status and bumps revision with optimistic concurrency", () => {
|
||||
const registry = new UnknownRegistry(limits);
|
||||
const created = registry.recordUnknown(
|
||||
baseRecordInput,
|
||||
"ev_a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",
|
||||
);
|
||||
if (!created.ok) throw new Error("create failed");
|
||||
const updated = registry.updateUnknown(
|
||||
{
|
||||
unknown_id: created.value.unknown_id,
|
||||
expected_revision: 1,
|
||||
approved: true,
|
||||
status: "investigating",
|
||||
severity: "high",
|
||||
required_authority: null,
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
resolution: null,
|
||||
},
|
||||
"ev_b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2",
|
||||
);
|
||||
expect(updated.ok).toBe(true);
|
||||
if (!updated.ok) return;
|
||||
expect(updated.value.revision).toBe(2);
|
||||
expect(updated.value.status).toBe("investigating");
|
||||
expect(updated.value.previous_revision_digest).toBe(
|
||||
created.value.revision_digest,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects update with wrong expected revision", () => {
|
||||
const registry = new UnknownRegistry(limits);
|
||||
const created = registry.recordUnknown(
|
||||
baseRecordInput,
|
||||
"ev_a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",
|
||||
);
|
||||
if (!created.ok) throw new Error("create failed");
|
||||
const updated = registry.updateUnknown(
|
||||
{
|
||||
unknown_id: created.value.unknown_id,
|
||||
expected_revision: 99,
|
||||
approved: true,
|
||||
status: "investigating",
|
||||
severity: "high",
|
||||
required_authority: null,
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
resolution: null,
|
||||
},
|
||||
"ev_b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2",
|
||||
);
|
||||
expect(updated.ok).toBe(false);
|
||||
if (updated.ok) return;
|
||||
expect(updated.error.reason).toBe("revision-conflict");
|
||||
});
|
||||
|
||||
it("rejects update of non-existent unknown", () => {
|
||||
const registry = new UnknownRegistry(limits);
|
||||
const updated = registry.updateUnknown(
|
||||
{
|
||||
unknown_id: "unk_" + "0".repeat(64),
|
||||
expected_revision: 1,
|
||||
approved: true,
|
||||
status: "investigating",
|
||||
severity: "high",
|
||||
required_authority: null,
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
resolution: null,
|
||||
},
|
||||
"ev_b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2",
|
||||
);
|
||||
expect(updated.ok).toBe(false);
|
||||
if (updated.ok) return;
|
||||
expect(updated.error.reason).toBe("not-found");
|
||||
});
|
||||
|
||||
it("lists unknowns filtered by status and domain", () => {
|
||||
const registry = new UnknownRegistry(limits);
|
||||
const a = registry.recordUnknown(
|
||||
{ ...baseRecordInput, domain: "notifications" },
|
||||
"ev_a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",
|
||||
);
|
||||
const b = registry.recordUnknown(
|
||||
{ ...baseRecordInput, question: "How does IPC work?", domain: "ipc" },
|
||||
"ev_b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2",
|
||||
);
|
||||
expect(a.ok).toBe(true);
|
||||
expect(b.ok).toBe(true);
|
||||
|
||||
const allOpen = registry.listUnknowns({ status: "open" });
|
||||
expect(allOpen.ok).toBe(true);
|
||||
if (!allOpen.ok) return;
|
||||
expect(allOpen.value).toHaveLength(2);
|
||||
|
||||
const ipcOnly = registry.listUnknowns({ domain: "ipc" });
|
||||
expect(ipcOnly.ok).toBe(true);
|
||||
if (!ipcOnly.ok) return;
|
||||
expect(ipcOnly.value).toHaveLength(1);
|
||||
expect(ipcOnly.value[0]?.domain).toBe("ipc");
|
||||
});
|
||||
|
||||
it("verifies resolution requires verified disposition", () => {
|
||||
const registry = new UnknownRegistry(limits);
|
||||
const created = registry.recordUnknown(
|
||||
baseRecordInput,
|
||||
"ev_a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",
|
||||
);
|
||||
if (!created.ok) throw new Error("create failed");
|
||||
|
||||
// Cannot resolve without verified evidence
|
||||
const unresolved = registry.updateUnknown(
|
||||
{
|
||||
unknown_id: created.value.unknown_id,
|
||||
expected_revision: 1,
|
||||
approved: true,
|
||||
status: "resolved",
|
||||
severity: "high",
|
||||
required_authority: null,
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
resolution: {
|
||||
disposition: "verified",
|
||||
rationale: "Test resolved",
|
||||
evidence_ids: [],
|
||||
},
|
||||
},
|
||||
"ev_b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2",
|
||||
);
|
||||
// The domain layer should reject resolving with verified disposition
|
||||
// and no evidence ids
|
||||
expect(unresolved.ok).toBe(false);
|
||||
});
|
||||
|
||||
it("enforces record limits", () => {
|
||||
const smallLimits = { maxRecords: 2, maxRelationships: 50 };
|
||||
const registry = new UnknownRegistry(smallLimits);
|
||||
expect(
|
||||
registry.recordUnknown(
|
||||
baseRecordInput,
|
||||
"ev_a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1",
|
||||
).ok,
|
||||
).toBe(true);
|
||||
expect(
|
||||
registry.recordUnknown(
|
||||
{ ...baseRecordInput, question: "Second?" },
|
||||
"ev_b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2",
|
||||
).ok,
|
||||
).toBe(true);
|
||||
const third = registry.recordUnknown(
|
||||
{ ...baseRecordInput, question: "Third?" },
|
||||
"ev_c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3",
|
||||
);
|
||||
expect(third.ok).toBe(false);
|
||||
if (third.ok) return;
|
||||
expect(third.error.reason).toBe("limit");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user