Merge origin/main for artifact admission and evidence fixes
This commit is contained in:
@@ -54,6 +54,15 @@ export interface AnalysisExecution {
|
||||
readonly subject: EvidenceSubjectTarget | null;
|
||||
}
|
||||
|
||||
interface CreateAnalysisExecutionOptions {
|
||||
readonly rawResult?: unknown;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations?: readonly string[];
|
||||
readonly relationshipCoverage?: RelationshipCoverage;
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
readonly subject?: EvidenceSubjectTarget;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a validated atomic provider observation at an adapter boundary.
|
||||
*
|
||||
@@ -61,38 +70,43 @@ export interface AnalysisExecution {
|
||||
* `result`. Omitting it records `null` rather than a second complete copy of
|
||||
* the normalized result in every Evidence record and tool response.
|
||||
*/
|
||||
export const createAnalysisExecution = (
|
||||
export function createAnalysisExecution<Subject extends EvidenceSubjectTarget>(
|
||||
result: unknown,
|
||||
provider: ProviderIdentity,
|
||||
options: {
|
||||
readonly rawResult?: unknown;
|
||||
readonly analysisProfile?: AnalysisProfileCommitment;
|
||||
readonly limitations?: readonly string[];
|
||||
readonly relationshipCoverage?: RelationshipCoverage;
|
||||
readonly locations?: readonly EvidenceLocation[];
|
||||
readonly subject?: EvidenceSubjectTarget;
|
||||
} = {},
|
||||
): AnalysisExecution => ({
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult:
|
||||
options.rawResult === undefined
|
||||
? null
|
||||
: jsonValueSchema.parse(options.rawResult),
|
||||
provider,
|
||||
...(options.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: structuredClone(options.analysisProfile) }),
|
||||
limitations: [...(options.limitations ?? [])],
|
||||
...(options.relationshipCoverage === undefined
|
||||
? {}
|
||||
: {
|
||||
relationshipCoverage: relationshipCoverageSchema.parse(
|
||||
options.relationshipCoverage,
|
||||
),
|
||||
}),
|
||||
locations: [...(options.locations ?? [])],
|
||||
subject: options.subject ?? null,
|
||||
});
|
||||
options: CreateAnalysisExecutionOptions & { readonly subject: Subject },
|
||||
): Omit<AnalysisExecution, "subject"> & { readonly subject: Subject };
|
||||
export function createAnalysisExecution(
|
||||
result: unknown,
|
||||
provider: ProviderIdentity,
|
||||
options?: CreateAnalysisExecutionOptions,
|
||||
): AnalysisExecution;
|
||||
export function createAnalysisExecution(
|
||||
result: unknown,
|
||||
provider: ProviderIdentity,
|
||||
options: CreateAnalysisExecutionOptions = {},
|
||||
): AnalysisExecution {
|
||||
return {
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult:
|
||||
options.rawResult === undefined
|
||||
? null
|
||||
: jsonValueSchema.parse(options.rawResult),
|
||||
provider,
|
||||
...(options.analysisProfile === undefined
|
||||
? {}
|
||||
: { analysisProfile: structuredClone(options.analysisProfile) }),
|
||||
limitations: [...(options.limitations ?? [])],
|
||||
...(options.relationshipCoverage === undefined
|
||||
? {}
|
||||
: {
|
||||
relationshipCoverage: relationshipCoverageSchema.parse(
|
||||
options.relationshipCoverage,
|
||||
),
|
||||
}),
|
||||
locations: [...(options.locations ?? [])],
|
||||
subject: options.subject ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Provider-neutral application capability for one analysis operation. */
|
||||
export interface AnalysisOperationPort {
|
||||
|
||||
@@ -481,7 +481,7 @@ const workflowAvailabilityFor = ({
|
||||
remediation: "Run process capture on a supported Linux or macOS host.",
|
||||
};
|
||||
if (kind === "application") return { reason: "available", remediation: null };
|
||||
if (kind === "flutter-provider")
|
||||
if (kind === "pcap-provider" || kind === "flutter-provider")
|
||||
return { reason: "available", remediation: null };
|
||||
const electron = electronProviderAvailability(name, kind, policy);
|
||||
if (electron !== null) return electron;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
clientServerForcedEnabled,
|
||||
clientServerListedDisabled,
|
||||
effectiveClientServer,
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { access } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
@@ -74,24 +75,48 @@ const registrationSchema = z
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
/** Inspect supported client registrations without reading their environment. */
|
||||
interface ClientRegistrationReadOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly resources?: ArtifactResourceScope;
|
||||
}
|
||||
|
||||
/** Registration facts shared by diagnostics and update maintenance. */
|
||||
export interface ClientRegistrationInspection {
|
||||
readonly status: ClientRegistrationStatus;
|
||||
readonly activation: "enabled" | "disabled" | "unknown";
|
||||
}
|
||||
|
||||
/** Project diagnostics from the same inspection used to select maintenance. */
|
||||
export const readClientRegistrationStatuses = async (
|
||||
home: string,
|
||||
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
|
||||
options: {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly resources?: ArtifactResourceScope;
|
||||
} = {},
|
||||
): Promise<readonly ClientRegistrationStatus[]> => {
|
||||
const statuses: ClientRegistrationStatus[] = [];
|
||||
options: ClientRegistrationReadOptions = {},
|
||||
): Promise<readonly ClientRegistrationStatus[]> =>
|
||||
(
|
||||
await readClientRegistrationInspections(home, currentCommandPath, options)
|
||||
).map(({ status }) => status);
|
||||
|
||||
/** Parse effective registrations and their client-specific activation once. */
|
||||
export const readClientRegistrationInspections = async (
|
||||
home: string,
|
||||
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
|
||||
options: ClientRegistrationReadOptions = {},
|
||||
): Promise<readonly ClientRegistrationInspection[]> => {
|
||||
const inspections: ClientRegistrationInspection[] = [];
|
||||
const record = (
|
||||
status: ClientRegistrationStatus,
|
||||
activation: ClientRegistrationInspection["activation"] = "unknown",
|
||||
): void => {
|
||||
inspections.push({ status, activation });
|
||||
};
|
||||
for (const client of supportedClients(
|
||||
home,
|
||||
options.platform,
|
||||
options.environment,
|
||||
)) {
|
||||
if (client.configPathError !== undefined) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -104,7 +129,7 @@ export const readClientRegistrationStatuses = async (
|
||||
const manualRemediation = manualRegistrationRemediation(client.name);
|
||||
if (client.format === "unsupported") {
|
||||
if (manualRemediation !== undefined)
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.markerPath ?? client.configPath,
|
||||
command: [],
|
||||
@@ -119,7 +144,7 @@ export const readClientRegistrationStatuses = async (
|
||||
options.resources,
|
||||
);
|
||||
if (!files.ok) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -130,9 +155,7 @@ export const readClientRegistrationStatuses = async (
|
||||
}
|
||||
const parsed = effectiveClientConfiguration(files.value);
|
||||
if (parsed === undefined) {
|
||||
statuses.push(
|
||||
unavailableStatus(client.name, client.configPath, "missing"),
|
||||
);
|
||||
record(unavailableStatus(client.name, client.configPath, "missing"));
|
||||
continue;
|
||||
}
|
||||
const policy = await readClientPolicyBlock(
|
||||
@@ -142,7 +165,7 @@ export const readClientRegistrationStatuses = async (
|
||||
options.resources,
|
||||
);
|
||||
if (!policy.ok) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -159,7 +182,7 @@ export const readClientRegistrationStatuses = async (
|
||||
? dshDocument(parsed.document).editabilityError
|
||||
: undefined;
|
||||
if (editabilityError !== undefined) {
|
||||
statuses.push({
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
@@ -168,9 +191,7 @@ export const readClientRegistrationStatuses = async (
|
||||
});
|
||||
continue;
|
||||
}
|
||||
statuses.push(
|
||||
unavailableStatus(client.name, client.configPath, "missing"),
|
||||
);
|
||||
record(unavailableStatus(client.name, client.configPath, "missing"));
|
||||
continue;
|
||||
}
|
||||
const registration = parseRegistration(raw, client);
|
||||
@@ -178,21 +199,18 @@ export const readClientRegistrationStatuses = async (
|
||||
registration.command,
|
||||
...registration.args,
|
||||
];
|
||||
statuses.push(
|
||||
const activation = registrationActivation(registration, client, parsed);
|
||||
record(
|
||||
configuredStatus(
|
||||
client.name,
|
||||
client.configPath,
|
||||
command,
|
||||
registrationAligned(
|
||||
registration,
|
||||
client,
|
||||
currentCommandPath,
|
||||
options.platform ?? process.platform,
|
||||
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey),
|
||||
) &&
|
||||
!clientServerListedDisabled(
|
||||
parsed,
|
||||
PRODUCT_IDENTITY.mcpServerKey,
|
||||
activation === "enabled" &&
|
||||
registrationAligned(
|
||||
registration,
|
||||
client,
|
||||
currentCommandPath,
|
||||
options.platform ?? process.platform,
|
||||
) &&
|
||||
(parsed.dialect !== "dsh" || dshDocument(parsed.document).ready) &&
|
||||
policyBlock === undefined
|
||||
@@ -200,9 +218,10 @@ export const readClientRegistrationStatuses = async (
|
||||
: "stale",
|
||||
policyBlock,
|
||||
),
|
||||
activation,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
statuses.push(
|
||||
record(
|
||||
unavailableStatus(
|
||||
client.name,
|
||||
client.configPath,
|
||||
@@ -211,26 +230,31 @@ export const readClientRegistrationStatuses = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
return statuses.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.client, right.client),
|
||||
return inspections.sort((left, right) =>
|
||||
compareUnicodeCodePoints(left.status.client, right.status.client),
|
||||
);
|
||||
};
|
||||
|
||||
const registrationActivation = (
|
||||
registration: z.output<typeof registrationSchema>,
|
||||
client: SetupClient,
|
||||
parsed: ClientConfigurationDocument,
|
||||
): "enabled" | "disabled" =>
|
||||
(client.format !== "grok" && registration.disabled === true) ||
|
||||
(registration.enabled === false &&
|
||||
!clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) ||
|
||||
(client.format === "zcode" && registration.enable === false) ||
|
||||
clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
|
||||
? "disabled"
|
||||
: "enabled";
|
||||
|
||||
const registrationAligned = (
|
||||
registration: z.output<typeof registrationSchema>,
|
||||
client: SetupClient,
|
||||
currentCommandPath: string,
|
||||
platform: NodeJS.Platform,
|
||||
forcedEnabled = false,
|
||||
): boolean => {
|
||||
const command = [registration.command, ...registration.args];
|
||||
if (
|
||||
(client.format !== "grok" && registration.disabled === true) ||
|
||||
(registration.enabled === false && !forcedEnabled) ||
|
||||
// ZCode's native flag is `enable`; other dialects leave that field opaque.
|
||||
(client.format === "zcode" && registration.enable === false)
|
||||
)
|
||||
return false;
|
||||
if (!isOwnedClientRegistrationCommand(command, currentCommandPath))
|
||||
return false;
|
||||
if (
|
||||
|
||||
@@ -1,19 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { readClientRegistrationStatuses } from "./ClientRegistrationStatus.js";
|
||||
import {
|
||||
clientServerForcedEnabled,
|
||||
clientServerListedDisabled,
|
||||
effectiveClientServer,
|
||||
parseClientConfiguration,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { supportedClients } from "./SupportedClients.js";
|
||||
import { readClientRegistrationInspections } from "./ClientRegistrationStatus.js";
|
||||
import { existingSkillDestinations } from "./SetupSkill.js";
|
||||
import type { SetupAction } from "./SetupTypes.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
|
||||
/** Existing REA integrations selected for maintenance, without discovering new targets. */
|
||||
@@ -61,41 +52,23 @@ export const existingMaintenanceScope = async (
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<MaintenanceScope> => {
|
||||
const registrations = await readClientRegistrationStatuses(home, entryPoint, {
|
||||
environment,
|
||||
...(resources === undefined ? {} : { resources }),
|
||||
});
|
||||
const supported = supportedClients(home, process.platform, environment);
|
||||
const registrations = await readClientRegistrationInspections(
|
||||
home,
|
||||
entryPoint,
|
||||
{
|
||||
environment,
|
||||
...(resources === undefined ? {} : { resources }),
|
||||
},
|
||||
);
|
||||
const clients: string[] = [];
|
||||
for (const registration of registrations) {
|
||||
for (const { status: registration, activation } of registrations) {
|
||||
if (
|
||||
activation !== "enabled" ||
|
||||
(registration.state !== "aligned" && registration.state !== "stale") ||
|
||||
!isOwnedClientRegistrationCommand(registration.command, entryPoint)
|
||||
)
|
||||
continue;
|
||||
const client = supported.find(({ name }) => name === registration.client);
|
||||
if (client === undefined) continue;
|
||||
const parsed = parseClientConfiguration(
|
||||
await readRegularFileText(
|
||||
client.configPath,
|
||||
resources === undefined ? {} : { resources },
|
||||
),
|
||||
client.format,
|
||||
);
|
||||
const enabled = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
})
|
||||
.parse(effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey));
|
||||
// Root disable lists override enabled entries and OMP's force-on allowlist.
|
||||
if (
|
||||
(enabled.enabled !== false ||
|
||||
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey)) &&
|
||||
enabled.disabled !== true &&
|
||||
!clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
|
||||
)
|
||||
clients.push(client.name);
|
||||
clients.push(registration.client);
|
||||
}
|
||||
const skillDestinations = await existingSkillDestinations(
|
||||
home,
|
||||
|
||||
@@ -4,13 +4,19 @@ import type {
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { InspectEvmInterfaceInput } from "../../domain/evm/evmInterface.js";
|
||||
import type { EvidenceSubjectTarget } from "../../domain/evidence.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Successful EVM interface recovery must identify the selected local file. */
|
||||
export type EvmInterfaceExecution = Omit<AnalysisExecution, "subject"> & {
|
||||
readonly subject: EvidenceSubjectTarget & { readonly format: "file" };
|
||||
};
|
||||
|
||||
/** Replaceable offline interface-recovery engine, independent of wallets and chain clients. */
|
||||
export interface EvmInterfacePort {
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectEvmInterfaceInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
): Promise<Result<EvmInterfaceExecution, AnalysisError>>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { EvmInterfaceService } from "./EvmInterfaceService.js";
|
||||
import type { EvmInterfaceExecution } from "./EvmInterfacePort.js";
|
||||
import {
|
||||
evmInterfaceExecution,
|
||||
evmInterfaceFixture,
|
||||
@@ -43,7 +44,8 @@ it.each(["carrier", "encoding", "digest", "no-subject"])(
|
||||
},
|
||||
};
|
||||
const service = new EvmInterfaceService({
|
||||
inspect: () => Promise.resolve(ok(execution)),
|
||||
inspect: () =>
|
||||
Promise.resolve(ok(execution as unknown as EvmInterfaceExecution)),
|
||||
});
|
||||
expect(
|
||||
await service.inspect({
|
||||
|
||||
@@ -67,6 +67,7 @@ export class EvmInterfaceService {
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.data.path ||
|
||||
report.data.artifact.encoding !== input.data.encoding ||
|
||||
execution.subject?.format !== "file" ||
|
||||
execution.subject?.path !== input.data.path ||
|
||||
execution.subject.sha256 !== report.data.artifact.sha256
|
||||
)
|
||||
|
||||
@@ -78,6 +78,51 @@ const update = (
|
||||
});
|
||||
|
||||
describe("residual unknown registry reads and identity", () => {
|
||||
it("seals mutation Evidence without freezing caller-owned inputs", () => {
|
||||
const store = ledger();
|
||||
const recordMutation = mutation("mutable-record-mutation");
|
||||
const recorded = store.recordUnknown(
|
||||
input("Does record mutation evidence stay stable?"),
|
||||
recordMutation,
|
||||
);
|
||||
if (!recorded.ok) throw recorded.error;
|
||||
|
||||
const updateMutation = mutation("mutable-update-mutation");
|
||||
const updated = store.updateUnknown(update(recorded.value), updateMutation);
|
||||
if (!updated.ok) throw updated.error;
|
||||
const atomicEvidence = evidence("mutable-atomic-evidence");
|
||||
const atomicMutation = mutation("mutable-atomic-mutation");
|
||||
const atomicallyRecorded = store.recordWithUnknown(
|
||||
atomicEvidence,
|
||||
input("Does atomic evidence stay stable?"),
|
||||
atomicMutation,
|
||||
);
|
||||
if (!atomicallyRecorded.ok) throw atomicallyRecorded.error;
|
||||
|
||||
for (const callerEvidence of [
|
||||
recordMutation,
|
||||
updateMutation,
|
||||
atomicEvidence,
|
||||
atomicMutation,
|
||||
]) {
|
||||
expect(Object.isFrozen(callerEvidence)).toBe(false);
|
||||
const retained = store.forAnalysis(callerEvidence.evidence_id);
|
||||
if (retained === undefined) throw new Error("Missing retained Evidence");
|
||||
const originalResult = structuredClone(retained.normalized_result);
|
||||
expect(Object.isFrozen(retained)).toBe(true);
|
||||
Reflect.set(callerEvidence, "operation", "caller mutation");
|
||||
expect(
|
||||
Reflect.set(
|
||||
callerEvidence.normalized_result as object,
|
||||
"label",
|
||||
"caller nested mutation",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(retained.operation).not.toBe("caller mutation");
|
||||
expect(retained.normalized_result).toEqual(originalResult);
|
||||
}
|
||||
});
|
||||
|
||||
it("merges record-only bundles without changing retained unknown history", () => {
|
||||
const store = ledger();
|
||||
const created = store.recordUnknown(
|
||||
|
||||
@@ -11,11 +11,7 @@ import {
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import {
|
||||
immutableEvidence,
|
||||
parseEvidence,
|
||||
type Evidence,
|
||||
} from "../../domain/evidence.js";
|
||||
import { immutableEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
createResidualUnknown,
|
||||
updateResidualUnknown,
|
||||
@@ -220,7 +216,7 @@ export class EvidenceLedger {
|
||||
): Result<ResidualUnknown, EvidenceIntegrityError | UnknownRegistryError> {
|
||||
let parsedMutation: Evidence;
|
||||
try {
|
||||
parsedMutation = parseEvidence(mutationEvidence);
|
||||
parsedMutation = immutableEvidence(mutationEvidence);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
|
||||
@@ -255,8 +251,8 @@ export class EvidenceLedger {
|
||||
let evidence: Evidence;
|
||||
let mutation: Evidence;
|
||||
try {
|
||||
evidence = parseEvidence(evidenceInput);
|
||||
mutation = parseEvidence(mutationInput);
|
||||
evidence = immutableEvidence(evidenceInput);
|
||||
mutation = immutableEvidence(mutationInput);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Atomic Evidence validation failed", {
|
||||
@@ -394,7 +390,7 @@ export class EvidenceLedger {
|
||||
): Result<ResidualUnknown, EvidenceIntegrityError | UnknownRegistryError> {
|
||||
let mutationEvidence: Evidence;
|
||||
try {
|
||||
mutationEvidence = parseEvidence(mutationEvidenceInput);
|
||||
mutationEvidence = immutableEvidence(mutationEvidenceInput);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Unknown mutation evidence is invalid", {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { TraceMap } from "@jridgewell/trace-mapping";
|
||||
|
||||
import { analyzeJavaScriptArtifactFiles } from "./JavaScriptArtifactAnalysis.js";
|
||||
|
||||
const HASH = "a".repeat(64);
|
||||
|
||||
it("retains batched TraceMap-resolved paths and null source positions", () => {
|
||||
const sourceMapText = JSON.stringify({
|
||||
version: 3,
|
||||
file: "main.js",
|
||||
sourceRoot: "../src/",
|
||||
sources: ["cafe\u0301.ts", null, "other.ts"],
|
||||
sourcesContent: ["export const value = 1;", null, "export {};"],
|
||||
names: [],
|
||||
mappings: "",
|
||||
});
|
||||
const analysis = analyzeJavaScriptArtifactFiles({
|
||||
files: [
|
||||
{
|
||||
path: "dist/main.js.map",
|
||||
container_sha256: HASH,
|
||||
sha256: HASH,
|
||||
bytes: Buffer.byteLength(sourceMapText),
|
||||
inventory_artifact_id: "artifact_test",
|
||||
kind: "source-map",
|
||||
unpacked: false,
|
||||
text: { included: true, value: sourceMapText },
|
||||
},
|
||||
],
|
||||
containers: [],
|
||||
text_bytes_read: Buffer.byteLength(sourceMapText),
|
||||
invalid_utf8_files: 0,
|
||||
});
|
||||
const originals = analysis.source_maps[0]?.sources;
|
||||
const original = originals?.[0];
|
||||
const producerPath = new TraceMap(
|
||||
{
|
||||
version: 3,
|
||||
file: "main.js",
|
||||
sourceRoot: "../src/",
|
||||
sources: ["cafe\u0301.ts", "", "other.ts"],
|
||||
names: [],
|
||||
mappings: "",
|
||||
},
|
||||
"file:///artifact/dist/main.js.map",
|
||||
).resolvedSources[0];
|
||||
|
||||
if (producerPath === undefined)
|
||||
throw new Error("TraceMap should resolve its single source declaration");
|
||||
expect(originals?.[1]?.reference).toBeNull();
|
||||
expect(originals?.[2]?.reference?.resolution).toEqual({
|
||||
kind: "artifact-relative",
|
||||
path: "src/other.ts",
|
||||
});
|
||||
expect(original?.reference).toMatchObject({
|
||||
source_name: "cafe\u0301.ts",
|
||||
source_root: "../src/",
|
||||
map_path: "dist/main.js.map",
|
||||
resolution: {
|
||||
kind: "artifact-relative",
|
||||
path: "src/cafe\u0301.ts",
|
||||
},
|
||||
});
|
||||
expect(original?.reference?.resolution).toEqual({
|
||||
kind: "artifact-relative",
|
||||
path: decodeURIComponent(
|
||||
new URL(producerPath).pathname.slice("/artifact/".length),
|
||||
),
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
|
||||
import { moduleKindForJavaScriptReference } from "./JavaScriptArtifactPathResolution.js";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
|
||||
import { resolveJavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
|
||||
import { resolveJavaScriptSourceMapReferences } from "../../domain/javascript/javascriptSourceMapPaths.js";
|
||||
import { analyzeParsedJavaScriptStaticSourceSteps } from "../../domain/javascript/javascriptStaticAnalysis.js";
|
||||
import {
|
||||
analyzeParsedJavaScriptSemanticsSteps,
|
||||
@@ -561,21 +561,27 @@ const collectSourceMapOriginals = (
|
||||
"Source map sourceRoot must be a string or null.",
|
||||
);
|
||||
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : null;
|
||||
for (const [index, raw] of names.entries()) {
|
||||
const sourceNames: (string | null)[] = [];
|
||||
for (const raw of names) {
|
||||
if (raw !== null && typeof raw !== "string")
|
||||
return invalidSourceMap(
|
||||
file,
|
||||
"Source map contains a non-string source name.",
|
||||
);
|
||||
sourceNames.push(raw);
|
||||
}
|
||||
const references = resolveJavaScriptSourceMapReferences(
|
||||
sourceNames,
|
||||
root,
|
||||
file.path,
|
||||
);
|
||||
for (const [index, reference] of references.entries()) {
|
||||
const rawContent = Array.isArray(contents) ? contents[index] : undefined;
|
||||
const content = typeof rawContent === "string" ? rawContent : null;
|
||||
sources.push({
|
||||
source_index: index,
|
||||
declaration_index: declarationIndex++,
|
||||
reference:
|
||||
typeof raw === "string"
|
||||
? resolveJavaScriptSourceMapReference(raw, root, file.path)
|
||||
: null,
|
||||
reference,
|
||||
content,
|
||||
content_sha256: content === null ? null : sha256(content),
|
||||
});
|
||||
|
||||
@@ -22,6 +22,26 @@ const exampleMethod = () => {
|
||||
};
|
||||
|
||||
describe("managed decompiler reconstruction import", () => {
|
||||
it("reports UTF-8 byte totals while preserving UTF-16 text lengths", () => {
|
||||
const text = 'return "é"; // 😀';
|
||||
const method = exampleMethod();
|
||||
const result = importManagedReconstructionEvidence({
|
||||
...MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
|
||||
methods: [
|
||||
{
|
||||
...method,
|
||||
reconstruction: { ...method.reconstruction, text },
|
||||
},
|
||||
],
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
summary: { total_text_bytes: 20 },
|
||||
methods: [{ reconstruction: { text, text_length: 17 } }],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects reconstruction text hash drift", () => {
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
ProviderAvailability,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { PcapRequest } from "../../domain/pcap/pcapAnalysis.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/**
|
||||
* Packet-capture analysis boundary over caller-supplied tshark/capinfos.
|
||||
* Implementation details belong to the provider adapter.
|
||||
*/
|
||||
export interface PcapAnalysisPort {
|
||||
/** Probe both tools without reading any capture file. */
|
||||
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
|
||||
/** Retry cleanup of retained owned commands and capture snapshots. */
|
||||
close(): Promise<void>;
|
||||
execute(
|
||||
request: PcapRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { PcapAnalysisPort } from "./PcapAnalysisPort.js";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import {
|
||||
pcapRequestSchema,
|
||||
type PcapOperation,
|
||||
} from "../../domain/pcap/pcapAnalysis.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import { createPcapEvidence } from "../../domain/pcap/pcapEvidence.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
/** Shared CLI/MCP admission, execution, and Evidence composition for pcap. */
|
||||
export class PcapAnalysisService {
|
||||
constructor(readonly provider: PcapAnalysisPort) {}
|
||||
|
||||
/** Run one caller-selected pcap request and retain capture identity inline. */
|
||||
async execute(
|
||||
operation: PcapOperation,
|
||||
input: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const request = pcapRequestSchema.safeParse({ operation, input });
|
||||
if (!request.success)
|
||||
return err(new AnalysisInputError(operation, { cause: request.error }));
|
||||
const executed = await this.provider.execute(request.data, options);
|
||||
if (!executed.ok) return executed;
|
||||
const execution = executed.value;
|
||||
return ok(createPcapEvidence(request.data, execution));
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,14 @@ import type {
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { InspectWasmArtifactInput } from "../../domain/wasm/wasmArtifact.js";
|
||||
import type { EvidenceSubjectTarget } from "../../domain/evidence.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Successful WASM inspection must identify the selected local file. */
|
||||
export type WasmArtifactExecution = Omit<AnalysisExecution, "subject"> & {
|
||||
readonly subject: EvidenceSubjectTarget & { readonly format: "file" };
|
||||
};
|
||||
|
||||
/** Replaceable offline WASM inspection engine, independent of target execution and network clients. */
|
||||
export interface WasmArtifactPort {
|
||||
/** Retry removal of retained workspaces; failures preserve ownership for another attempt. */
|
||||
@@ -13,5 +19,5 @@ export interface WasmArtifactPort {
|
||||
inspect(
|
||||
input: InspectWasmArtifactInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
): Promise<Result<WasmArtifactExecution, AnalysisError>>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user