mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 14:59:05 +00:00
* feat(firmware): disassemble ARM and Xtensa PC-relative literal-pool MMIO loads Disassemble PC-relative literal-pool load instructions (`arm-thumb` 16-bit LDR and 32-bit Thumb-2 LDR.W, `arm-a32` LDR, and `xtensa` L32R) from local firmware images at an explicit `base_address` without target execution: - Byte-granular `PoolByteBitset` suppresses forward and backward pool byte ranges even at `4k + 2` unaligned file offsets (`base_address` ending in 2). - Two-pass Xtensa pool discovery preserves `L32R` alignment after leading or interleaved 4-byte literal pools and preserves valid `21 36 01` encodings. - Indexed `O(log M)` CMSIS-SVD disjoint `<addressBlock>`/`<register>` matching with cycle-safe multi-hop `derivedFrom` resolution, `mapped_image` bounds precedence, exact ARMv7-M/v8-M SCS sub-blocks, and `arm-a32` SoC neutrality. - Cooperative `setImmediate` event-loop yields with `AbortSignal` cancellation, complete retained Evidence with `detail: "summary"` and `inspect_analysis_view` (`firmware-literal-pools`), `max_svd_nodes` parameter budget, and field-specific `invalid_request` validation. * fix(firmware): bound SVD and candidate memory, preserve overshadowed loads, and report required_value * fix(firmware): resolve SVD derivedFrom chains iteratively and restore lifecycle test title * fix(firmware): bound Xtensa trace and SVD representation memory, make Evidence cooperative, and preserve unaligned literal loads * fix(firmware): retain completed literal-pool scans on late cancellation and avoid repeated SVD string hashing * fix(firmware): walk SVD register clusters, sweep dense overlaps linearly, and preserve XML depth recovery * fix(firmware): enforce profile-wide cooperative SVD cluster expansion budget and sync schema * fix(firmware): pre-parse SVD cluster templates, inherit defaults, and keep Xtensa framing * fix(firmware): share inherited SVD template chains and count compact arrays as single intervals * fix(firmware): replace SVD override chain links with persistent O(log K) treap * fix(firmware): default max_references to the representation-bounded maximum The IROM segment of the MicroPython 1.24.1 ESP32 image resolves 35,179 literal-pool loads. A default call scanned it and then refused at 16,384 references, so the agent had to repeat the whole scan with a larger max_references. The count is checked after scanning, and max_representation_bytes already bounds the Evidence these rows build. The default is now the maximum; the same image completes in 1.4 s with a 12 MB complete result. Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * refactor(firmware): use the max_references maximum as its default directly Knip reported DEFAULT_LITERAL_POOL_MAX_REFERENCES as a duplicate export of MAX_LITERAL_POOL_REFERENCES. The budget now names the maximum as its default, and the provider test reads the default from the budget. Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> * fix(firmware): preserve inherited SVD register widths and addressBlock spans --------- Co-authored-by: gensokyo-dev <gensokyo-dev@users.noreply.github.com> Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
231 lines
7.4 KiB
TypeScript
231 lines
7.4 KiB
TypeScript
import { z } from "zod";
|
|
import {
|
|
primaryAnalysisError,
|
|
type AnalysisError,
|
|
type AnalysisErrorOptions,
|
|
type AnalysisPartialObservation,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
AnalysisOutputError,
|
|
cancelledBy,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import type { Evidence } from "../domain/evidence.js";
|
|
import {
|
|
freezeJsonSnapshot,
|
|
isImmutableJsonSnapshot,
|
|
} from "../domain/immutableJson.js";
|
|
import { jsonValueSchema } from "../domain/jsonValue.js";
|
|
import { analysisOperationInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import type {
|
|
AnalysisExecution,
|
|
ExecutionOptions,
|
|
} from "../ports/AnalysisProvider.js";
|
|
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
|
|
|
|
/** Validated caller-selected request carrying its operation input. */
|
|
export interface ProviderOperationRequest {
|
|
readonly input: unknown;
|
|
}
|
|
|
|
/** Provider boundary executing one validated caller-selected request. */
|
|
export interface ProviderOperationPort<
|
|
TRequest extends ProviderOperationRequest,
|
|
> {
|
|
execute(
|
|
request: TRequest,
|
|
options?: ExecutionOptions,
|
|
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
|
}
|
|
|
|
/**
|
|
* Shared CLI/MCP admission, execution, and Evidence composition for
|
|
* single-request providers. The caller retains its operation vocabulary and
|
|
* confidence; this normalizes cancellation, input validation, and Evidence
|
|
* assembly once instead of per provider.
|
|
*/
|
|
export const executeProviderOperation = async <
|
|
TRequest extends ProviderOperationRequest,
|
|
>(
|
|
operation: string,
|
|
input: unknown,
|
|
options: ExecutionOptions | undefined,
|
|
schema: z.ZodType<TRequest>,
|
|
provider: ProviderOperationPort<TRequest>,
|
|
confidence: "observed" | "derived",
|
|
buildEvidence?: (request: TRequest, execution: AnalysisExecution) => Evidence,
|
|
): Promise<Result<Evidence, AnalysisError>> => {
|
|
if (options?.signal?.aborted)
|
|
return err(cancelledBy(operation, options.signal));
|
|
const request = schema.safeParse({ operation, input });
|
|
if (!request.success)
|
|
return err(
|
|
analysisOperationInputErrorFromIssues(
|
|
operation,
|
|
request.error.issues,
|
|
input,
|
|
request.error,
|
|
),
|
|
);
|
|
const executed = await provider.execute(request.data, options);
|
|
if (!executed.ok) return executed;
|
|
const evidence =
|
|
buildEvidence !== undefined
|
|
? buildEvidence(request.data, executed.value)
|
|
: createAnalysisExecutionEvidence(
|
|
operation,
|
|
request.data.input,
|
|
executed.value,
|
|
confidence,
|
|
);
|
|
return completeProviderEvidence(evidence, options?.signal);
|
|
};
|
|
|
|
/**
|
|
* Shared single-request provider service wrapping {@link executeProviderOperation}
|
|
* and optional provider cleanup. Replaces per-provider pass-through service classes.
|
|
*/
|
|
export class ProviderOperationService<
|
|
TOperation extends string,
|
|
TRequest extends ProviderOperationRequest,
|
|
TPort extends ProviderOperationPort<TRequest> =
|
|
ProviderOperationPort<TRequest>,
|
|
> {
|
|
constructor(
|
|
readonly provider: TPort,
|
|
private readonly schema: z.ZodType<TRequest>,
|
|
private readonly confidence:
|
|
| "observed"
|
|
| "derived"
|
|
| ((operation: TOperation) => "observed" | "derived") = "observed",
|
|
private readonly buildEvidence?: (
|
|
request: TRequest,
|
|
execution: AnalysisExecution,
|
|
) => Evidence,
|
|
) {}
|
|
|
|
close(): Promise<void> {
|
|
return (
|
|
(this.provider as { close?: () => Promise<void> }).close?.() ??
|
|
Promise.resolve()
|
|
);
|
|
}
|
|
|
|
execute(
|
|
operation: TOperation,
|
|
input: unknown,
|
|
options?: ExecutionOptions,
|
|
): Promise<Result<Evidence, AnalysisError>> {
|
|
const resolvedConfidence =
|
|
typeof this.confidence === "function"
|
|
? this.confidence(operation)
|
|
: this.confidence;
|
|
return executeProviderOperation(
|
|
operation,
|
|
input,
|
|
options,
|
|
this.schema,
|
|
this.provider,
|
|
resolvedConfidence,
|
|
this.buildEvidence,
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Classify completion after Evidence assembly, preserving facts on late abort. */
|
|
export const completeProviderEvidence = (
|
|
evidence: Evidence,
|
|
signal?: AbortSignal,
|
|
capturedOutput?: AnalysisErrorOptions["capturedOutput"],
|
|
): Result<Evidence, AnalysisCancelledError> => {
|
|
if (signal?.aborted)
|
|
return err(
|
|
cancelledBy(evidence.operation, signal, {
|
|
partialObservation: evidence,
|
|
...(capturedOutput === undefined ? {} : { capturedOutput }),
|
|
}),
|
|
);
|
|
return ok(evidence);
|
|
};
|
|
|
|
/** Select the observation visible on a failure, then on its primary owner. */
|
|
export const artifactFailureObservation = (failure: AnalysisError) =>
|
|
failure.partialObservation ??
|
|
primaryAnalysisError(failure).partialObservation;
|
|
|
|
/** Share projected partial Evidence with cleanup owners retaining the same source or no observation. */
|
|
export const retainProjectedArtifactObservation = (
|
|
failure: AnalysisError,
|
|
source: AnalysisPartialObservation | undefined,
|
|
evidence: AnalysisPartialObservation,
|
|
includeEmptyOwners = true,
|
|
): void => {
|
|
for (
|
|
let owner: AnalysisError | undefined = failure;
|
|
owner !== undefined;
|
|
owner = owner.cleanupPrimary
|
|
)
|
|
if (
|
|
owner.partialObservation === source ||
|
|
(includeEmptyOwners && owner.partialObservation === undefined)
|
|
)
|
|
owner.partialObservation = evidence;
|
|
};
|
|
|
|
/** Use the admitted Evidence on every failure retaining the same report. */
|
|
export const retainCompletedArtifactEvidence = (
|
|
error: AnalysisError,
|
|
evidence: AnalysisPartialObservation,
|
|
): void => {
|
|
const source = error.partialObservation;
|
|
if (source !== undefined)
|
|
retainProjectedArtifactObservation(error, source, evidence, false);
|
|
};
|
|
|
|
/**
|
|
* Retain an incomplete observation when projection can serialize it.
|
|
* A JSON partial is replaced by one frozen snapshot, so a later mutation
|
|
* cannot make projection throw and projection does not copy it again.
|
|
* A partial that is not JSON is cleared from the returned error and from
|
|
* every cleanup primary projection can select later. Each cleared error
|
|
* records an output failure, leaving cancellation or timeout primary.
|
|
*/
|
|
export const keepIncompleteObservation = (
|
|
error: AnalysisError,
|
|
operation: string,
|
|
reason: string,
|
|
): AnalysisError => {
|
|
const seen = new Set<AnalysisError>();
|
|
// One source object can sit on a wrapper and its cleanup primary.
|
|
const judged = new Map<object, AnalysisPartialObservation | undefined>();
|
|
let current: AnalysisError | undefined = error;
|
|
while (current !== undefined && !seen.has(current)) {
|
|
seen.add(current);
|
|
const partial = current.partialObservation;
|
|
if (
|
|
partial !== undefined &&
|
|
!isImmutableJsonSnapshot(partial) &&
|
|
typeof partial === "object"
|
|
) {
|
|
// safeParse clones only after validation succeeds. Freeze that copy once.
|
|
let snapshot = judged.get(partial);
|
|
if (!judged.has(partial)) {
|
|
const parsed = jsonValueSchema.safeParse(partial);
|
|
snapshot = parsed.success
|
|
? (freezeJsonSnapshot(parsed.data) as AnalysisPartialObservation)
|
|
: undefined;
|
|
judged.set(partial, snapshot);
|
|
}
|
|
if (snapshot === undefined) {
|
|
current.partialObservation = undefined;
|
|
current.retainSecondaryFailure(
|
|
new AnalysisOutputError(operation, reason),
|
|
);
|
|
} else current.partialObservation = snapshot;
|
|
}
|
|
current = current.cleanupPrimary;
|
|
}
|
|
return error;
|
|
};
|