refactor(app): split session and CLI workflows

This commit is contained in:
morluto
2026-07-18 05:49:14 +00:00
parent 3e61a63a10
commit c6ee0049c4
88 changed files with 7428 additions and 6024 deletions
+54 -470
View File
@@ -1,25 +1,15 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { parseBinaryTarget } from "../domain/binaryTarget.js";
import {
analysisProfilesEqual,
type AnalysisProfileCommitment,
} from "../domain/analysisProfile.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import {
AnalysisCapabilityUnavailableError,
EvidenceIntegrityError,
EvidenceLimitError,
AnalysisCancelledError,
NoBinaryOpenError,
ProviderAdapterError,
type AnalysisError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Evidence } from "../domain/evidence.js";
import { createEvidence } from "../domain/evidence.js";
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
import { evidenceBundleForTarget } from "../domain/evidenceBundle.js";
import type {
AnalysisClient,
AnalysisExecution,
@@ -28,48 +18,23 @@ import type {
AnalysisProfileResolutionOptions,
AnalysisOperationPort,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
} from "./AnalysisProvider.js";
import { EvidenceLedger } from "./EvidenceLedger.js";
import type {
RecordUnknownInput,
ResidualUnknown,
UnknownStatus,
UpdateUnknownInput,
} from "../domain/residualUnknown.js";
import { UnknownRegistryError } from "../domain/errors.js";
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { enhancedToolNameSchema } from "../contracts/enhancedInputs.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import {
snapshotMatchesBinding,
snapshotMatchesTarget,
snapshotTarget,
} from "../domain/analysisSnapshot.js";
import {
AnalysisSnapshotCache,
isSnapshotCacheable,
} from "./AnalysisSnapshotCache.js";
import {
UNKNOWN_REGISTRY_PROVIDER,
unknownEvidenceLinks,
unknownMutationEvidence,
} from "./UnknownEvidence.js";
import type { BinarySessionPort } from "./BinarySessionPort.js";
import {
parseInvestigationWorkspace,
type InvestigationWorkspace,
} from "../domain/investigationWorkspace.js";
import {
parseReconstructionCoverageWorkspace,
type ReconstructionCoverageWorkspace,
} from "../domain/reconstructionCoverage.js";
import {
SessionProviderRouter,
type SessionProviderRoute,
} from "./SessionProviderRouter.js";
import { BinarySessionRecords } from "./BinarySessionRecords.js";
import { binarySessionStatus } from "./BinarySessionStatus.js";
import {
resolveSessionOpen,
type BinarySessionOpenOptions,
} from "./BinarySessionOpen.js";
import { prepareSessionExecution } from "./BinarySessionExecution.js";
export type { BinarySessionPort } from "./BinarySessionPort.js";
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
@@ -82,7 +47,10 @@ const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
* active provider client. A failed switch recreates the previous target instead
* of retaining a client whose resources were already shut down.
*/
export class BinarySession implements BinarySessionPort {
export class BinarySession
extends BinarySessionRecords
implements BinarySessionPort
{
#active:
| {
readonly target: BinaryTarget;
@@ -95,22 +63,11 @@ export class BinarySession implements BinarySessionPort {
#transition: Promise<void> = Promise.resolve();
readonly #calls = new Set<Promise<unknown>>();
readonly #providerRouter: SessionProviderRouter;
readonly #evidence = new EvidenceLedger({
maxRecords: 10_000,
maxBytes: 64 * 1024 * 1024,
});
readonly #snapshot = new AnalysisSnapshotCache();
readonly #investigationWorkspaces = new Map<string, InvestigationWorkspace>();
readonly #reconstructionCoverageWorkspaces = new Map<
string,
ReconstructionCoverageWorkspace
>();
readonly #runtimeAvailability = new Map<
string,
{ readonly available: boolean; readonly reason: string | null }
>();
readonly #availabilityListeners = new Set<() => void | Promise<void>>();
#snapshotInvalidated = false;
constructor(
readonly provider:
@@ -124,6 +81,7 @@ export class BinarySession implements BinarySessionPort {
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
} = {},
) {
super();
this.#providerRouter =
provider instanceof SessionProviderRouter
? provider
@@ -186,279 +144,28 @@ export class BinarySession implements BinarySessionPort {
return () => this.#availabilityListeners.delete(listener);
}
/** Add one successful public observation to the session ledger. */
recordEvidence(
evidence: Evidence,
): Result<
"added" | "duplicate",
EvidenceIntegrityError | EvidenceLimitError
> {
return this.#evidence.record(evidence);
}
/** Check that comparison input Evidence is already session-owned. */
hasEvidence(evidenceId: string): boolean {
return this.#evidence.has(evidenceId);
}
/** Read one detached session-owned Evidence record by semantic ID. */
evidenceById(evidenceId: string): Evidence | undefined {
return this.#evidence.get(evidenceId);
}
/** Return a deterministic snapshot without clearing session evidence. */
exportEvidenceBundle(): EvidenceBundle {
return this.#evidence.export();
}
/** Atomically merge a validated evidence bundle into this session. */
importEvidenceBundle(
bundle: unknown,
): Result<number, EvidenceIntegrityError | EvidenceLimitError> {
return this.#evidence.import(bundle);
}
/** Export immutable cached calls and session evidence for the active target. */
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError> {
if (this.#snapshotInvalidated)
return err(
new EvidenceIntegrityError(
"Analysis snapshots are unavailable after analysis metadata mutations",
),
);
const target = this.#active?.target;
const profile = this.#active?.profile ?? undefined;
if (target !== undefined && profile === undefined)
return err(
new EvidenceIntegrityError(
"Analysis snapshots require a concrete provider analysis profile",
),
);
return this.#snapshot.export(
target,
profile,
target === undefined
? this.#evidence.export()
: evidenceBundleForTarget(this.#evidence.export(), target.sha256),
);
}
/** Stage validated cached calls for an identical binary and merge its evidence. */
importAnalysisSnapshot(
snapshot: AnalysisSnapshot,
): Result<number, AnalysisError> {
const active = this.#active;
if (active?.profile === null)
return err(
new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: the active target has no concrete analysis profile",
),
);
return this.#snapshot.import(
snapshot,
active === undefined
? undefined
: { target: active.target, profile: active.profile },
(bundle) => this.#evidence.import(bundle),
);
}
/** Retain one validated immutable workspace revision for session resources. */
retainInvestigationWorkspace(
workspace: InvestigationWorkspace,
): "added" | "duplicate" {
const parsed = parseInvestigationWorkspace(workspace);
const key = `${parsed.workspace_id}:${String(parsed.revision)}`;
if (this.#investigationWorkspaces.has(key)) return "duplicate";
this.#investigationWorkspaces.set(key, parsed);
return "added";
}
/** Read one session-retained immutable workspace revision. */
investigationWorkspace(
workspaceId: string,
revision: number,
): InvestigationWorkspace | undefined {
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,
)
.map((workspace) => structuredClone(workspace));
}
/** Retain one validated immutable reconstruction coverage revision. */
retainReconstructionCoverageWorkspace(
workspace: ReconstructionCoverageWorkspace,
): "added" | "duplicate" {
const parsed = parseReconstructionCoverageWorkspace(workspace);
const key = `${parsed.workspace_id}:${String(parsed.revision)}`;
if (this.#reconstructionCoverageWorkspaces.has(key)) return "duplicate";
this.#reconstructionCoverageWorkspaces.set(key, parsed);
return "added";
}
/** Read one session-retained reconstruction coverage revision. */
reconstructionCoverageWorkspace(
workspaceId: string,
revision: number,
): ReconstructionCoverageWorkspace | undefined {
const workspace = this.#reconstructionCoverageWorkspaces.get(
`${workspaceId}:${String(revision)}`,
);
return workspace === undefined ? undefined : structuredClone(workspace);
}
/** List reconstruction coverage revisions in canonical identity order. */
reconstructionCoverageWorkspaces(): readonly ReconstructionCoverageWorkspace[] {
return [...this.#reconstructionCoverageWorkspaces.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. */
recordUnknown(
input: RecordUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const evidence = unknownMutationEvidence(this.#active?.target, input);
return this.#evidence.recordUnknown(input, evidence);
}
/** Atomically record derived Evidence and its approved residual unknown. */
recordEvidenceWithUnknown(
evidence: Evidence,
input: RecordUnknownInput,
): Result<ResidualUnknown | null, AnalysisError> {
return this.#evidence.recordWithUnknown(
evidence,
input,
unknownMutationEvidence(undefined, input),
);
}
/** Update one unknown using compare-and-swap revision semantics. */
updateUnknown(
input: UpdateUnknownInput,
): Result<ResidualUnknown, AnalysisError> {
const evidence = createEvidence(
this.#active?.target,
UNKNOWN_REGISTRY_PROVIDER,
{
predicateType: "rea.residual-unknown-mutation/v1",
operation: "update_unknown",
parameters: {
unknown_id: input.unknown_id,
expected_revision: input.expected_revision,
},
result: { action: "update", status: input.status },
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: unknownEvidenceLinks(input),
limitations: [
"Registry mutation evidence records analyst intent, not proof of the answer.",
],
},
);
return this.#evidence.updateUnknown(input, evidence);
}
/** Query stable current residual-unknown heads. */
listUnknowns(
filters: {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
} = {},
): ResidualUnknown[] {
return this.#evidence.listUnknowns(filters);
}
/** Check whether current head is a bundle-valid resolved state. */
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
readonly truthVerified: boolean;
readonly unknown: ResidualUnknown;
},
UnknownRegistryError
> {
return this.#evidence.verifyUnknownResolution(unknownId);
}
/**
* Open or switch targets after draining calls against the current target.
* Returns the switch failure even if best-effort restoration also fails.
*/
open(
path: string,
options: {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
readonly snapshot?: AnalysisSnapshot;
readonly providerId?: AnalysisProviderSelector;
} = {},
options: BinarySessionOpenOptions = {},
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#serialize(async () => {
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const parsed = await parseBinaryTarget(
const resolved = await resolveSessionOpen({
router: this.#providerRouter,
current: this.#active,
path,
process.cwd(),
process.arch,
options.targetKind,
);
if (!parsed.ok) return parsed;
const sameTarget =
this.#active?.target.path === parsed.value.path &&
snapshotMatchesTarget(
snapshotTarget(this.#active.target),
parsed.value,
);
const resolvedRoute =
sameTarget &&
options.providerId === undefined &&
this.#active !== undefined
? ok(this.#active.route)
: await this.#providerRouter.resolve(
parsed.value,
options.providerId,
options.signal,
);
if (!resolvedRoute.ok) return resolvedRoute;
const route = resolvedRoute.value;
options,
stagedSnapshotMatches: (target, profile) =>
this.matchesSnapshot(target, profile),
});
if (!resolved.ok) return resolved;
const { target, route, sameTarget } = resolved.value;
const { profile, compatibility } = route;
if (
options.snapshot !== undefined &&
(profile === null ||
!snapshotMatchesBinding(options.snapshot, parsed.value, profile))
)
return err(
new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the requested binary",
),
);
if (
this.#active === undefined &&
!this.#snapshot.matches(parsed.value, profile ?? undefined)
)
return err(
new EvidenceIntegrityError(
"Analysis snapshot profile_mismatch: staged target, provider, or analysis profile does not match",
),
);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const activeProfile = this.#active?.profile;
@@ -471,13 +178,13 @@ export class BinarySession implements BinarySessionPort {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) return imported;
}
return ok(parsed.value);
return ok(target);
}
await this.#drainCalls();
const previous = this.#active;
this.#active = undefined;
await previous?.client.close();
const client = route.createClient(parsed.value);
const client = route.createClient(target);
const started = await client.execute("health", {}, options);
if (!started.ok) {
await client.close();
@@ -490,15 +197,15 @@ export class BinarySession implements BinarySessionPort {
return err(new AnalysisCancelledError("open_binary"));
}
this.#active = {
target: parsed.value,
target,
client,
profile,
compatibility: structuredClone(compatibility),
route,
};
this.#clearRuntimeAvailability();
if (profile === null) this.#snapshot.clear();
else this.#snapshot.select(parsed.value, profile);
if (profile === null) this.clearSnapshot();
else this.selectSnapshot(target, profile);
if (options.snapshot !== undefined) {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) {
@@ -508,8 +215,8 @@ export class BinarySession implements BinarySessionPort {
return imported;
}
}
this.#snapshotInvalidated = false;
return ok(parsed.value);
this.resetSnapshotInvalidation();
return ok(target);
});
}
@@ -520,9 +227,7 @@ export class BinarySession implements BinarySessionPort {
this.#active = undefined;
await this.#drainCalls();
await previous?.client.close();
this.#evidence.clear();
this.#snapshot.clear();
this.#snapshotInvalidated = false;
this.clearSessionRecords();
this.#clearRuntimeAvailability();
return ok(null);
});
@@ -530,85 +235,12 @@ export class BinarySession implements BinarySessionPort {
/** Describe the active binary session. */
status(): JsonValue {
const target = this.#active?.target;
const route = this.#currentRoute();
const configuredProvider = this.#providerRouter.configuredIdentity();
const provider = {
id: configuredProvider.id,
name: configuredProvider.name,
version: configuredProvider.version,
};
const providerList = this.#providerRouter
.providerIdentities(route)
.map(({ id, name, version }) => ({ id, name, version }));
const capabilities =
route.capabilities === undefined
? []
: [...route.capabilities.values()]
.sort((left, right) =>
left.operation.localeCompare(right.operation),
)
.map((descriptor) => ({
...descriptor,
...this.#runtimeAvailability.get(descriptor.operation),
}))
.map((descriptor) => capabilityStatus(descriptor));
const analysisProviderBinding =
route.binding === null
? null
: {
provider: {
id: route.binding.identity.id,
name: route.binding.identity.name,
version: route.binding.identity.version,
},
selection_source: route.binding.selectionSource,
analysis_profile: structuredClone(route.binding.profile),
};
const analysisProviderCandidates = this.#providerRouter
.candidateStatuses(route)
.map((candidate) => ({
provider: {
id: candidate.provider.id,
name: candidate.provider.name,
version: candidate.provider.version,
},
availability: {
status: candidate.availability.status,
code: candidate.availability.code,
reason: candidate.availability.reason,
diagnostics: structuredClone(candidate.availability.diagnostics),
},
target_support: {
status: candidate.targetSupport.status,
code: candidate.targetSupport.code,
reason: candidate.targetSupport.reason,
diagnostics: structuredClone(candidate.targetSupport.diagnostics),
},
selected: candidate.selected,
capabilities: candidate.capabilities
.slice()
.sort((left, right) => left.operation.localeCompare(right.operation))
.map((descriptor) => capabilityStatus(descriptor)),
}));
const common = {
provider,
providers: providerList,
capabilities,
analysis_provider_binding: analysisProviderBinding,
analysis_provider_candidates: analysisProviderCandidates,
};
return target === undefined
? { open: false, ...common }
: {
open: true,
...common,
path: target.path,
sha256: target.sha256,
format: target.format,
kind: target.kind,
architecture: target.architecture ?? null,
};
return binarySessionStatus({
target: this.#active?.target,
route: this.#currentRoute(),
router: this.#providerRouter,
runtimeAvailability: this.#runtimeAvailability,
});
}
/** Return the immutable artifact identity captured before its provider started. */
@@ -618,6 +250,10 @@ export class BinarySession implements BinarySessionPort {
: structuredClone(this.#active.target);
}
protected activeAnalysisBinding() {
return this.#active;
}
/**
* Invoke a provider operation against the active target.
* Calls may overlap, but a pending target transition prevents new calls from
@@ -630,38 +266,17 @@ export class BinarySession implements BinarySessionPort {
): Promise<Result<AnalysisExecution, AnalysisError>> {
const transitioned = await this.#waitForTransition(name, options?.signal);
if (!transitioned.ok) return transitioned;
const active = this.#active;
if (active === undefined) return err(new NoBinaryOpenError());
const capability = active.route.capabilities?.get(name);
if (
active.route.capabilities !== undefined &&
capability?.available !== true
) {
const selectionError = this.#providerRouter.unboundOperationError(
name,
active.route,
);
if (selectionError !== undefined) return err(selectionError);
return err(
new AnalysisCapabilityUnavailableError(
active.route.binding?.identity.id ?? active.route.identity.id,
name,
capability?.reason ?? "operation is not declared by this provider",
),
);
}
const profile =
active.profile !== null &&
(capability === undefined ||
capability.provider.id === active.profile.provider.id)
? active.profile
: undefined;
const cacheable =
profile !== undefined &&
isSnapshotCacheable(name, capability, arguments_);
const cached = cacheable
? this.#snapshot.lookup(active.target, profile, name, arguments_)
: undefined;
const prepared = prepareSessionExecution({
active: this.#active,
operation: name,
parameters: arguments_,
unboundOperationError: (operation, route) =>
this.#providerRouter.unboundOperationError(operation, route),
lookupSnapshot: (target, profile, operation, parameters) =>
this.lookupSnapshot(target, profile, operation, parameters),
});
if (!prepared.ok) return prepared;
const { active, capability, profile, cacheable, cached } = prepared.value;
if (cached !== undefined) return ok(cached);
const call = active.client.execute(name, arguments_, options);
this.#calls.add(call);
@@ -669,8 +284,8 @@ export class BinarySession implements BinarySessionPort {
const result = await call;
const profiled = commitExecutionProfile(name, result, profile);
this.#observeRuntimeAvailability(name, profiled);
if (profiled.ok && cacheable)
this.#snapshot.record({
if (profiled.ok && cacheable && profile !== undefined)
this.recordSnapshot({
target: active.target,
profile,
operation: name,
@@ -678,8 +293,7 @@ export class BinarySession implements BinarySessionPort {
execution: profiled.value,
});
else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
this.#snapshot.clear();
this.#snapshotInvalidated = true;
this.invalidateSnapshot();
}
return profiled;
} finally {
@@ -859,33 +473,3 @@ const commitExecutionProfile = (
analysisProfile: structuredClone(profile),
});
};
const capabilityStatus = (
descriptor: Omit<CapabilityDescriptor, "available" | "reason"> & {
readonly available: boolean;
readonly reason: string | null;
},
) => ({
operation: descriptor.operation,
available: descriptor.available,
reason: descriptor.reason,
input_contract_version: descriptor.inputContractVersion,
output_contract_version: descriptor.outputContractVersion,
pagination: descriptor.pagination,
exhaustive: descriptor.exhaustive,
effects: {
mutates_artifact: descriptor.effects.mutatesArtifact,
launches_process: descriptor.effects.launchesProcess,
may_show_ui: descriptor.effects.mayShowUi,
may_access_network: descriptor.effects.mayAccessNetwork,
may_write_filesystem: descriptor.effects.mayWriteFilesystem,
changes_permissions: descriptor.effects.changesPermissions,
requires_root: descriptor.effects.requiresRoot,
},
limits: {
max_results: descriptor.limits.maxResults,
max_payload_bytes: descriptor.limits.maxPayloadBytes,
timeout_ms: descriptor.limits.timeoutMs,
},
limitations: [...descriptor.limitations],
});