feat(process): record provider and verifier run lineage
This commit is contained in:
@@ -13,6 +13,7 @@ import type { EvidenceSubjectTarget } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { ProgressReporter } from "./ProgressReporter.js";
|
||||
import type { ProviderRejectionCode } from "../contracts/providerSelection.js";
|
||||
import type { ProcessLineageObservation } from "../process/ProcessOwnership.js";
|
||||
|
||||
export interface ExecutionOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
@@ -74,14 +75,28 @@ export interface AnalysisOperationPort {
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
|
||||
/** Retained provider-process observation attributed to its producing provider. */
|
||||
export interface ProviderRuntimeLineageSnapshot {
|
||||
readonly provider: ProviderIdentity;
|
||||
readonly observation: ProcessLineageObservation;
|
||||
}
|
||||
|
||||
/** Provider session bound to exactly one parsed artifact. */
|
||||
export interface AnalysisClient extends AnalysisOperationPort {
|
||||
/** Retained token-verified process snapshots for dynamic providers this client started. */
|
||||
runtimeLineageSnapshots?(): readonly ProviderRuntimeLineageSnapshot[];
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Per-client identity allocated before any provider side effect starts. */
|
||||
export interface AnalysisClientContext {
|
||||
readonly runId: string;
|
||||
}
|
||||
|
||||
export type AnalysisClientFactory = (
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
context?: AnalysisClientContext,
|
||||
) => AnalysisClient;
|
||||
|
||||
export interface ProviderIdentity {
|
||||
@@ -144,6 +159,7 @@ export interface AnalysisProvider {
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
context?: AnalysisClientContext,
|
||||
): AnalysisClient;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
analysisProfilesEqual,
|
||||
@@ -58,6 +60,7 @@ export class BinarySession
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
readonly route: SessionProviderRoute;
|
||||
readonly runId: string;
|
||||
}
|
||||
| undefined;
|
||||
#transition: Promise<void> = Promise.resolve();
|
||||
@@ -184,7 +187,8 @@ export class BinarySession
|
||||
const previous = this.#active;
|
||||
this.#active = undefined;
|
||||
await previous?.client.close();
|
||||
const client = route.createClient(target);
|
||||
const runId = randomUUID();
|
||||
const client = route.createClient(target, { runId });
|
||||
const started = await client.execute("health", {}, options);
|
||||
if (!started.ok) {
|
||||
await client.close();
|
||||
@@ -202,6 +206,7 @@ export class BinarySession
|
||||
profile,
|
||||
compatibility: structuredClone(compatibility),
|
||||
route,
|
||||
runId,
|
||||
};
|
||||
this.#clearRuntimeAvailability();
|
||||
if (profile === null) this.clearSnapshot();
|
||||
@@ -240,6 +245,9 @@ export class BinarySession
|
||||
route: this.#currentRoute(),
|
||||
router: this.#providerRouter,
|
||||
runtimeAvailability: this.#runtimeAvailability,
|
||||
runId: this.#active?.runId,
|
||||
runtimeLineageSnapshots:
|
||||
this.#active?.client.runtimeLineageSnapshots?.() ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -396,11 +404,13 @@ export class BinarySession
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
readonly route: SessionProviderRoute;
|
||||
readonly runId: string;
|
||||
}
|
||||
| undefined,
|
||||
): Promise<void> {
|
||||
if (previous === undefined) return;
|
||||
const client = previous.route.createClient(previous.target);
|
||||
const runId = randomUUID();
|
||||
const client = previous.route.createClient(previous.target, { runId });
|
||||
const started = await client.execute("health", {});
|
||||
if (started.ok)
|
||||
this.#active = {
|
||||
@@ -409,6 +419,7 @@ export class BinarySession
|
||||
profile: previous.profile,
|
||||
compatibility: previous.compatibility,
|
||||
route: previous.route,
|
||||
runId,
|
||||
};
|
||||
else await client.close();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { CapabilityDescriptor } from "./AnalysisProvider.js";
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderRuntimeLineageSnapshot,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type {
|
||||
SessionProviderRoute,
|
||||
SessionProviderRouter,
|
||||
@@ -14,6 +17,8 @@ interface BinarySessionStatusInput {
|
||||
string,
|
||||
{ readonly available: boolean; readonly reason: string | null }
|
||||
>;
|
||||
readonly runId: string | undefined;
|
||||
readonly runtimeLineageSnapshots: readonly ProviderRuntimeLineageSnapshot[];
|
||||
}
|
||||
|
||||
/** Project internal provider routing state into the caller-visible session status. */
|
||||
@@ -22,6 +27,8 @@ export const binarySessionStatus = ({
|
||||
route,
|
||||
router,
|
||||
runtimeAvailability,
|
||||
runId,
|
||||
runtimeLineageSnapshots,
|
||||
}: BinarySessionStatusInput): JsonValue => {
|
||||
const configuredProvider = router.configuredIdentity();
|
||||
const provider = providerSummary(configuredProvider);
|
||||
@@ -59,6 +66,13 @@ export const binarySessionStatus = ({
|
||||
capabilities,
|
||||
analysis_provider_binding: analysisProviderBinding,
|
||||
analysis_provider_candidates: analysisProviderCandidates,
|
||||
analysis_run:
|
||||
runId === undefined
|
||||
? null
|
||||
: {
|
||||
run_id: runId,
|
||||
process_lineage: processLineageStatus(runtimeLineageSnapshots),
|
||||
},
|
||||
};
|
||||
return target === undefined
|
||||
? { open: false, ...common }
|
||||
@@ -83,6 +97,47 @@ const providerSummary = ({
|
||||
readonly version: string | null;
|
||||
}) => ({ id, name, version });
|
||||
|
||||
const processLineageStatus = (
|
||||
snapshots: readonly ProviderRuntimeLineageSnapshot[],
|
||||
) =>
|
||||
snapshots.length === 0
|
||||
? { status: "not_observed" }
|
||||
: {
|
||||
status: "snapshots",
|
||||
snapshots: snapshots
|
||||
.slice()
|
||||
.sort((left, right) =>
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
)
|
||||
.map(({ provider, observation }) => ({
|
||||
provider: providerSummary(provider),
|
||||
observation:
|
||||
observation.status === "unavailable"
|
||||
? {
|
||||
status: observation.status,
|
||||
observed_at: observation.observedAt,
|
||||
launcher_pid: observation.launcherPid,
|
||||
process_group_id: observation.processGroupId,
|
||||
reason: observation.reason,
|
||||
}
|
||||
: {
|
||||
status: observation.status,
|
||||
observed_at: observation.observedAt,
|
||||
schema_version: observation.lineage.schemaVersion,
|
||||
launcher_pid: observation.lineage.launcherPid,
|
||||
launcher_parent_pid: observation.lineage.launcherParentPid,
|
||||
process_group_id: observation.lineage.processGroupId,
|
||||
descendants: observation.lineage.descendants.map(
|
||||
({ pid, parentPid, processGroupId }) => ({
|
||||
pid,
|
||||
parent_pid: parentPid,
|
||||
process_group_id: processGroupId,
|
||||
}),
|
||||
),
|
||||
},
|
||||
})),
|
||||
};
|
||||
|
||||
const capabilityStatus = (
|
||||
descriptor: Omit<CapabilityDescriptor, "available" | "reason"> & {
|
||||
readonly available: boolean;
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisClientContext,
|
||||
AnalysisProfileResolutionOptions,
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
@@ -88,6 +89,7 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
context?: AnalysisClientContext,
|
||||
): AnalysisClient {
|
||||
const clients = new Map<AnalysisProvider, AnalysisClient>();
|
||||
const clientFor = (provider: AnalysisProvider): AnalysisClient => {
|
||||
@@ -96,6 +98,7 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
const created = provider.createClient(
|
||||
target,
|
||||
profile?.provider.id === provider.identity().id ? profile : undefined,
|
||||
context,
|
||||
);
|
||||
clients.set(provider, created);
|
||||
return created;
|
||||
@@ -126,6 +129,12 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
)
|
||||
: clientFor(provider).execute(operation, parameters, options);
|
||||
},
|
||||
runtimeLineageSnapshots: () =>
|
||||
[...clients.values()]
|
||||
.flatMap((client) => client.runtimeLineageSnapshots?.() ?? [])
|
||||
.sort((left, right) =>
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
),
|
||||
close: async () => {
|
||||
await Promise.allSettled(
|
||||
[...clients.values()].map(async (client) => client.close()),
|
||||
|
||||
@@ -15,6 +15,7 @@ import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisClientContext,
|
||||
AnalysisClientFactory,
|
||||
AnalysisProfileResolution,
|
||||
AnalysisProfileResolutionOptions,
|
||||
@@ -42,7 +43,10 @@ export interface SessionProviderRoute {
|
||||
readonly compatibility: Readonly<Record<string, JsonValue>>;
|
||||
readonly binding: AnalysisProviderBinding | null;
|
||||
readonly selection: AnalysisProviderSelection | undefined;
|
||||
createClient(target: BinaryTarget): AnalysisClient;
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
context: AnalysisClientContext,
|
||||
): AnalysisClient;
|
||||
}
|
||||
|
||||
interface LegacyProviderRuntime {
|
||||
@@ -172,7 +176,8 @@ export class SessionProviderRouter {
|
||||
compatibility: {},
|
||||
binding: null,
|
||||
selection: undefined,
|
||||
createClient: (target) => createLegacyClient(runtime, target, undefined),
|
||||
createClient: (target, context) =>
|
||||
createLegacyClient(runtime, target, undefined, context),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -225,11 +230,12 @@ export class SessionProviderRouter {
|
||||
compatibility: normalized.value.compatibility,
|
||||
binding: null,
|
||||
selection: undefined,
|
||||
createClient: (openedTarget) =>
|
||||
createClient: (openedTarget, context) =>
|
||||
createLegacyClient(
|
||||
runtime,
|
||||
openedTarget,
|
||||
normalized.value.profile ?? undefined,
|
||||
context,
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -280,8 +286,9 @@ const selectableRoute = (
|
||||
compatibility: structuredClone(binding?.compatibility ?? {}),
|
||||
binding,
|
||||
selection,
|
||||
createClient: (target) =>
|
||||
provider?.createClient(target, binding?.profile) ?? emptyClient(identity),
|
||||
createClient: (target, context) =>
|
||||
provider?.createClient(target, binding?.profile, context) ??
|
||||
emptyClient(identity),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -289,10 +296,11 @@ const createLegacyClient = (
|
||||
runtime: LegacyProviderRuntime,
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
context: AnalysisClientContext,
|
||||
): AnalysisClient =>
|
||||
typeof runtime.provider === "function"
|
||||
? runtime.provider(target, profile)
|
||||
: runtime.provider.createClient(target, profile);
|
||||
? runtime.provider(target, profile, context)
|
||||
: runtime.provider.createClient(target, profile, context);
|
||||
|
||||
const emptyClient = (identity: ProviderIdentity): AnalysisClient => ({
|
||||
execute: (operation) =>
|
||||
|
||||
@@ -91,6 +91,52 @@ export const providerIdentity = z.object({
|
||||
version: z.string().nullable(),
|
||||
});
|
||||
|
||||
const processCoordinates = {
|
||||
launcher_pid: z.number().int().min(1),
|
||||
process_group_id: z.number().int().min(1),
|
||||
};
|
||||
|
||||
const processLineageObservation = z.discriminatedUnion("status", [
|
||||
z.object({
|
||||
status: z.literal("unavailable"),
|
||||
observed_at: z.iso.datetime(),
|
||||
...processCoordinates,
|
||||
reason: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
status: z.literal("verified"),
|
||||
observed_at: z.iso.datetime(),
|
||||
schema_version: z.literal(1),
|
||||
...processCoordinates,
|
||||
launcher_parent_pid: z.number().int().min(0),
|
||||
descendants: z.array(
|
||||
z.object({
|
||||
pid: z.number().int().min(1),
|
||||
parent_pid: z.number().int().min(0),
|
||||
process_group_id: z.number().int().min(1),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
const analysisRun = z
|
||||
.object({
|
||||
run_id: z.string().uuid(),
|
||||
process_lineage: z.discriminatedUnion("status", [
|
||||
z.object({ status: z.literal("not_observed") }),
|
||||
z.object({
|
||||
status: z.literal("snapshots"),
|
||||
snapshots: z.array(
|
||||
z.object({
|
||||
provider: providerIdentity,
|
||||
observation: processLineageObservation,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]),
|
||||
})
|
||||
.nullable();
|
||||
|
||||
const providerRejectionCode: z.ZodType<ProviderRejectionCode> = z.enum(
|
||||
PROVIDER_REJECTION_CODES,
|
||||
);
|
||||
@@ -175,6 +221,7 @@ export const sessionProvider = z.object({
|
||||
provider: providerIdentity,
|
||||
providers: z.array(providerIdentity),
|
||||
capabilities: z.array(providerCapability),
|
||||
analysis_run: analysisRun,
|
||||
analysis_provider_binding: z
|
||||
.object({
|
||||
provider: providerIdentity,
|
||||
|
||||
@@ -29,6 +29,52 @@ const skillDigestSchema = z.strictObject({
|
||||
skill_id: identifierSchema,
|
||||
sha256: digestSchema,
|
||||
});
|
||||
const verifierRunSchema = z
|
||||
.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
run_id: z.string().uuid(),
|
||||
verifier_pid: z.number().int().positive(),
|
||||
parent_pid: z.number().int().nonnegative(),
|
||||
process_lineage: z.discriminatedUnion("status", [
|
||||
z.strictObject({
|
||||
status: z.literal("verified"),
|
||||
schema_version: z.literal(1),
|
||||
observed_at: z.iso.datetime(),
|
||||
launcher_pid: z.number().int().positive(),
|
||||
launcher_parent_pid: z.number().int().nonnegative(),
|
||||
process_group_id: z.number().int().positive(),
|
||||
descendants: z.array(
|
||||
z.strictObject({
|
||||
pid: z.number().int().positive(),
|
||||
parent_pid: z.number().int().nonnegative(),
|
||||
process_group_id: z.number().int().positive(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.literal("unavailable"),
|
||||
observed_at: z.iso.datetime(),
|
||||
launcher_pid: z.number().int().positive(),
|
||||
launcher_parent_pid: z.number().int().nonnegative(),
|
||||
process_group_id: z.number().int().positive().nullable(),
|
||||
reason: z.string().min(1).max(500),
|
||||
}),
|
||||
]),
|
||||
})
|
||||
.superRefine((run, context) => {
|
||||
if (run.process_lineage.launcher_pid !== run.verifier_pid)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["process_lineage", "launcher_pid"],
|
||||
message: "Lineage launcher PID must identify the verifier process",
|
||||
});
|
||||
if (run.process_lineage.launcher_parent_pid !== run.parent_pid)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["process_lineage", "launcher_parent_pid"],
|
||||
message: "Lineage parent PID must identify the verifier parent",
|
||||
});
|
||||
});
|
||||
const reportClaimSchema = z.strictObject({
|
||||
claim_id: identifierSchema,
|
||||
scenario: scenarioSchema,
|
||||
@@ -42,6 +88,7 @@ const reportClaimSchema = z.strictObject({
|
||||
const completionVerifierReportObjectSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
verifier: identitySchema,
|
||||
verifier_run: verifierRunSchema,
|
||||
environment: environmentSchema,
|
||||
claims: z.array(reportClaimSchema).min(1).max(10_000),
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import { silentLogger, type Logger } from "../logger.js";
|
||||
import { PendingOperations } from "../process/PendingOperations.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import { ProviderRunLineage } from "../process/ProviderRunLineage.js";
|
||||
import {
|
||||
type ProviderProcessDiagnostic,
|
||||
type ProviderProcessSnapshot,
|
||||
@@ -84,6 +85,7 @@ export class GhidraClient {
|
||||
#snapshotPath: string | undefined;
|
||||
#token: string | undefined;
|
||||
#runId: string | undefined;
|
||||
readonly #lineage = new ProviderRunLineage();
|
||||
#nextId = 1;
|
||||
#closing = false;
|
||||
#processSnapshot: ProviderProcessSnapshot | undefined;
|
||||
@@ -217,6 +219,11 @@ export class GhidraClient {
|
||||
return structuredClone(this.#diagnostics());
|
||||
}
|
||||
|
||||
/** Latest token-verified launcher lineage for the active run. */
|
||||
runtimeLineage() {
|
||||
return this.#lineage.snapshot();
|
||||
}
|
||||
|
||||
async #start(signal: AbortSignal): Promise<GhidraStartResult> {
|
||||
if (signal.aborted)
|
||||
return err(this.#failure("cancelled", "Ghidra startup was cancelled"));
|
||||
@@ -274,7 +281,8 @@ export class GhidraClient {
|
||||
}
|
||||
if (deadline.signal.aborted) return this.#startupInterrupted(deadline);
|
||||
this.#token = randomBytes(32).toString("hex");
|
||||
this.#runId = randomUUID();
|
||||
this.#lineage.reset();
|
||||
this.#runId = this.#options.runId ?? randomUUID();
|
||||
const launched = await this.#options.launcher
|
||||
.launch(
|
||||
{
|
||||
@@ -312,7 +320,7 @@ export class GhidraClient {
|
||||
await this.#cleanup();
|
||||
return err(failure);
|
||||
}
|
||||
return completeGhidraStartupHandshake({
|
||||
const completed = await completeGhidraStartupHandshake({
|
||||
deadline,
|
||||
request: (method, params, requestOptions) =>
|
||||
this.#wire.request(method, params, requestOptions),
|
||||
@@ -321,6 +329,8 @@ export class GhidraClient {
|
||||
failure: this.#failure,
|
||||
startupTimeoutMs: this.#options.startupTimeoutMs,
|
||||
});
|
||||
if (completed.ok) await this.#lineage.observe(this.#launch);
|
||||
return completed;
|
||||
}
|
||||
|
||||
async #connect(
|
||||
@@ -497,6 +507,7 @@ export class GhidraClient {
|
||||
transport: this.#options.transport,
|
||||
providerVersion: this.#options.providerVersion,
|
||||
profileDigest: this.#options.profileDigest,
|
||||
...(this.#runId === undefined ? {} : { runId: this.#runId }),
|
||||
...(this.#runtimeRoot === undefined
|
||||
? {}
|
||||
: { runtimeRoot: this.#runtimeRoot.path }),
|
||||
|
||||
@@ -33,6 +33,7 @@ export type GhidraDiagnostic =
|
||||
/** Dependencies and exact profile commitment for one headless import. */
|
||||
export interface GhidraClientOptions {
|
||||
readonly launcher: GhidraLauncher;
|
||||
readonly runId?: string;
|
||||
readonly targetPath: string;
|
||||
readonly targetSha256: string;
|
||||
readonly transport?: GhidraTransportKind;
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface GhidraDiagnosticsOptions {
|
||||
readonly transport: GhidraTransportKind;
|
||||
readonly providerVersion: string;
|
||||
readonly profileDigest: string;
|
||||
readonly runId?: string;
|
||||
readonly runtimeRoot?: string;
|
||||
readonly launch?: GhidraLaunch;
|
||||
readonly snapshot?: ProviderProcessSnapshot;
|
||||
@@ -39,6 +40,7 @@ export const createGhidraDiagnostics = (
|
||||
transport: options.transport,
|
||||
provider_version: options.providerVersion,
|
||||
profile_digest: options.profileDigest,
|
||||
...(options.runId === undefined ? {} : { run_id: options.runId }),
|
||||
...(options.runtimeRoot === undefined
|
||||
? {}
|
||||
: {
|
||||
|
||||
@@ -157,9 +157,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
}
|
||||
const spawned = started;
|
||||
return ok({
|
||||
process: spawned.process,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup: () => cleanupStartedProcess(spawned, platform),
|
||||
...ownedGhidraProcess(spawned, platform),
|
||||
projectRoot: paths.projectRoot,
|
||||
ghidraLogPath: paths.ghidraLogPath,
|
||||
scriptLogPath: paths.scriptLogPath,
|
||||
@@ -176,6 +174,19 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
}
|
||||
}
|
||||
|
||||
const ownedGhidraProcess = (
|
||||
spawned: SpawnedOwnedProviderProcess,
|
||||
platform: NodeJS.Platform,
|
||||
): Pick<
|
||||
GhidraLaunch,
|
||||
"process" | "ownsProcessLifetime" | "ownership" | "cleanup"
|
||||
> => ({
|
||||
process: spawned.process,
|
||||
ownsProcessLifetime: true,
|
||||
ownership: spawned.ownership,
|
||||
cleanup: () => cleanupStartedProcess(spawned, platform),
|
||||
});
|
||||
|
||||
/** Exact executable and argv passed to shell-free process creation. */
|
||||
export interface GhidraHeadlessCommand {
|
||||
readonly command: string;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisClient,
|
||||
type AnalysisClientContext,
|
||||
type AnalysisOperation,
|
||||
type AnalysisProfileResolutionOptions,
|
||||
type AnalysisProviderCandidate,
|
||||
@@ -69,7 +70,8 @@ const SUPPORTED_FORMATS = new Set(["elf", "pe", "mach-o"]);
|
||||
/** Production seam for exercising provider projection without a real process. */
|
||||
export type GhidraProviderClientFactory = (
|
||||
options: GhidraClientOptions,
|
||||
) => Pick<GhidraClient, "start" | "callTool" | "close">;
|
||||
) => Pick<GhidraClient, "start" | "callTool" | "close"> &
|
||||
Partial<Pick<GhidraClient, "runtimeLineage">>;
|
||||
|
||||
/** Ghidra candidate backed by an isolated read-only headless import. */
|
||||
export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
@@ -172,6 +174,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
context?: AnalysisClientContext,
|
||||
): AnalysisClient {
|
||||
const installation = this.#inspectInstallation();
|
||||
const prerequisites = ghidraClientPrerequisites(
|
||||
@@ -202,6 +205,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
: "unix-socket",
|
||||
providerVersion: prerequisites.value.providerVersion,
|
||||
profileDigest: committedProfile.digest,
|
||||
...(context === undefined ? {} : { runId: context.runId }),
|
||||
logger: this.logger.child({ layer: "ghidra-bridge" }),
|
||||
});
|
||||
return {
|
||||
@@ -254,6 +258,12 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
}),
|
||||
);
|
||||
},
|
||||
runtimeLineageSnapshots: () => {
|
||||
const observation = client.runtimeLineage?.() ?? null;
|
||||
return observation === null
|
||||
? []
|
||||
: [{ provider: committedProfile.provider, observation }];
|
||||
},
|
||||
close: () => client.close(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -183,6 +183,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
|
||||
return ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
ownership: started.ownership,
|
||||
shutdownByCleanup: ownsProcessLifetime,
|
||||
cleanup: () => cleanupOwnedProcessGroup(started.ownership),
|
||||
});
|
||||
|
||||
@@ -21,6 +21,7 @@ import { PendingOperations } from "../process/PendingOperations.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import type { ProcessCleanupResult } from "../process/ProcessOwnership.js";
|
||||
import { ProviderRunLineage } from "../process/ProviderRunLineage.js";
|
||||
import {
|
||||
type ProviderProcessDiagnostic,
|
||||
ProviderProcessSupervisor,
|
||||
@@ -45,6 +46,7 @@ const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
|
||||
/** Dependencies, deadlines, and redacted diagnostics for one bridge client. */
|
||||
export interface HopperClientOptions {
|
||||
readonly launcher: BridgeLauncher;
|
||||
readonly runId?: string;
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly startupTimeoutMs?: number;
|
||||
readonly onDiagnostic?: (event: HopperDiagnostic) => void;
|
||||
@@ -79,6 +81,7 @@ export class HopperClient {
|
||||
#process: ProviderProcessSupervisor | undefined;
|
||||
#runtimeRoot: PrivateRuntimeRoot | undefined;
|
||||
#token: string | undefined;
|
||||
readonly #lineage = new ProviderRunLineage();
|
||||
#nextId = 1;
|
||||
#buffer = "";
|
||||
#closing = false;
|
||||
@@ -106,6 +109,11 @@ export class HopperClient {
|
||||
};
|
||||
}
|
||||
|
||||
/** Latest token-verified launcher lineage for the active run. */
|
||||
runtimeLineage() {
|
||||
return this.#lineage.snapshot();
|
||||
}
|
||||
|
||||
/** Launch the bridge once and complete its authenticated health handshake. */
|
||||
start(signal?: AbortSignal): Promise<Result<HopperServerInfo, HopperError>> {
|
||||
if (this.#closePromise !== undefined) {
|
||||
@@ -179,9 +187,10 @@ export class HopperClient {
|
||||
}
|
||||
const socketPath = join(this.#runtimeRoot.path, "bridge.sock");
|
||||
this.#token = randomBytes(32).toString("hex");
|
||||
this.#lineage.reset();
|
||||
this.#launcherExitCode = undefined;
|
||||
this.#launcherFailureDiagnostic = undefined;
|
||||
const runId = randomUUID();
|
||||
const runId = this.#options.runId ?? randomUUID();
|
||||
const launched: Result<
|
||||
BridgeLaunch,
|
||||
HopperStartError | HopperCancelledError | HopperProcessError
|
||||
@@ -229,7 +238,8 @@ export class HopperClient {
|
||||
: health;
|
||||
}
|
||||
const parsed = parseHopperServerInfo(health.value, runId);
|
||||
if (!parsed.ok) await this.#cleanup();
|
||||
if (parsed.ok) await this.#lineage.observe(this.#launch);
|
||||
else await this.#cleanup();
|
||||
return parsed;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { accessSync, constants } from "node:fs";
|
||||
import { createAnalysisExecution } from "../application/AnalysisProvider.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisClientContext,
|
||||
AnalysisProfileResolutionOptions,
|
||||
AnalysisProviderCandidate,
|
||||
CapabilityDescriptor,
|
||||
@@ -186,6 +187,7 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
createClient(
|
||||
target: BinaryTarget,
|
||||
profile?: AnalysisProfileCommitment,
|
||||
context?: AnalysisClientContext,
|
||||
): AnalysisClient {
|
||||
if (target.kind !== "executable" && target.kind !== "database")
|
||||
return {
|
||||
@@ -229,6 +231,7 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
}
|
||||
: { launchMode: "native" as const }),
|
||||
}),
|
||||
...(context === undefined ? {} : { runId: context.runId }),
|
||||
logger: this.logger.child({ layer: "bridge" }),
|
||||
});
|
||||
return {
|
||||
@@ -246,6 +249,12 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
}
|
||||
: result;
|
||||
},
|
||||
runtimeLineageSnapshots: () => {
|
||||
const observation = client.runtimeLineage();
|
||||
return observation === null
|
||||
? []
|
||||
: [{ provider: executionProvider, observation }];
|
||||
},
|
||||
close: () => client.close(),
|
||||
};
|
||||
}
|
||||
|
||||
+329
-79
@@ -15,8 +15,8 @@ export interface OwnedProcessGroup {
|
||||
readonly expectedParentPid?: number;
|
||||
}
|
||||
|
||||
/** One operating-system observation of a process-group member. */
|
||||
interface ProcessGroupMember {
|
||||
/** One entry from an operating-system process-table snapshot. */
|
||||
export interface ProcessTableEntry {
|
||||
readonly pid: number;
|
||||
readonly parentPid: number;
|
||||
readonly processGroupId: number;
|
||||
@@ -24,17 +24,39 @@ interface ProcessGroupMember {
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
/** Narrow operating-system seam used to inspect and signal process groups. */
|
||||
export interface ProcessOwnershipHost {
|
||||
listMembers(processGroupId: number): Promise<
|
||||
readonly {
|
||||
readonly pid: number;
|
||||
readonly parentPid: number;
|
||||
/** Token-verified process lineage retained for one owned provider run. */
|
||||
export interface OwnedProcessLineage {
|
||||
readonly schemaVersion: 1;
|
||||
readonly runId: string;
|
||||
readonly launcherPid: number;
|
||||
readonly launcherParentPid: number;
|
||||
readonly processGroupId: number;
|
||||
readonly descendants: readonly {
|
||||
readonly pid: number;
|
||||
readonly parentPid: number;
|
||||
readonly processGroupId: number;
|
||||
}[];
|
||||
}
|
||||
|
||||
/** Result of observing owned lineage without signaling any process. */
|
||||
export type ProcessLineageObservation =
|
||||
| {
|
||||
readonly status: "verified";
|
||||
readonly observedAt: string;
|
||||
readonly lineage: OwnedProcessLineage;
|
||||
}
|
||||
| {
|
||||
readonly status: "unavailable";
|
||||
readonly observedAt: string;
|
||||
readonly runId: string;
|
||||
readonly launcherPid: number;
|
||||
readonly processGroupId: number;
|
||||
readonly state: string;
|
||||
readonly command: string;
|
||||
}[]
|
||||
>;
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** Narrow operating-system seam used to inspect processes and signal groups. */
|
||||
export interface ProcessOwnershipHost {
|
||||
listProcesses(): Promise<readonly ProcessTableEntry[]>;
|
||||
environment(pid: number): Promise<Readonly<Record<string, string>>>;
|
||||
signalGroup(processGroupId: number, signal: NodeJS.Signals): void;
|
||||
}
|
||||
@@ -126,7 +148,7 @@ export const parseProcessEnvironment = (
|
||||
);
|
||||
|
||||
const systemHost: ProcessOwnershipHost = {
|
||||
async listMembers(processGroupId) {
|
||||
async listProcesses() {
|
||||
if (process.platform === "win32") return [];
|
||||
const { stdout } = await execFileAsync("ps", [
|
||||
"-axo",
|
||||
@@ -142,8 +164,7 @@ const systemHost: ProcessOwnershipHost = {
|
||||
processGroupId: Number(match[3]),
|
||||
state: match[4] ?? "",
|
||||
command: match[5] ?? "",
|
||||
}))
|
||||
.filter((member) => member.processGroupId === processGroupId);
|
||||
}));
|
||||
},
|
||||
async environment(pid) {
|
||||
if (process.platform === "linux") {
|
||||
@@ -192,73 +213,186 @@ export const readProcessRunId = async (
|
||||
): Promise<string | undefined> =>
|
||||
(await host.environment(pid)).REA_PROCESS_RUN_ID;
|
||||
|
||||
/**
|
||||
* Verify run-token ownership before signaling a POSIX process group.
|
||||
*
|
||||
* Process IDs and group IDs can be reused. REA therefore re-reads every live
|
||||
* member's environment immediately before signaling and fails closed if any
|
||||
* member cannot be inspected or lacks the per-capture run token.
|
||||
*/
|
||||
/** Token-validate every rooted POSIX process group before signaling any. */
|
||||
export const cleanupOwnedProcessGroup = async (
|
||||
ownership: OwnedProcessGroup,
|
||||
host: ProcessOwnershipHost = systemHost,
|
||||
): Promise<ProcessCleanupResult> => {
|
||||
let members: readonly ProcessGroupMember[];
|
||||
let processes: readonly ProcessTableEntry[];
|
||||
try {
|
||||
members = await host.listMembers(ownership.processGroupId);
|
||||
processes = liveProcesses(await host.listProcesses());
|
||||
} catch {
|
||||
return { cleaned: false, reason: "process group could not be inspected" };
|
||||
return { cleaned: false, reason: "process table could not be inspected" };
|
||||
}
|
||||
const liveMembers = liveProcessGroupMembers(members);
|
||||
if (liveMembers.length === 0) return { cleaned: true, signaled: false };
|
||||
const leader = liveMembers.find(
|
||||
(member) => member.pid === ownership.leaderPid,
|
||||
);
|
||||
if (leader !== undefined) {
|
||||
if (
|
||||
ownership.expectedParentPid !== undefined &&
|
||||
leader.parentPid !== ownership.expectedParentPid
|
||||
)
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "owned launcher parent identity did not match",
|
||||
};
|
||||
if (
|
||||
ownership.expectedCommand !== undefined &&
|
||||
!commandMatches(leader.command, ownership.expectedCommand)
|
||||
)
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "owned launcher command identity did not match",
|
||||
};
|
||||
}
|
||||
const failures: ProcessOwnershipValidationFailure[] = [];
|
||||
for (const member of liveMembers) {
|
||||
const plan = await createOwnedCleanupPlan(ownership, processes, host);
|
||||
if ("cleaned" in plan) return plan;
|
||||
let signaled = false;
|
||||
for (const processGroupId of plan.signalOrder) {
|
||||
const revalidation = await revalidateOwnedProcessGroup(
|
||||
processGroupId,
|
||||
ownership,
|
||||
host,
|
||||
);
|
||||
if ("cleaned" in revalidation) return revalidation;
|
||||
if (revalidation.empty) continue;
|
||||
try {
|
||||
const environment = await host.environment(member.pid);
|
||||
if (environment.REA_PROCESS_RUN_ID !== ownership.runId)
|
||||
host.signalGroup(processGroupId, "SIGKILL");
|
||||
signaled = true;
|
||||
} catch (cause: unknown) {
|
||||
const code =
|
||||
cause instanceof Error && "code" in cause ? cause.code : undefined;
|
||||
if (code !== "ESRCH")
|
||||
return { cleaned: false, reason: "owned process group signal failed" };
|
||||
}
|
||||
}
|
||||
return { cleaned: true, signaled };
|
||||
};
|
||||
|
||||
interface OwnedCleanupPlan {
|
||||
readonly signalOrder: readonly number[];
|
||||
}
|
||||
|
||||
const createOwnedCleanupPlan = async (
|
||||
ownership: OwnedProcessGroup,
|
||||
processes: readonly ProcessTableEntry[],
|
||||
host: ProcessOwnershipHost,
|
||||
): Promise<OwnedCleanupPlan | ProcessCleanupResult> => {
|
||||
const launcher = processes.find(({ pid }) => pid === ownership.leaderPid);
|
||||
const rootMembers = processes.filter(
|
||||
({ processGroupId }) => processGroupId === ownership.processGroupId,
|
||||
);
|
||||
if (launcher === undefined && rootMembers.length === 0)
|
||||
return { cleaned: true, signaled: false };
|
||||
let descendants: readonly ProcessTableEntry[] = [];
|
||||
if (launcher !== undefined) {
|
||||
const identityFailure = launcherIdentityFailure(launcher, ownership);
|
||||
if (identityFailure !== null)
|
||||
return { cleaned: false, reason: identityFailure };
|
||||
descendants = descendantsOf(launcher.pid, processes);
|
||||
}
|
||||
const descendantPids = new Set(descendants.map(({ pid }) => pid));
|
||||
const processGroupIds = new Set<number>([ownership.processGroupId]);
|
||||
for (const descendant of descendants)
|
||||
processGroupIds.add(descendant.processGroupId);
|
||||
for (const processGroupId of processGroupIds) {
|
||||
if (processGroupId === ownership.processGroupId) continue;
|
||||
const groupLeader = processes.find(
|
||||
({ pid, processGroupId: observedGroupId }) =>
|
||||
pid === processGroupId && observedGroupId === processGroupId,
|
||||
);
|
||||
if (groupLeader === undefined || !descendantPids.has(groupLeader.pid))
|
||||
return {
|
||||
cleaned: false,
|
||||
reason:
|
||||
"descendant process-group leader identity could not be verified",
|
||||
};
|
||||
}
|
||||
const liveMembers = processes.filter(({ processGroupId }) =>
|
||||
processGroupIds.has(processGroupId),
|
||||
);
|
||||
const failures = await processOwnershipFailures(
|
||||
liveMembers,
|
||||
ownership.runId,
|
||||
host,
|
||||
);
|
||||
if (failures.length > 0) return cleanupValidationFailure(failures);
|
||||
return {
|
||||
signalOrder: [ownership.processGroupId].concat(
|
||||
[...processGroupIds]
|
||||
.filter((processGroupId) => processGroupId !== ownership.processGroupId)
|
||||
.sort((left, right) => left - right),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const launcherIdentityFailure = (
|
||||
launcher: ProcessTableEntry,
|
||||
ownership: OwnedProcessGroup,
|
||||
): string | null => {
|
||||
if (launcher.processGroupId !== ownership.processGroupId)
|
||||
return "owned launcher process-group identity did not match";
|
||||
if (
|
||||
ownership.expectedParentPid !== undefined &&
|
||||
launcher.parentPid !== ownership.expectedParentPid
|
||||
)
|
||||
return "owned launcher parent identity did not match";
|
||||
if (
|
||||
ownership.expectedCommand !== undefined &&
|
||||
!commandMatches(launcher.command, ownership.expectedCommand)
|
||||
)
|
||||
return "owned launcher command identity did not match";
|
||||
return null;
|
||||
};
|
||||
|
||||
const revalidateOwnedProcessGroup = async (
|
||||
processGroupId: number,
|
||||
ownership: OwnedProcessGroup,
|
||||
host: ProcessOwnershipHost,
|
||||
): Promise<{ readonly empty: boolean } | ProcessCleanupResult> => {
|
||||
let members: readonly ProcessTableEntry[];
|
||||
try {
|
||||
members = liveProcesses(await host.listProcesses()).filter(
|
||||
({ processGroupId: observedGroupId }) =>
|
||||
observedGroupId === processGroupId,
|
||||
);
|
||||
} catch {
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "process ownership could not be revalidated",
|
||||
};
|
||||
}
|
||||
const failures = await processOwnershipFailures(
|
||||
members,
|
||||
ownership.runId,
|
||||
host,
|
||||
);
|
||||
if (failures.length > 0) return cleanupValidationFailure(failures);
|
||||
if (processGroupId === ownership.processGroupId) {
|
||||
const launcher = members.find(({ pid }) => pid === ownership.leaderPid);
|
||||
if (launcher !== undefined) {
|
||||
const identityFailure = launcherIdentityFailure(launcher, ownership);
|
||||
if (identityFailure !== null)
|
||||
return { cleaned: false, reason: identityFailure };
|
||||
}
|
||||
}
|
||||
if (
|
||||
processGroupId !== ownership.processGroupId &&
|
||||
members.length > 0 &&
|
||||
!members.some(({ pid }) => pid === processGroupId)
|
||||
)
|
||||
return {
|
||||
cleaned: false,
|
||||
reason:
|
||||
"descendant process-group leader identity could not be revalidated",
|
||||
};
|
||||
return { empty: members.length === 0 };
|
||||
};
|
||||
|
||||
const cleanupValidationFailure = (
|
||||
failures: readonly ProcessOwnershipValidationFailure[],
|
||||
): ProcessCleanupResult => ({
|
||||
cleaned: false,
|
||||
reason: failures.some(({ reason }) => reason === "run-token-mismatch")
|
||||
? "process tree contains an unowned or PID-reused process"
|
||||
: "process ownership could not be revalidated",
|
||||
failures,
|
||||
});
|
||||
|
||||
const processOwnershipFailures = async (
|
||||
members: readonly ProcessTableEntry[],
|
||||
runId: string,
|
||||
host: ProcessOwnershipHost,
|
||||
): Promise<readonly ProcessOwnershipValidationFailure[]> => {
|
||||
const failures: ProcessOwnershipValidationFailure[] = [];
|
||||
for (const member of members) {
|
||||
try {
|
||||
if ((await host.environment(member.pid)).REA_PROCESS_RUN_ID !== runId)
|
||||
failures.push({ pid: member.pid, reason: "run-token-mismatch" });
|
||||
} catch {
|
||||
failures.push({ pid: member.pid, reason: "environment-unreadable" });
|
||||
}
|
||||
}
|
||||
if (failures.length > 0)
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: failures.some(({ reason }) => reason === "run-token-mismatch")
|
||||
? "process group contains an unowned or PID-reused process"
|
||||
: "process ownership could not be revalidated",
|
||||
failures,
|
||||
};
|
||||
try {
|
||||
host.signalGroup(ownership.processGroupId, "SIGKILL");
|
||||
} catch (cause: unknown) {
|
||||
const code =
|
||||
cause instanceof Error && "code" in cause ? cause.code : undefined;
|
||||
if (code !== "ESRCH")
|
||||
return { cleaned: false, reason: "owned process group signal failed" };
|
||||
}
|
||||
return { cleaned: true, signaled: true };
|
||||
return failures;
|
||||
};
|
||||
|
||||
/** Observe one group without signaling it, failing closed on identity doubt. */
|
||||
@@ -266,16 +400,18 @@ export const observeOwnedProcessGroup = async (
|
||||
ownership: OwnedProcessGroup,
|
||||
host: ProcessOwnershipHost = systemHost,
|
||||
): Promise<ProcessGroupObservation> => {
|
||||
let members: readonly ProcessGroupMember[];
|
||||
let members: readonly ProcessTableEntry[];
|
||||
try {
|
||||
members = await host.listMembers(ownership.processGroupId);
|
||||
members = (await host.listProcesses()).filter(
|
||||
({ processGroupId }) => processGroupId === ownership.processGroupId,
|
||||
);
|
||||
} catch {
|
||||
return {
|
||||
state: "unverifiable",
|
||||
reason: "process group could not be inspected",
|
||||
};
|
||||
}
|
||||
const liveMembers = liveProcessGroupMembers(members);
|
||||
const liveMembers = liveProcesses(members);
|
||||
if (liveMembers.length === 0) return { state: "empty" };
|
||||
for (const member of liveMembers) {
|
||||
try {
|
||||
@@ -297,16 +433,130 @@ export const observeOwnedProcessGroup = async (
|
||||
return { state: "alive" };
|
||||
};
|
||||
|
||||
const liveProcessGroupMembers = (
|
||||
members: readonly ProcessGroupMember[],
|
||||
): readonly ProcessGroupMember[] =>
|
||||
/**
|
||||
* Record the live launcher and descendant lineage after run-token validation.
|
||||
*
|
||||
* The observation is intentionally point-in-time. A verified empty descendant
|
||||
* list means no descendants were live during this observation, not that the
|
||||
* run never created a short-lived child.
|
||||
*/
|
||||
export const observeOwnedProcessLineage = async (
|
||||
ownership: OwnedProcessGroup,
|
||||
host: ProcessOwnershipHost = systemHost,
|
||||
): Promise<ProcessLineageObservation> => {
|
||||
let processes: readonly ProcessTableEntry[];
|
||||
try {
|
||||
processes = liveProcesses(await host.listProcesses());
|
||||
} catch {
|
||||
return unavailableLineage(
|
||||
ownership,
|
||||
"process table could not be inspected",
|
||||
);
|
||||
}
|
||||
const launcher = processes.find(({ pid }) => pid === ownership.leaderPid);
|
||||
if (launcher === undefined)
|
||||
return unavailableLineage(ownership, "owned launcher is not live");
|
||||
if (launcher.processGroupId !== ownership.processGroupId)
|
||||
return unavailableLineage(
|
||||
ownership,
|
||||
"owned launcher process-group identity did not match",
|
||||
);
|
||||
if (
|
||||
ownership.expectedParentPid !== undefined &&
|
||||
launcher.parentPid !== ownership.expectedParentPid
|
||||
)
|
||||
return unavailableLineage(
|
||||
ownership,
|
||||
"owned launcher parent identity did not match",
|
||||
);
|
||||
if (
|
||||
ownership.expectedCommand !== undefined &&
|
||||
!commandMatches(launcher.command, ownership.expectedCommand)
|
||||
)
|
||||
return unavailableLineage(
|
||||
ownership,
|
||||
"owned launcher command identity did not match",
|
||||
);
|
||||
const descendants = descendantsOf(launcher.pid, processes);
|
||||
for (const member of [launcher, ...descendants]) {
|
||||
try {
|
||||
if (
|
||||
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
|
||||
ownership.runId
|
||||
)
|
||||
return unavailableLineage(
|
||||
ownership,
|
||||
"process lineage contains an unowned or PID-reused process",
|
||||
);
|
||||
} catch {
|
||||
return unavailableLineage(
|
||||
ownership,
|
||||
"process ownership could not be revalidated",
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: "verified",
|
||||
observedAt: new Date().toISOString(),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: ownership.runId,
|
||||
launcherPid: launcher.pid,
|
||||
launcherParentPid: launcher.parentPid,
|
||||
processGroupId: launcher.processGroupId,
|
||||
descendants: descendants
|
||||
.sort((left, right) => left.pid - right.pid)
|
||||
.map(({ pid, parentPid, processGroupId }) => ({
|
||||
pid,
|
||||
parentPid,
|
||||
processGroupId,
|
||||
})),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const descendantsOf = (
|
||||
launcherPid: number,
|
||||
processes: readonly ProcessTableEntry[],
|
||||
): ProcessTableEntry[] => {
|
||||
const childrenByParent = new Map<number, ProcessTableEntry[]>();
|
||||
for (const process of processes) {
|
||||
const siblings = childrenByParent.get(process.parentPid) ?? [];
|
||||
siblings.push(process);
|
||||
childrenByParent.set(process.parentPid, siblings);
|
||||
}
|
||||
const descendants: ProcessTableEntry[] = [];
|
||||
const pending = [...(childrenByParent.get(launcherPid) ?? [])];
|
||||
const visited = new Set<number>([launcherPid]);
|
||||
for (const process of pending) {
|
||||
if (visited.has(process.pid)) continue;
|
||||
visited.add(process.pid);
|
||||
descendants.push(process);
|
||||
pending.push(...(childrenByParent.get(process.pid) ?? []));
|
||||
}
|
||||
return descendants;
|
||||
};
|
||||
|
||||
const unavailableLineage = (
|
||||
ownership: OwnedProcessGroup,
|
||||
reason: string,
|
||||
): Extract<ProcessLineageObservation, { readonly status: "unavailable" }> => ({
|
||||
status: "unavailable",
|
||||
observedAt: new Date().toISOString(),
|
||||
runId: ownership.runId,
|
||||
launcherPid: ownership.leaderPid,
|
||||
processGroupId: ownership.processGroupId,
|
||||
reason,
|
||||
});
|
||||
|
||||
const liveProcesses = (
|
||||
members: readonly ProcessTableEntry[],
|
||||
): readonly ProcessTableEntry[] =>
|
||||
members.filter(({ state }) => !state.startsWith("Z"));
|
||||
|
||||
const commandMatches = (actual: string, expected: string): boolean => {
|
||||
const normalizedActual = actual.trim();
|
||||
const normalizedExpected = expected.trim();
|
||||
return (
|
||||
normalizedActual === normalizedExpected ||
|
||||
normalizedActual.startsWith(`${normalizedExpected} `)
|
||||
actual.trim() === expected.trim() ||
|
||||
actual.trim().startsWith(`${expected.trim()} `)
|
||||
);
|
||||
};
|
||||
|
||||
@@ -33,6 +33,7 @@ export interface SpawnedOwnedProviderProcess {
|
||||
export interface ProviderProcessLaunch {
|
||||
readonly process: ChildProcess;
|
||||
readonly ownsProcessLifetime: boolean;
|
||||
readonly ownership?: OwnedProcessGroup;
|
||||
readonly cleanup?: () => Promise<ProcessCleanupResult>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { ProcessLineageObservation } from "./ProcessOwnership.js";
|
||||
import { observeOwnedProcessLineage } from "./ProcessOwnership.js";
|
||||
import type { ProviderProcessLaunch } from "./ProviderProcess.js";
|
||||
|
||||
/** Retain the latest truthful process-lineage observation for one client. */
|
||||
export class ProviderRunLineage {
|
||||
#observation: ProcessLineageObservation | null = null;
|
||||
|
||||
/** Clear stale lineage before a new launch attempt. */
|
||||
reset(): void {
|
||||
this.#observation = null;
|
||||
}
|
||||
|
||||
/** Observe a token-owned launcher without signaling it. */
|
||||
async observe(launch: ProviderProcessLaunch | undefined): Promise<void> {
|
||||
if (launch?.ownership === undefined) return;
|
||||
this.#observation = await observeOwnedProcessLineage(launch.ownership);
|
||||
}
|
||||
|
||||
/** Return a detached copy suitable for caller-visible status. */
|
||||
snapshot(): ProcessLineageObservation | null {
|
||||
return this.#observation === null
|
||||
? null
|
||||
: structuredClone(this.#observation);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user