Files
rea/src/kuna/KunaTargetCommands.ts
sharif 2dea2c2038 feat(kuna): admit PE/COFF, and forward the engine's spec variables (#15058)
* kuna: admit PE/COFF and forward the engine's spec variables

PE x64 is the class kuna handles and no other provider here does; its .pdata is a
better boundary source than discovery (430,906 discovered against 299,257
.pdata extents on one 120 MB image). Admission is the format check only — kuna
opens at the header base itself.

A source-built kuna also finds its compiled specs through KUNA_SPECS or
SLEIGHHOME, and the child environment carried only HOME/XDG_CACHE_HOME/NO_COLOR,
so a build install failed with 'Could not find .sla' and it read as a target
problem. Both are forwarded when set; a release kuna carries its specs and is
unaffected.

Adds the env test, flips the PE admission assertion, and says both in the
provider doc.

* chore: rerun checks

* fix(kuna): bind selected spec trees into the child and the cache

Forward KUNA_SPECS and SLEIGHHOME from the environment captured for the
provider, not from the ambient process. Hash each selected tree into the
analysis profile and export key so an in-place rebuild cannot reuse an
older result, and give a tree that cannot be hashed its own inspection
fence.

* fix(kuna): revalidate spec trees at launch and admit only x86-64 PE

The session kept the first specification digest, so a later export could
read a rebuilt tree and publish it under the earlier key. Each command
and export now hashes the selected trees again and keys the result with
that read; a tree that cannot be confirmed becomes an unknown identity
with a new reuse fence.

Directory close failures are retained on the caller's resource scope, and
the entry cap stops the directory read instead of buffering every name.
PE admission is x86-64; other PE architectures are refused.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* style(kuna): format the launch-revalidation changes

oxfmt --check rejected KunaProjectCache, KunaSessionClient, KunaSpecIdentity,
and the spec identity test. Apply the repository formatter.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(kuna): own spec identity once per launching operation

Compute one specification snapshot inside the session's classified
failure boundary and use that value for the cache key, the close key,
the profile, and the launch. Cached answers from an adopted project do
not walk the tree again. A tree that differs from the committed profile
is refused and the adopted reader is dropped. Directory close retains
one lease, and the session dialect keeps that cleanup on the classified
error.

Delete the extra refreshes in project build and command launch.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(kuna): check spec identity when a child spawns

Drop the operation allowlist. Each operation carries one memoized
confirmation, and runKunaCommand runs it under that command's deadline
before spawn. An unidentifiable tree reuses the fence minted for the
resolved profile, so the export key matches the profile BinarySession
commits. Relative spec paths are resolved from REA's working directory
when they are selected. A spec-file close keeps the lease the hook
returns, and installation retention is keyed by the original owner.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(kuna): keep spec-scan leases with the spawn owner

A shared export was retaining a failed spec close on the client that
started the build. That client can close while another client still
waits, and its close does not join the scan. The scan now runs in the
cache scope and the lease it returns is the cache's hash lease, so
close and settled can still release it. A client-owned command keeps
the lease in that command's scope.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(kuna): isolate each spec scan's signal and deadline

Spawns still share one identity result, but each waits on its own abort,
budget, and cleanup owner. The child timeout is whatever budget remains
after the scan and names the Kuna timeout setting.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* test(analysis-view): accept either oversized-page parent recovery

Source tests merge this branch with main, whose fixed-allowance recovery
no longer says "caller-supplied bundle".

Co-authored-by: morluto <morluto@users.noreply.github.com>

* test(views): drop recovery-prose lock on oversized route refusal

* fix(kuna): bound installation spec reads by the function timeout

identifyKunaExternalSpecs requires the caller's deadline. Inspection uses
REA_KUNA_TIMEOUT_MS, or the version-probe deadline when that timeout cannot
be read, and reports AnalysisTimeoutError.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(kuna): own spec scans through close and register spec roots

A cancelled wait keeps the physical spec read on the command or export
scope until its close settles. Setup and doctor copy an explicit
KUNA_SPECS or SLEIGHHOME into the client registration.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(kuna): retry a clean spec timeout and re-list walked directories

A spec-read timeout keeps a failed close's lease. A clean installation
timeout is not reused, so the next settings scan again. The walk re-lists
each directory and refuses the digest when the name set changed.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(kuna): keep spec-scan waits bounded and save absolute spec roots

The caller's wait ends at its deadline while the scope still owns the
read. Setup stores KUNA_SPECS and SLEIGHHOME as absolute paths.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* refactor(kuna): verify spec trees inline at each spawn

Replace the shared, detached per-operation spec scan in KunaSessionClient,
and the ownSpecScan plumbing that kept it owned, with an inline check in
runKunaCommand beside the executable-digest check. Each spawn reads the
tree under its own signal, deadline and cleanup owner, so the scan cannot
outlive the request or the shutdown that admitted it.

- Route every Kuna deadline timeout, including the spec-read timeout and
  its cleanup facts, through one kunaDeadlineTimeout owner.
- Move spec-variable selection into KunaConfiguration, its only reader.
- Pass an owner cancellation reason to the scan timer and read the
  function timeout through readRuntimeSetting (architecture guards).
- Cover a spec-file close failure that coincides with the scan timeout.

* fix(kuna): report late spec scans as timeouts and keep empty selections

- Check the deadline after the final directory read and close, so a scan
  that finishes past its budget is a timeout, not an identified tree.
- Convert only a deadline-stopped read to a timeout; an earlier physical
  failure keeps its cause beside the cleanup it left.
- Keep an explicitly empty KUNA_SPECS or SLEIGHHOME empty in setup and
  doctor registrations instead of resolving it to the working directory.

* test(kuna): remove wall-clock timing from spec deadline tests

- Observe the timeout the strings child is granted instead of asserting
  elapsed time; the scan delay must come out of that grant. A control that
  gives the child the full budget fails the test.
- Block the failing spec close on the scan's own deadline signal, with a
  test-owned release, instead of racing a fixed delay against a 20 ms
  deadline.

* fix(kuna): keep launch directory cleanup and report doctor spec timeouts

- A spec directory whose close failed during a launch scan now reports its
  retained cleanup through kunaRetainedResourceCleanupError instead of a
  plain adapter error, so the command reports cleanupIncomplete until its
  scope retries the handle.
- Doctor projects a spec read that exceeds kuna.function_timeout_ms into a
  failed Kuna version check with the timeout's recovery, instead of
  aborting the doctor run.
- Narrow the granted child timeout in the deadline test (CI typecheck).

---------

Co-authored-by: sharif <sharif@localhost>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-29 22:51:59 +00:00

490 lines
16 KiB
TypeScript

import {
artifactFileCleanupError,
ArtifactFileCleanupFailure,
artifactFilePrimaryFacts,
bindArtifactFileCleanup,
ArtifactResourceScope,
AnalysisCleanupLease,
AnalysisCleanupLeaseGroup,
ArtifactReaderFailure,
} from "../resources/index.js";
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
import {
retainProcessInspectionCleanup,
processInspectionCancellationError,
} from "../providers/OwnedCommandCleanup.js";
import { basename, join } from "node:path";
import { realpath } from "node:fs/promises";
import type { Writable } from "node:stream";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisArtifactChangedError,
cancelledBy,
carriedReason,
OwnerCancellation,
} from "../domain/analysisErrorCore.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import {
analysisErrorWithCleanupDependencies,
providerCleanupErrorFromFailures,
} from "../domain/analysisErrorCleanup.js";
import { err, ok, type Result } from "../domain/result.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js";
import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
import {
copyAndHash,
runKunaCommand,
type KunaInputPrefix,
type KunaProcessLauncher,
} from "./KunaCommand.js";
import type { KunaDeadline } from "./KunaConfiguration.js";
import type { KunaInstallation } from "./KunaInstallation.js";
import { KUNA_PROVIDER_ID } from "./KunaRelease.js";
import type { KunaRunRelease } from "./KunaRunSlots.js";
import {
classifyProviderFailure,
type ProviderFailureDialect,
} from "../providers/classifyProviderFailure.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { errorMessage } from "../kernel/errorMessage.js";
interface WorkspaceRoot {
readonly root: PrivateRuntimeRoot;
readonly cleanup: AnalysisCleanupLease;
}
interface Workspace extends WorkspaceRoot {
readonly input: string;
readonly bytes: number;
/** Leading bytes of the input kept while it was copied and hashed. */
readonly prefix: Buffer;
}
/** The private input's size and the leading bytes kept from its verified copy. */
export interface KunaInputHead {
readonly bytes: number;
readonly prefix: Buffer;
}
export interface KunaTargetCommandSnapshot extends ProviderProcessSnapshot {
/** Canonical, digest-checked private input used by this command. */
readonly input: string;
}
export interface KunaTargetCommandRequest {
readonly installation: KunaInstallation;
readonly operation: string;
readonly arguments: (input: string) => readonly string[];
readonly outputBytes: number;
/** Parses stdout as it arrives instead of buffering it in the snapshot. */
readonly stdout?: Writable;
readonly deadline: KunaDeadline;
readonly signal: AbortSignal;
/** Admission remains owned until the native process is proven stopped. */
readonly releaseRun?: KunaRunRelease;
}
/** Own the digest-checked target copy and every command that can still use it. */
const workspaceCopyFailure = (cause: unknown) =>
new ProviderAdapterError(KUNA_PROVIDER_ID, "kuna:workspace", { cause });
/**
* How a failed workspace copy is reported. The shared classifier keeps typed
* failures and the copy's cancellation; a copy whose descriptor cleanup failed
* reports that cleanup with the copy's own failure as its primary.
*/
const KUNA_WORKSPACE_COPY_DIALECT: ProviderFailureDialect = {
providerId: KUNA_PROVIDER_ID,
operation: "kuna:workspace",
readCleanup: (read, primary) => {
// A completed copy's cleanup is the only failure; an unfinished plain
// read keeps its own failure as the primary.
const reported =
primary ??
(read instanceof ArtifactFileCleanupFailure
? undefined
: workspaceCopyFailure(artifactFilePrimaryFacts(read).cause));
const error = new ProviderCleanupError(
KUNA_PROVIDER_ID,
read.cleanup.resources,
{ reason: read.cleanup.reason },
{
operation: "kuna:workspace",
cause: read,
...(reported === undefined ? {} : { cleanupPrimary: reported }),
},
);
bindArtifactFileCleanup(read, error);
return error;
},
unclassified: (cause) =>
workspaceCopyFailure(artifactFilePrimaryFacts(cause).cause),
};
export class KunaTargetCommands {
readonly #resources = new ArtifactResourceScope();
readonly #retained: {
readonly error: ProviderCleanupError;
readonly process: AnalysisCleanupLease;
}[] = [];
readonly #roots: WorkspaceRoot[] = [];
#workspace: Promise<Result<Workspace, AnalysisError>> | undefined;
#closeAttempt: Promise<Result<null, ProviderCleanupError>> | undefined;
#closing = false;
constructor(
private readonly target: BinaryTarget,
private readonly lifetime: {
readonly signal: AbortSignal;
readonly launcher?: KunaProcessLauncher;
/** Leading bytes in-process readers need, kept while the copy is hashed. */
readonly inputPrefix?: KunaInputPrefix;
},
) {}
run(
request: KunaTargetCommandRequest,
): Promise<Result<KunaTargetCommandSnapshot, AnalysisError>> {
if (this.#closing || request.signal.aborted) {
request.releaseRun?.();
return Promise.resolve(
err(
cancelledBy(
request.operation,
request.signal.aborted
? request.signal
: OwnerCancellation.ownerClosed,
),
),
);
}
return this.#run(request);
}
/** Establish the immutable input before waiting for a foreground run slot. */
prepare(): Promise<Result<null, AnalysisError>> {
if (this.#closing || this.lifetime.signal.aborted)
return Promise.resolve(
err(
cancelledBy(
"kuna:workspace",
this.lifetime.signal.aborted
? this.lifetime.signal
: OwnerCancellation.ownerClosed,
),
),
);
return this.#admit("kuna:workspace", () =>
this.#ensureWorkspace().then((workspace) =>
workspace.ok ? ok(null) : workspace,
),
);
}
/**
* The verified input's size and kept leading bytes, establishing the input
* first. They come from the stream that was hashed, so they are exactly
* the bytes Kuna analyzes, and reading them opens no file.
*/
inputHead(operation: string): Promise<Result<KunaInputHead, AnalysisError>> {
if (this.#closing || this.lifetime.signal.aborted)
return Promise.resolve(
err(
cancelledBy(
operation,
this.lifetime.signal.aborted
? this.lifetime.signal
: OwnerCancellation.ownerClosed,
),
),
);
return this.#admit(operation, async () => {
const workspace = await this.#ensureWorkspace();
if (!workspace.ok) return workspace;
const { bytes, prefix } = workspace.value;
return ok({ bytes, prefix });
});
}
async #run(
request: KunaTargetCommandRequest,
): Promise<Result<KunaTargetCommandSnapshot, AnalysisError>> {
const { releaseRun, ...options } = request;
let retained = false;
try {
return await this.#admit(request.operation, async () => {
const workspace = await this.#ensureWorkspace();
if (!workspace.ok) return workspace;
let failedHashClose:
| {
readonly owner: OwnedFileHandle;
readonly lease: AnalysisCleanupLease;
}
| undefined;
const outcome = await runKunaCommand({
...options,
arguments: request.arguments(workspace.value.input),
workspace: workspace.value.root.path,
timeoutMs: request.deadline.ms,
launcher: this.lifetime.launcher,
retainFailedFileClose: (owner, resource) => {
const lease = new AnalysisCleanupLease(
() => owner.close(),
[resource],
);
this.#resources.retain({ kind: "lease", resource, lease });
if (owner instanceof OwnedFileHandle)
failedHashClose = { owner, lease };
return lease;
},
});
if (outcome.kind === "retained") {
const process = new AnalysisCleanupLease(async () => {
const stopped = await outcome.owner?.stop();
if (stopped === undefined)
throw new Error("Kuna process ownership remains unresolved");
if (stopped.status === "incomplete")
throw new Error(stopped.reason, { cause: stopped });
releaseRun?.();
}, outcome.processResources);
new AnalysisCleanupLeaseGroup(outcome.error, [
process,
workspace.value.cleanup,
]);
this.#retained.push({ error: outcome.error, process });
retained = true;
return err(outcome.error);
}
const fileFailure =
outcome.kind === "failed" ? outcome.fileCleanupFailure : undefined;
if (outcome.kind === "ok")
return ok({ ...outcome.snapshot, input: workspace.value.input });
if (
fileFailure !== undefined &&
fileFailure.owner === failedHashClose?.owner
)
failedHashClose.lease.bindCleanupError(outcome.error);
return err(outcome.error);
});
} finally {
if (!retained) releaseRun?.();
}
}
/** Called after the session signal aborts; failures keep their retry owners. */
close(): Promise<Result<null, ProviderCleanupError>> {
this.#closing = true;
this.#closeAttempt ??= this.#closeCommands().finally(() => {
this.#closeAttempt = undefined;
});
return this.#closeAttempt;
}
async #closeCommands(): Promise<Result<null, ProviderCleanupError>> {
const failures: ProviderCleanupError[] = [];
try {
await this.#resources.close();
} catch (cause: unknown) {
const observation = ArtifactReaderFailure.cleanupObservation(
cause,
"Kuna command file descriptor",
);
const failure = new ProviderCleanupError(
KUNA_PROVIDER_ID,
observation.resources,
{ reason: observation.reason },
{ cause },
);
bindArtifactFileCleanup(cause, failure);
failures.push(failure);
}
for (const retained of [...this.#retained]) {
try {
await retained.process.release();
this.#retained.splice(this.#retained.indexOf(retained), 1);
} catch {
// The exact process lease remains available for the next retry.
}
}
failures.push(...this.#retained.map(({ error }) => error));
const workspace = await this.#workspace;
if (this.#retained.length === 0) {
if (workspace?.ok === true) {
this.#roots.push(workspace.value);
this.#workspace = undefined;
}
for (const owned of [...this.#roots])
try {
await owned.cleanup.release();
this.#roots.splice(this.#roots.indexOf(owned), 1);
} catch (cause: unknown) {
const failure = new ProviderCleanupError(
KUNA_PROVIDER_ID,
[owned.root.path],
{ reason: errorMessage(cause) },
{ cause },
);
owned.cleanup.bindCleanupError(failure);
failures.push(failure);
}
}
return failures.length === 0
? ok(null)
: err(
providerCleanupErrorFromFailures(
KUNA_PROVIDER_ID,
failures,
failures
.map((failure) =>
String(failure.diagnostics?.["reason"] ?? failure.message),
)
.join("; "),
{
operation: "close_binary",
message: "Kuna command cleanup remains incomplete",
},
),
);
}
async #admit<T>(
operation: string,
work: () => Promise<Result<T, AnalysisError>>,
): Promise<Result<T, AnalysisError>> {
try {
return await this.#resources.run(work);
} catch (cause: unknown) {
const fileCleanup = artifactFileCleanupError(
cause,
KUNA_PROVIDER_ID,
operation,
);
if (fileCleanup !== undefined) return err(fileCleanup);
if (this.#closing && cause instanceof ArtifactReaderFailure)
return err(cancelledBy(operation, carriedReason(cause)));
throw cause;
}
}
async #ensureWorkspace(): Promise<Result<Workspace, AnalysisError>> {
const pending = (this.#workspace ??= this.#createWorkspace());
const result = await pending;
if (
this.#workspace === pending &&
!result.ok &&
!result.error.cleanupIncomplete
)
this.#workspace = undefined;
return result;
}
async #createWorkspace(): Promise<Result<Workspace, AnalysisError>> {
let owned: WorkspaceRoot | undefined;
try {
const root = await PrivateRuntimeRoot.create({ prefix: "rea-kuna-" });
const copyResources = new ArtifactResourceScope();
owned = {
root,
cleanup: new AnalysisCleanupLease(async () => {
await copyResources.close();
await root.close();
}, [root.path]),
};
const input = join(root.path, basename(this.target.path));
let copied: Awaited<ReturnType<typeof copyAndHash>>;
try {
copied = await copyAndHash(this.target.path, input, {
signal: this.lifetime.signal,
resources: copyResources,
...(this.lifetime.inputPrefix === undefined
? {}
: { keep: this.lifetime.inputPrefix }),
});
} catch (cause: unknown) {
return await this.#workspaceFailure(
classifyProviderFailure(cause, KUNA_WORKSPACE_COPY_DIALECT),
owned,
);
}
if (copied.sha256 !== this.target.sha256)
return await this.#workspaceFailure(
new AnalysisArtifactChangedError(
"kuna:workspace",
this.target.path,
"the target no longer matches the digest selected for analysis",
),
owned,
);
try {
await prepareProcessOwnershipInspection(this.lifetime.signal);
} catch (cause: unknown) {
const primary =
processInspectionCancellationError(cause, "kuna:workspace") ??
new ProviderAdapterError(KUNA_PROVIDER_ID, "kuna:workspace", {
cause,
});
throw retainProcessInspectionCleanup(
cause,
primary,
this.#resources,
"kuna:workspace",
);
}
return ok({
...owned,
input: await realpath(input),
bytes: copied.bytes,
prefix: copied.prefix,
});
} catch (cause: unknown) {
return this.#workspaceFailure(
cause instanceof AnalysisError
? cause
: new ProviderAdapterError(KUNA_PROVIDER_ID, "kuna:workspace", {
cause,
userMessage: `Kuna workspace failed: ${errorMessage(cause)}`,
}),
owned,
);
}
}
/** Rollback and the original outcome share the exact root cleanup lease. */
async #workspaceFailure(
primary: AnalysisError,
owned: WorkspaceRoot | undefined,
): Promise<Result<never, AnalysisError>> {
let failure = primary;
if (owned !== undefined) {
try {
await owned.cleanup.release();
} catch (cause: unknown) {
this.#roots.push(owned);
const cleanup = new ProviderCleanupError(
KUNA_PROVIDER_ID,
[owned.root.path],
{ reason: errorMessage(cause) },
{ cause, operation: "kuna:workspace" },
);
owned.cleanup.bindCleanupError(cleanup);
failure = analysisErrorWithCleanupDependencies(
primary,
cleanup,
"kuna:workspace",
);
}
}
return err(
this.lifetime.signal.aborted
? analysisErrorWithCancellation(
failure,
cancelledBy("kuna:workspace", this.lifetime.signal),
)
: failure,
);
}
}