feat(sqlite): inspect offline snapshots with selective evidence (#2271)

Add offline SQLite database/WAL inspection through the shared CLI/MCP.

Use compact inventory, selected-table schema, exact ordered columns and
bounded row samples while preserving source identity and lossless values.
Retain completed Evidence through late cancellation and private-root cleanup
failures, bound concurrent inspections, and recheck journal validity after
acquisition. Reuse prepared CI runtime artifacts across supported Node lines.

Co-authored-by: Y0UW1SH <29498139+Y0UW1SH@users.noreply.github.com>
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
Ysopwnable
2026-10-12 18:33:23 +00:00
committed by GitHub
co-authored by Y0UW1SH
parent 916ac97bf9
commit aeee5074d1
59 changed files with 5757 additions and 24 deletions
+10
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
import type {
OptionalProviderLoadFailures,
OptionalProviderLoadFailure,
@@ -341,6 +342,15 @@ const workflowAvailabilityFor = ({
}: AvailabilityContext): Availability | null => {
if (name === "inspect_go_binary")
return { reason: "available", remediation: null };
if (name === "inspect_sqlite_database") {
const capability = sqliteDatabaseCapability(process.versions.node);
return capability.available
? { reason: "available", remediation: null }
: {
reason: "provider_unavailable",
remediation: capability.reason,
};
}
if (name === "trace_web_module_imports")
return {
reason: "available",
+11 -1
View File
@@ -4,6 +4,9 @@ import { createServerIdentity } from "../serverIdentity.js";
import { silentLogger } from "../logger.js";
import type { Logger } from "pino";
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
import { providerCapabilitySet } from "../contracts/toolOutputSchemaPrimitives.js";
import { providerCapabilitySets } from "./binary/BinarySessionStatus.js";
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
/** Read target-free provider status and operation availability. */
export const runSessionStatus = async (
@@ -17,8 +20,15 @@ export const runSessionStatus = async (
if (!config.ok) return { error: projectAnalysisError(config.error) };
const session = await dependencies.createBinarySession(config.value, logger);
try {
const status = jsonObjectSchema.parse(session.status());
return {
...jsonObjectSchema.parse(session.status()),
...status,
capabilities: [
...providerCapabilitySet.array().parse(status.capabilities),
...providerCapabilitySets([
sqliteDatabaseCapability(process.versions.node),
]),
],
server_identity: createServerIdentity({
startedAt: new Date().toISOString(),
}),
@@ -198,15 +198,19 @@ type CapabilityAvailabilityCode = Exclude<
CapabilityDescriptor["availabilityCode"],
undefined
>;
type CapabilityProjection = Omit<CapabilityDescriptor, "available" | "reason"> &
(
// Wire capability projection also covers target-free operations outside binary routing.
type CapabilityProjection = Omit<
CapabilityDescriptor,
"operation" | "available" | "reason"
> & { readonly operation: string } & (
| { readonly available: true; readonly reason: null }
| { readonly available: false; readonly reason: string }
);
type ProviderCapabilityGroup = ProviderCapabilitySet["groups"][number];
/** Group inline capability facts without merging distinct providers or states. */
const providerCapabilitySets = (
/** Project provider descriptors once for binary and target-free status consumers. */
export const providerCapabilitySets = (
descriptors: readonly CapabilityProjection[],
): ProviderCapabilitySet[] => {
const providers = new Map<
@@ -0,0 +1,31 @@
import { expect, it } from "vitest";
import { expandProviderCapabilities } from "../../contracts/toolOutputSchemaPrimitives.js";
import { providerCapabilitySets } from "../binary/BinarySessionStatus.js";
import { sqliteDatabaseCapability } from "./SqliteDatabaseCapability.js";
it.each([
["22.23.1", false],
["24.11.0", false],
["24.14.9", false],
["24.15.0", true],
["25.1.0", false],
["26.0.0", true],
["24.15.0-rc.1", false],
["invalid", false],
])(
"reports SQLite inspection availability on Node %s as %s",
(version, available) => {
const [capability] = expandProviderCapabilities(
providerCapabilitySets([sqliteDatabaseCapability(version)]),
);
expect(capability).toMatchObject({
operation: "inspect_sqlite_database",
available,
reason: available
? null
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
availability_code: available ? null : "unsupported_version",
limitations: [expect.stringContaining("DatabaseSync.limits")],
});
},
);
@@ -0,0 +1,33 @@
import { satisfies } from "semver";
import { toolContract } from "../../contracts/toolContracts.js";
import { SQLITE_PROVIDER_IDENTITY } from "../../domain/sqlite/sqliteDatabase.js";
const SQLITE_RUNTIME_REQUIREMENT =
"SQLite inspection requires Node.js 24.x >=24.15 or 26+ with the native DatabaseSync.limits API. Other REA features retain their published runtime requirements. The inspection worker verifies the API before querying the snapshot.";
/** Discover inspection readiness without opening a database or starting a worker. */
export const sqliteDatabaseCapability = (nodeVersion: string) => {
const contract = toolContract("inspect_sqlite_database");
const facts = {
operation: contract.name,
provider: SQLITE_PROVIDER_IDENTITY,
effects: {
mutatesArtifact: contract.effects.mutatesTarget,
launchesProcess: contract.effects.launchesProcess,
mayShowUi: contract.effects.changesUiState,
mayAccessNetwork: contract.effects.accessesNetwork,
mayWriteFilesystem: contract.effects.writesFilesystem,
changesPermissions: false,
requiresRoot: false,
},
limitations: [SQLITE_RUNTIME_REQUIREMENT],
};
return satisfies(nodeVersion, "^24.15.0 || >=26.0.0")
? { ...facts, available: true as const, reason: null }
: {
...facts,
available: false as const,
reason: SQLITE_RUNTIME_REQUIREMENT,
availabilityCode: "unsupported_version" as const,
};
};
@@ -0,0 +1,17 @@
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { InspectSqliteDatabaseInput } from "../../domain/sqlite/sqliteDatabase.js";
import type { Result } from "../../domain/result.js";
/** Offline database inspection boundary shared by CLI and MCP. */
export interface SqliteDatabasePort {
/** Await and retry provider-owned snapshot cleanup. */
close?(): Promise<void>;
inspect(
input: InspectSqliteDatabaseInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,147 @@
import { expect, it } from "vitest";
import { SqliteDatabaseService } from "./SqliteDatabaseService.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { err } from "../../domain/result.js";
import { ok } from "../../domain/result.js";
import { createAnalysisExecution } from "../AnalysisProvider.js";
const fixture = () => ({
artifact: { path: "/selected.db", sha256: "a".repeat(64), bytes: 4096 },
wal: null,
engine: { name: "SQLite", version: "3.50.2" },
database_encoding: "UTF-8",
schema: {
scope: "inventory",
completeness: "complete",
tables: [],
indexes: [],
views: [],
triggers: [],
},
rows: null,
limitations: [],
});
const execution = (value: unknown) =>
createAnalysisExecution(
value,
{ id: "sqlite", name: "SQLite", version: "3.50.2" },
{
subject: { path: "/selected.db", sha256: "a".repeat(64), format: "file" },
locations: [{ kind: "artifact-path", path: "/selected.db" }],
},
);
it.each([
{ path: "relative.db" },
{ path: "/selected.db", approval: true },
{ path: "/selected.db", row_limit: 1 },
{ path: "/selected.db", table: 1 },
{ path: "/selected.db", table: "data", row_limit: 0 },
{
path: "/selected.db",
table: "data",
row_limit: Number.MAX_SAFE_INTEGER + 1,
},
])(
"rejects invalid SQLite selection before provider effects: %j",
async (input) => {
const service = new SqliteDatabaseService({
inspect: () => {
throw new Error("Invalid selection must not read a database");
},
});
expect(await service.inspect(input)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
},
);
it("preserves producer failures and rejects pre-cancelled requests before effects", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"rea-sqlite",
"inspect_sqlite_database",
"Selected worker could not start",
);
const service = new SqliteDatabaseService({
inspect: () => Promise.resolve(err(failure)),
});
expect(await service.inspect({ path: "/selected.db" })).toEqual(err(failure));
const signal = AbortSignal.abort();
const untouched = new SqliteDatabaseService({
inspect: () => {
throw new Error("Cancelled selection must not read a database");
},
});
expect(
await untouched.inspect({ path: "/selected.db" }, { signal }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it.each(["path", "digest", "subject", "wal", "table"])(
"rejects producer results with changed caller binding: %s",
async (problem) => {
const value = fixture();
if (problem === "path") value.artifact.path = "/other.db";
if (problem === "digest") value.artifact.sha256 = "b".repeat(64);
const observed = execution({
...value,
...(problem === "wal"
? { wal: { path: "/other.db-wal", sha256: "b".repeat(64), bytes: 32 } }
: {}),
});
const service = new SqliteDatabaseService({
inspect: () =>
Promise.resolve(
ok({
...observed,
...(problem === "subject" ? { subject: null } : {}),
}),
),
});
expect(
await service.inspect({
path: "/selected.db",
...(problem === "table" ? { table: "selected" } : {}),
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
},
);
it("preserves completed observed evidence when cancellation arrives after provider completion", async () => {
const value = fixture();
const service = new SqliteDatabaseService({
inspect: () => Promise.resolve(ok(execution(value))),
});
expect(await service.inspect({ path: "/selected.db" })).toMatchObject({
ok: true,
value: {
confidence: "observed",
subject: {
local_path: "/selected.db",
digest: { sha256: "a".repeat(64) },
},
normalized_result: value,
},
});
const controller = new AbortController();
const cancelled = new SqliteDatabaseService({
inspect: () => {
controller.abort();
return Promise.resolve(ok(execution(value)));
},
});
expect(
await cancelled.inspect(
{ path: "/selected.db" },
{ signal: controller.signal },
),
).toMatchObject({
ok: true,
value: { normalized_result: value },
});
});
@@ -0,0 +1,121 @@
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { SqliteDatabasePort } from "./SqliteDatabasePort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import {
createEvidence,
type Evidence,
type EvidenceSubjectTarget,
} from "../../domain/evidence.js";
import {
inspectSqliteDatabaseInputSchema,
sqliteDatabaseSchema,
type InspectSqliteDatabaseInput,
type SqliteDatabase,
SQLITE_ROW_LIMIT_DEFAULT,
sqliteSchemaScope,
sqliteInspectionParameters,
} from "../../domain/sqlite/sqliteDatabase.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
const OPERATION = "inspect_sqlite_database";
const matchesSelectedDatabase = (
report: SqliteDatabase,
input: InspectSqliteDatabaseInput,
subject: EvidenceSubjectTarget,
): boolean =>
report.artifact.path === input.path &&
subject.path === input.path &&
subject.sha256 === report.artifact.sha256 &&
subject.format === "file" &&
(report.wal === null || report.wal.path === `${input.path}-wal`) &&
report.schema.scope === sqliteSchemaScope(input) &&
(report.schema.scope !== "selected_table" ||
(report.schema.tables.length === 1 &&
report.schema.tables[0]?.name === input.table &&
report.schema.indexes.every((index) => index.table === input.table) &&
report.schema.triggers.every(
(trigger) => trigger.table === input.table,
) &&
report.schema.views.length === 0)) &&
(input.table === undefined
? report.rows === null
: report.rows?.table === input.table &&
report.rows.row_limit === (input.row_limit ?? SQLITE_ROW_LIMIT_DEFAULT) &&
(input.columns === undefined ||
(report.rows.columns.length === input.columns.length &&
report.rows.columns.every(
(name, index) => name === input.columns?.[index],
))));
/** Shared snapshot inspection and caller-selection validation for CLI and MCP. */
export class SqliteDatabaseService {
constructor(readonly provider: SqliteDatabasePort) {}
/** Await provider shutdown, retaining failed cleanup owners for retry. */
close(): Promise<void> {
return this.provider.close?.() ?? Promise.resolve();
}
/** Inspect an explicit database snapshot and preserve its original database/WAL identity. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const input = inspectSqliteDatabaseInputSchema.safeParse(rawInput);
if (!input.success)
return err(
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
if (!inspected.ok) return inspected;
const execution = inspected.value;
const report = sqliteDatabaseSchema.safeParse(execution.result);
if (
!report.success ||
execution.subject === null ||
!matchesSelectedDatabase(report.data, input.data, execution.subject)
)
return err(
new AnalysisOutputError(
OPERATION,
"SQLite adapter returned malformed data or changed the selected database identity/table/row limit.",
),
);
return ok(
createEvidence(execution.subject, execution.provider, {
operation: OPERATION,
parameters: sqliteInspectionParameters(input.data),
result: jsonValueSchema.parse(report.data),
...(execution.rawResult === null
? {}
: { rawResult: execution.rawResult }),
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
}),
);
}
}
+22 -1
View File
@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
import { constants, type BigIntStats } from "node:fs";
import { lstat, open, type FileHandle } from "node:fs/promises";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import type { ArtifactResourceScope } from "./ArtifactResourceScope.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
/** Filesystem boundary for stable reads, including deterministic replacement probes. */
export interface StableArtifactFileSystem {
@@ -42,6 +44,7 @@ export const readStableArtifact = async (
maximumBytes: number,
signal?: AbortSignal,
fileSystem: StableArtifactFileSystem = FILE_SYSTEM,
resourceScope?: ArtifactResourceScope,
): Promise<{ readonly bytes: Buffer; readonly sha256: string }> => {
signal?.throwIfAborted();
const before = await fileSystem.lstat(path);
@@ -61,6 +64,9 @@ export const readStableArtifact = async (
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
),
);
const owner =
resourceScope === undefined ? undefined : new OwnedFileHandle(file);
let failure: unknown;
try {
const initial = await file.stat({ bigint: true });
if (
@@ -116,7 +122,22 @@ export const readStableArtifact = async (
);
const bytes = Buffer.concat(chunks, count);
return { bytes, sha256: createHash("sha256").update(bytes).digest("hex") };
} catch (cause: unknown) {
failure = cause;
throw cause;
} finally {
await file.close();
if (owner === undefined || resourceScope === undefined) await file.close();
else {
const cleanup = await resourceScope.release({
kind: "file-handle",
resource: path,
handle: owner,
});
if (cleanup.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
failure ?? cleanup.cause,
ArtifactReaderFailure.cleanupObservation(cleanup.cause, path),
);
}
}
};
+2
View File
@@ -3,6 +3,7 @@ import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
import { createDirectAnalysis } from "./composition/directAnalysis.js";
import { registerEvmCommands } from "./cli/evmCommands.js";
import { registerGoCommands } from "./cli/goCommands.js";
import { registerSqliteCommands } from "./cli/sqliteCommands.js";
import { registerAnalysisViewCommands } from "./cli/analysisViewCommands.js";
import { registerBinaryDiagnosticsCommands } from "./cli/binaryDiagnosticsCommands.js";
import { registerFridaCommands } from "./cli/fridaCommands.js";
@@ -95,6 +96,7 @@ export const createCli = (
registerWasmCommands(cli, logger, environment);
registerEvmCommands(cli, logger, environment);
registerGoCommands(cli, logger);
registerSqliteCommands(cli, logger, environment);
registerArtifactCommands(cli, logger, analysis.runProviderAnalysis);
registerManagedCommands(cli, logger, analysis.runProviderAnalysis);
registerAndroidCommands(cli, logger, environment);
+111
View File
@@ -0,0 +1,111 @@
import { z } from "incur";
import { resolve } from "node:path";
import { createSqliteDatabaseService } from "../composition/sqlite.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** Resolve an operator-selected SQLite snapshot through the shared inspection workflow. */
export const registerSqliteCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
): void => {
const service = createSqliteDatabaseService(environment);
cli.command(CLI_COMMANDS.inspectSqliteDatabase, {
description:
"Inspect SQLite schema and optional ordinary-table rows from a local snapshot",
args: z.object({
path: z.string().describe("Local SQLite database snapshot"),
}),
options: z.object({
table: z
.string()
.optional()
.describe("Exact ordinary table name to read"),
column: z
.array(z.string())
.optional()
.describe(
"Repeat to select exact row columns in the requested order; requires table",
),
schemaScope: z
.enum(["inventory", "selected_table", "database"])
.optional()
.describe(
"Compact inventory by default, or selected-table details when table is supplied; database requests full schema",
),
rowLimit: z
.number()
.int()
.min(1)
.optional()
.describe(
"Positive safe integer row count; default 20; requires table",
),
}),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectSqliteDatabase, async () => {
const inspection = await service
.inspect(
{
path: resolve(args.path),
...(options.table === undefined
? {}
: { table: options.table }),
...(options.rowLimit === undefined
? {}
: { row_limit: options.rowLimit }),
...(options.column === undefined
? {}
: { columns: options.column }),
...(options.schemaScope === undefined
? {}
: { schema_scope: options.schemaScope }),
},
{ signal },
)
.then(
(result) => ({ result }),
(cause: unknown) => ({ cause }),
);
try {
await service.close();
} catch (cause: unknown) {
const primary =
"cause" in inspection
? inspection.cause
: inspection.result.ok
? undefined
: inspection.result.error;
if (
primary instanceof AnalysisError &&
cause instanceof AnalysisError
)
throw analysisErrorWithCleanupFailure(
primary,
cause,
"inspect_sqlite_database",
);
if ("cause" in inspection)
throw new AggregateError(
[inspection.cause, cause],
"SQLite inspection and provider cleanup both failed",
{ cause: inspection.cause },
);
throw cause;
}
if ("cause" in inspection) throw inspection.cause;
return inspection.result.ok
? inspection.result.value
: projectAnalysisError(inspection.result.error);
}),
),
});
};
+1
View File
@@ -1,6 +1,7 @@
/** Canonical names used by every one-shot CLI command registration. */
export const CLI_COMMANDS = Object.freeze({
inspectWasmArtifact: "inspect-wasm-artifact",
inspectSqliteDatabase: "inspect-sqlite-database",
inspectEvmInterface: "inspect-evm-interface",
inspectWebNetworkCapture: "inspect-web-network-capture",
observeWebExecution: "observe-web-execution",
+8
View File
@@ -0,0 +1,8 @@
import { SqliteDatabaseService } from "../application/sqlite/SqliteDatabaseService.js";
import { SqliteDatabaseProvider } from "../sqlite/SqliteDatabaseProvider.js";
/** Compose local snapshot inspection without opening a native analysis provider. */
export const createSqliteDatabaseService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): SqliteDatabaseService =>
new SqliteDatabaseService(new SqliteDatabaseProvider(environment));
@@ -0,0 +1,42 @@
import {
inspectSqliteDatabaseInputSchema,
sqliteDatabaseSchema,
} from "../../domain/sqlite/sqliteDatabase.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
/** Snapshot inspection is independent of any active native-analysis target. */
export const SQLITE_TOOL_CONTRACTS = [
{
name: "inspect_sqlite_database",
...toolContractMetadata("inspect_sqlite_database"),
kind: "artifact-provider",
description:
"Inspect an explicit local SQLite database snapshot and its existing sibling WAL without modifying source files or opening a native analysis provider. Requires Node.js 24.x >=24.15 or 26+ with native DatabaseSync.limits support, checked by the worker. Returns observed Evidence with database/WAL SHA-256 and a compact schema inventory. Selecting an exact ordinary table expands only its schema and samples rows (default 20, subject to byte and worker resource limits). Select exact columns in the requested order to avoid unrelated or large values; schema_scope=database explicitly expands the whole schema; returned rows retain 64-bit integers, text bytes and blobs with explicit truncation. No arbitrary SQL, view or virtual-table execution, extension loading, database repair, encryption support or live-snapshot atomicity claim. At most two inspections per provider are admitted; occupied capacity is retryable. An isolated temporary copy and owned worker enforce input, value/record, SQL-statement, JSON-reply, JavaScript-heap and deadline limits; overall native heap is not capped. Supply a quiescent snapshot for coherent database/WAL evidence.",
inputSchema: inspectSqliteDatabaseInputSchema,
outputSchema: evidenceResultOf(sqliteDatabaseSchema),
examples: [
{
title: "Inspect a compact inventory of a local SQLite snapshot",
input: { path: "/artifacts/application.sqlite" },
},
{
title: "Read selected rows from an ordinary table",
input: {
path: "/artifacts/application.sqlite",
table: "settings",
columns: ["key", "value"],
row_limit: 20,
},
},
{
title: "Expand the complete stored schema",
input: {
path: "/artifacts/application.sqlite",
schema_scope: "database",
},
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -1,6 +1,7 @@
import { WASM_TOOL_CONTRACTS } from "./wasm/wasmToolContracts.js";
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { GO_TOOL_CONTRACTS } from "./go/goToolContracts.js";
import { SQLITE_TOOL_CONTRACTS } from "./sqlite/sqliteToolContracts.js";
import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "./analysisViewToolContracts.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "./native/nativeToolContracts.js";
@@ -37,6 +38,7 @@ export const TOOL_CONTRACTS = [
...EVM_TOOL_CONTRACTS,
...GO_TOOL_CONTRACTS,
...WASM_TOOL_CONTRACTS,
...SQLITE_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...APKTOOL_TOOL_CONTRACTS,
+2
View File
@@ -19,6 +19,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
resolve_native_call_targets: "states that it does not execute code",
inspect_pe_resources: "states that it does not execute the image",
inspect_go_binary: "reads embedded metadata without executing the target",
inspect_sqlite_database:
"uses a trusted inspector worker without executing application code or caller SQL",
inspect_binary_layout:
"parses the binary offline with operator-configured pwntools",
inspect_recorded_crash: "inspects a core file without launching its target",
+5
View File
@@ -54,6 +54,11 @@ const sessionEvidence = effects({ mutatesSession: true });
/** Explicit effect audit for every public tool. */
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
inspect_go_binary: evidence,
inspect_sqlite_database: effects({
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
}),
inspect_wasm_artifact: effects({
mutatesSession: true,
writesFilesystem: true,
+10 -1
View File
@@ -21,13 +21,22 @@ export class AnalysisUnsupportedTargetError extends AnalysisError {
}
/** An analysis or transport resource failure, distinct from malformed input or unsupported coverage. */
export const ANALYSIS_RESOURCE_KINDS = [
"memory",
"cpu",
"file-size",
"transport",
"capacity",
] as const;
/** A measured resource constraint or bounded admission refusal. */
export class AnalysisResourceConstraintError extends AnalysisError {
readonly _tag = "AnalysisResourceConstraintError";
readonly remediationAction: string | undefined;
constructor(
readonly operation: string,
readonly resource: "memory" | "cpu" | "file-size" | "transport",
readonly resource: (typeof ANALYSIS_RESOURCE_KINDS)[number],
readonly reason: string,
readonly reportedLimits: Readonly<Record<string, JsonValue>> | null,
options?: AnalysisErrorOptions & { readonly remediationAction?: string },
+9 -7
View File
@@ -45,13 +45,15 @@ export const analysisErrorRemediationAction = (
if (error instanceof AnalysisResourceConstraintError)
return (
error.remediationAction ??
(error.resource === "transport"
? "Discover retained records with get_evidence_bundle and detail: summary, then inspect compatible records through inspect_analysis_view using an exact Evidence reference. Export complete retained session evidence through export_evidence_bundle to a caller-selected path, or use complete CLI JSON output. The connection remains usable."
: error.resource === "cpu"
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
: error.resource === "file-size"
? "Review the reported worker file-size limits and write failure. Retry with a sufficient file-size allowance for the evidence reply; REA retains tighter inherited limits."
: "Review the reported worker memory limits and available host memory. Retry with sufficient memory or a smaller artifact; REA retains tighter inherited limits.")
(error.resource === "capacity"
? "Wait for an active analysis to complete, then retry within the reported admission limits."
: error.resource === "transport"
? "Discover retained records with get_evidence_bundle and detail: summary, then inspect compatible records through inspect_analysis_view using an exact Evidence reference. Export complete retained session evidence through export_evidence_bundle to a caller-selected path, or use complete CLI JSON output. The connection remains usable."
: error.resource === "cpu"
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
: error.resource === "file-size"
? "Review the reported worker file-size limits and write failure. Retry with a sufficient file-size allowance for the evidence reply; REA retains tighter inherited limits."
: "Review the reported worker memory limits and available host memory. Retry with sufficient memory or a smaller artifact; REA retains tighter inherited limits.")
);
if (error instanceof HopperTimeoutError)
return error.operation === undefined
@@ -116,6 +116,40 @@ it("distinguishes unsupported target formats from unavailable provider capabilit
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
it.each([false, true])(
"marks occupied capacity retryable only while cleanup is confirmed: %s",
(cleanupIncomplete) => {
const projected = projectAnalysisError(
new AnalysisResourceConstraintError(
"inspect_sqlite_database",
"capacity",
"Inspection slots are occupied",
{ max_concurrent_inspections: 2 },
cleanupIncomplete
? {
cleanup: {
reason: "Snapshot removal denied",
resources: ["/private/snapshot"],
},
}
: undefined,
),
);
expect(projected.retryable).toBe(!cleanupIncomplete);
expect(projected.code).toBe(
cleanupIncomplete ? "cleanup_incomplete" : "resource_constraint",
);
expect(projected.details).toMatchObject({
resource: "capacity",
reported_limits: { max_concurrent_inspections: 2 },
});
expect(projected.remediation.action).toContain("Wait");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it.each([
["memory", null],
["memory", { address_space_bytes: 67108864 }],
+5 -1
View File
@@ -78,7 +78,11 @@ export const projectAnalysisError = (
code,
category: analysisErrorCategory(error),
message: analysisErrorUserMessage(error),
retryable: RETRYABLE_CODES.has(code),
retryable:
RETRYABLE_CODES.has(code) ||
(code === "resource_constraint" &&
error instanceof AnalysisResourceConstraintError &&
error.resource === "capacity"),
remediation: {
action: analysisErrorRemediationAction(error),
},
+235
View File
@@ -0,0 +1,235 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import type { JsonValue } from "../jsonValue.js";
/** Format identity is shared by discovery, catalog, and observed SQLite results. */
export const SQLITE_PROVIDER_IDENTITY = {
id: "sqlite",
name: "REA SQLite database inspector",
version: null,
} as const;
/** Default ordinary-table sample size when the caller selects a table. */
export const SQLITE_ROW_LIMIT_DEFAULT = 20;
const nonnegative = z.number().int().nonnegative();
const hex = z.string().regex(/^(?:[0-9a-f]{2})*$/);
const encoding = z.enum(["UTF-8", "UTF-16le", "UTF-16be"]);
const artifactSchema = z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[0-9a-f]{64}$/),
bytes: nonnegative,
});
/** Inspect one frozen database and its sibling WAL, with optional ordinary-table rows. */
export const inspectSqliteDatabaseInputSchema = z
.strictObject({
path: localPathStringSchema.describe(
"Absolute path to an offline SQLite database snapshot",
),
table: z
.string()
.optional()
.describe(
"Exact ordinary table name; views and virtual/shadow tables are not executed",
),
columns: z
.array(z.string())
.min(1)
.optional()
.describe(
"Exact row columns in caller-selected order; requires table. Omit to sample all visible columns.",
),
schema_scope: z
.enum(["inventory", "selected_table", "database"])
.optional()
.describe(
"Default: compact inventory without a table, or detailed selected-table schema with a table. Database explicitly expands all stored declarations and supported columns.",
),
row_limit: z
.number()
.int()
.min(1)
.optional()
.describe(
"Selected-table sample size, default 20; subject to byte and worker resource limits",
),
})
.superRefine((input, context) => {
if (input.row_limit !== undefined && input.table === undefined)
context.addIssue({
code: "custom",
path: ["row_limit"],
message: "row_limit requires an explicit table selection",
});
if (input.columns !== undefined && input.table === undefined)
context.addIssue({
code: "custom",
path: ["columns"],
message: "columns requires an explicit table selection",
});
if (input.schema_scope === "selected_table" && input.table === undefined)
context.addIssue({
code: "custom",
path: ["schema_scope"],
message: "selected_table schema scope requires table",
});
})
.meta({
dependentRequired: { row_limit: ["table"], columns: ["table"] },
if: {
properties: { schema_scope: { const: "selected_table" } },
required: ["schema_scope"],
},
then: { required: ["table"] },
});
/** JSON-safe SQLite cells retain integers, binary content and special REAL values. */
export const sqliteValueSchema = z.discriminatedUnion("type", [
z.strictObject({ type: z.literal("null") }),
z.strictObject({
type: z.literal("integer"),
value: z.string().regex(/^-?(?:0|[1-9][0-9]*)$/),
}),
z.strictObject({
type: z.literal("real"),
value: z.union([z.number(), z.enum(["Infinity", "-Infinity", "-0"])]),
}),
z.strictObject({
type: z.literal("text"),
value: z.string(),
bytes_hex: hex,
encoding,
}),
z.strictObject({ type: z.literal("blob"), hex }),
]);
/** Frozen schema facts and explicitly bounded selected records, without arbitrary SQL. */
export const sqliteDatabaseSchema = z
.strictObject({
artifact: artifactSchema,
wal: artifactSchema.nullable(),
engine: z.strictObject({
name: z.literal("SQLite"),
version: z.string().min(1),
}),
database_encoding: encoding,
schema: z.strictObject({
scope: z.enum(["inventory", "selected_table", "database"]),
completeness: z
.literal("complete")
.describe(
"Complete within the indicated schema scope; inventory omits declarations and column details",
),
tables: z.array(
z.strictObject({
name: z.string(),
sql: z.string().nullable().optional(),
root_page: nonnegative,
kind: z
.enum(["table", "virtual", "shadow", "unknown"])
.describe(
"Unknown means a possible shadow table of an unresolved virtual table; its rows cannot be inspected",
),
without_rowid: z.boolean(),
strict: z.boolean(),
column_count: nonnegative.nullable(),
columns_completeness: z.enum([
"complete",
"unsupported",
"not_requested",
]),
columns: z.array(
z.strictObject({
cid: nonnegative,
name: z.string(),
declared_type: z.string(),
not_null: z.boolean(),
default_sql: z.string().nullable(),
primary_key_position: nonnegative,
hidden: z.union([
z.literal(0),
z.literal(1),
z.literal(2),
z.literal(3),
]),
}),
),
}),
),
indexes: z.array(
z.strictObject({
name: z.string(),
table: z.string(),
sql: z.string().nullable().optional(),
root_page: nonnegative,
}),
),
views: z.array(
z.strictObject({
name: z.string(),
sql: z.string().nullable().optional(),
}),
),
triggers: z.array(
z.strictObject({
name: z.string(),
table: z.string(),
sql: z.string().nullable().optional(),
}),
),
}),
rows: z
.strictObject({
table: z.string(),
columns: z.array(z.string()),
values: z.array(z.array(sqliteValueSchema)),
row_limit: z.number().int().min(1),
returned_rows: nonnegative,
truncated: z.boolean(),
order: z.literal("unspecified"),
})
.nullable(),
limitations: z.array(z.string()),
})
.superRefine((report, context) => {
const rows = report.rows;
if (
rows !== null &&
(rows.returned_rows !== rows.values.length ||
rows.returned_rows > rows.row_limit ||
rows.values.some((row) => row.length !== rows.columns.length))
)
context.addIssue({
code: "custom",
path: ["rows"],
message:
"Selected row counts and column dimensions must match the retained values",
});
});
export type InspectSqliteDatabaseInput = z.infer<
typeof inspectSqliteDatabaseInputSchema
>;
export type SqliteDatabase = z.infer<typeof sqliteDatabaseSchema>;
export type SqliteValue = z.infer<typeof sqliteValueSchema>;
/** Preserve explicit caller selections while omitting absent optional values from JSON. */
export const sqliteInspectionParameters = (
input: InspectSqliteDatabaseInput,
): Readonly<Record<string, JsonValue>> => ({
path: input.path,
...(input.table === undefined ? {} : { table: input.table }),
...(input.columns === undefined ? {} : { columns: input.columns }),
...(input.schema_scope === undefined
? {}
: { schema_scope: input.schema_scope }),
...(input.row_limit === undefined ? {} : { row_limit: input.row_limit }),
});
/** One contract owner interprets omitted scope for adapters and selection checks. */
export const sqliteSchemaScope = (
input: InspectSqliteDatabaseInput,
): SqliteDatabase["schema"]["scope"] =>
input.schema_scope ??
(input.table === undefined ? "inventory" : "selected_table");
@@ -1,4 +1,5 @@
import { z } from "zod";
import { ANALYSIS_RESOURCE_KINDS } from "../../domain/analysisErrorCore.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { digestSchema } from "../../domain/digests.js";
import {
@@ -65,7 +66,7 @@ export const javaScriptWorkerMessageSchema = z.discriminatedUnion("kind", [
kind: z.literal("failure"),
...identity,
reason: z.enum(["resource", "output", "io"]),
resource: z.enum(["memory", "cpu", "file-size", "transport"]).nullable(),
resource: z.enum(ANALYSIS_RESOURCE_KINDS).nullable(),
limits: z.record(z.string(), jsonValueSchema).nullable(),
message: z.string(),
}),
+46 -7
View File
@@ -56,6 +56,17 @@ export const startMcpTransport = async (
);
}
const androidProviders: AndroidAnalysisPort[] = [];
const servers = new Set<ReturnType<typeof createServer>>();
const closeServers = async (): Promise<void> => {
const results = await Promise.allSettled(
[...servers].map((server) => server.close()),
);
const failures = results.flatMap((result) =>
result.status === "rejected" ? [result.reason] : [],
);
if (failures.length > 0)
throw new AggregateError(failures, "REA server cleanup failed");
};
const closeAndroid = async (): Promise<void> => {
const results = await Promise.allSettled(
androidProviders.map((provider) => provider.close()),
@@ -77,7 +88,7 @@ export const startMcpTransport = async (
serverContext.environment,
);
androidProviders.push(android);
return (dependencies.createServer ?? createServer)(
const server = (dependencies.createServer ?? createServer)(
{ kind: "session", session },
{
logger: serverContext.logger,
@@ -87,6 +98,14 @@ export const startMcpTransport = async (
androidAnalysis: android,
},
);
// The SDK can discard a server even when its provider cleanup failed.
servers.add(server);
const closeServer = server.close.bind(server);
server.close = async () => {
await closeServer();
servers.delete(server);
};
return server;
},
{
onerror: () => {
@@ -96,10 +115,12 @@ export const startMcpTransport = async (
},
);
} catch (cause: unknown) {
const [binaryCleanup, androidCleanup] = await Promise.allSettled([
session.close(),
closeAndroid(),
]);
const [binaryCleanup, androidCleanup, serverCleanup] =
await Promise.allSettled([
session.close(),
closeAndroid(),
closeServers(),
]);
serverLogger.error(
{
error: cause instanceof Error ? cause.message : String(cause),
@@ -115,7 +136,7 @@ export const startMcpTransport = async (
);
dependencies.writeStderr(`${cleanupError.message}\n`);
}
for (const cleanup of [binaryCleanup, androidCleanup]) {
for (const cleanup of [binaryCleanup, androidCleanup, serverCleanup]) {
if (cleanup.status === "rejected") {
const reason =
cleanup.reason instanceof Error
@@ -130,5 +151,23 @@ export const startMcpTransport = async (
}
return { ok: false };
}
return { ok: true, handle, closeAndroid, closeOptionalProviders };
return {
ok: true,
handle: {
close: async () => {
const results = await Promise.allSettled([
handle.close(),
closeServers(),
]);
const failures = results.flatMap((result) =>
result.status === "rejected" ? [result.reason] : [],
);
if (failures.length === 1) throw failures[0];
if (failures.length > 1)
throw new AggregateError(failures, "REA transport cleanup failed");
},
},
closeAndroid,
closeOptionalProviders,
};
};
+12 -1
View File
@@ -61,8 +61,19 @@ export const createEvidenceToolHandler =
const result = await logToolExecution(logger, name, () =>
operation(input, { signal: context.mcpReq.signal }),
);
if (!result.ok)
if (!result.ok) {
const partial = result.error.partialObservation;
if (partial !== undefined && "evidence_id" in partial) {
const recorded = recordEvidence?.(partial);
if (recorded !== undefined)
return server.delivery.toRecordedPartialErrorToolResult(
result.error,
partial.evidence_id,
recorded,
);
}
return server.delivery.toCallToolResult(result, contract);
}
const recorded = recordEvidence?.(result.value);
return server.delivery.toEvidenceToolResult(
result.value,
+15
View File
@@ -7,6 +7,9 @@ import { registerPeResourcesTool } from "./registerPeResourcesTool.js";
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
import { evmInterfaceModule } from "../composition/evm.js";
import { registerEvmTools } from "./registerEvmTools.js";
import type { SqliteDatabaseService } from "../application/sqlite/SqliteDatabaseService.js";
import { createSqliteDatabaseService } from "../composition/sqlite.js";
import { registerSqliteTools } from "./registerSqliteTools.js";
import { registerRecordedCrashTools } from "./registerRecordedCrashTools.js";
import { createRecordedCrashService } from "../composition/binaryDiagnostics.js";
import { createGoBinaryService } from "../composition/go.js";
@@ -118,6 +121,7 @@ export interface CreateServerOptions {
readonly delivery?: ToolResultDelivery;
readonly wasmArtifact?: WasmArtifactService;
readonly evmInterface?: EvmInterfaceService;
readonly sqliteDatabase?: SqliteDatabaseService;
readonly logger?: Logger;
readonly binaryLayout?: BinaryLayoutService;
readonly goBinary?: GoBinaryService;
@@ -243,6 +247,8 @@ export const createServer = (
const delivery = selectToolResultDelivery(environment, options.delivery);
const evmInterface =
options.evmInterface ?? evmInterfaceModule.create(environment);
const sqliteDatabase =
options.sqliteDatabase ?? createSqliteDatabaseService(environment);
const binaryLayout =
options.binaryLayout ?? createBinaryLayoutService(environment);
const recordedCrash =
@@ -262,6 +268,7 @@ export const createServer = (
environment,
delivery,
evmInterface,
sqliteDatabase,
binaryLayout,
recordedCrash,
webSourceLocation,
@@ -302,6 +309,7 @@ export const createServer = (
adbDevice.close(),
flutter.close(),
evmInterface.close(),
sqliteDatabase.close(),
binaryLayout.close(),
recordedCrash.close(),
webSourceLocation.close(),
@@ -520,6 +528,13 @@ const registerConfiguredAnalysisTools = (
recordEvidence,
withAdmittedAnalysis,
);
registerSqliteTools(
server,
options.sqliteDatabase ?? createSqliteDatabaseService(environment),
toolLogger,
recordEvidence,
withAdmittedAnalysis,
);
registerRecordedCrashTools(
server,
options.recordedCrash ?? createRecordedCrashService(environment),
+31
View File
@@ -0,0 +1,31 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { SqliteDatabaseService } from "../application/sqlite/SqliteDatabaseService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { createEvidenceToolHandler } from "./contractToolHandler.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Bind snapshot inspection to its named contract and additive session Evidence. */
export const registerSqliteTools = (
server: EvidenceMcpServer,
service: SqliteDatabaseService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
): void => {
const contract = toolContract("inspect_sqlite_database");
const handler = createEvidenceToolHandler(
server,
(input, options) => service.inspect(input, options),
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
handler(contract),
);
};
+165
View File
@@ -0,0 +1,165 @@
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../domain/analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
import { SQLITE_PROVIDER_IDENTITY } from "../domain/sqlite/sqliteDatabase.js";
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
/** Preserve diagnostics independently of worker exit and private-root cleanup. */
export const capturedSqliteOutput = (
snapshot: ProviderProcessSnapshot,
): AnalysisCapturedOutput => ({
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
truncated: snapshot.diagnosticTruncated === true,
});
/** Preserve artifact, caller, process, resource and output failure meanings. */
export const sqliteDatabaseFailure = (
cause: unknown,
path: string,
phase: string,
signal?: AbortSignal,
): AnalysisError => {
const operation = "inspect_sqlite_database";
if (cause instanceof AnalysisError) return cause;
if (cause instanceof ArtifactReaderFailure) {
if (cause.cleanup !== undefined)
return new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
cause.cleanup.resources,
{
reason: cause.cleanup.reason,
previous_error:
cause.cause === undefined
? null
: projectAnalysisError(
signal?.aborted
? new AnalysisCancelledError(operation, {
cause: cause.cause,
})
: sqliteDatabaseFailure(cause.cause, path, phase),
),
},
{ operation, cause },
);
if (cause.reason === "io" && cause.cause !== undefined)
return sqliteDatabaseFailure(cause.cause, path, phase, signal);
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(operation, path, cause.message, {
cause,
});
if (cause.reason === "cancelled")
return new AnalysisCancelledError(operation, { cause });
return new AnalysisInputError(operation, { cause }, [
{
path: ["path"],
reason: cause.reason === "limit" ? "out_of_range" : "invalid_format",
message: cause.message,
},
]);
}
if (cause instanceof Error && cause.name === "AbortError")
return new AnalysisCancelledError(operation, { cause });
if (cause instanceof OwnedCommandFailure) {
const projected = ownedCommandFailure(cause);
if (projected !== undefined) return projected;
}
if (phase === "artifact-read" && cause instanceof Error && "code" in cause) {
if (cause.code === "EACCES" || cause.code === "EPERM")
return new AnalysisAccessDeniedError(operation, path, cause.code, {
cause,
});
if (cause.code === "ENOENT" || cause.code === "ENOTDIR")
return new AnalysisInputError(operation, { cause }, [
{
path: ["path"],
reason: "invalid_value",
message: `Selected database file set could not be read (${String(cause.code)}): ${path}`,
},
]);
}
return new ProviderAdapterError(SQLITE_PROVIDER_IDENTITY.id, operation, {
cause,
diagnostics: {
phase,
path,
reason: cause instanceof Error ? cause.message : String(cause),
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
? {
failure_kind: cause.reason,
exit_code: cause.snapshot.exitCode ?? null,
signal: cause.snapshot.signal ?? null,
captured_output: { ...capturedSqliteOutput(cause.snapshot) },
}
: {}),
},
});
};
const ownedCommandFailure = (
cause: OwnedCommandFailure,
): AnalysisError | undefined => {
const operation = "inspect_sqlite_database";
const capturedOutput =
cause.snapshot === null ? undefined : capturedSqliteOutput(cause.snapshot);
const options = {
cause,
...(capturedOutput === undefined ? {} : { capturedOutput }),
};
if (cause.cleanupFailure !== null)
return new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
cause.resources,
{
reason: cause.cleanupFailure,
previous_error: {
failure_kind: cause.reason,
message: cause.message,
},
...(capturedOutput === undefined
? {}
: { captured_output: { ...capturedOutput } }),
},
{ operation, cause },
);
if (cause.reason === "cancelled")
return new AnalysisCancelledError(operation, options);
if (cause.reason === "timeout")
return new AnalysisTimeoutError(
operation,
SQLITE_DATABASE_LIMITS.timeoutMs,
options,
);
if (cause.reason === "output-limit")
return new AnalysisOutputError(operation, cause.message, options);
if (
cause.snapshot?.stderr.text.includes("JavaScript heap out of memory") ===
true
)
return new AnalysisResourceConstraintError(
operation,
"memory",
"Owned SQLite worker reported JavaScript heap exhaustion.",
{
javascript_heap_bytes: 256 * 1024 * 1024,
},
options,
);
return undefined;
};
+514
View File
@@ -0,0 +1,514 @@
import { DatabaseSync } from "node:sqlite";
import { z } from "zod";
import { jsonParts } from "../domain/jsonSerialization.js";
import {
SQLITE_ROW_LIMIT_DEFAULT,
sqliteSchemaScope,
type InspectSqliteDatabaseInput,
type SqliteDatabase,
type SqliteValue,
} from "../domain/sqlite/sqliteDatabase.js";
import {
SQLITE_DATABASE_LIMITS,
SqliteInspectionFailure,
} from "./SqliteDatabaseLimits.js";
const natural = z
.bigint()
.nonnegative()
.max(BigInt(Number.MAX_SAFE_INTEGER))
.transform(Number);
const schemaRow = z.object({
type: z.enum(["table", "index", "view", "trigger"]),
name: z.instanceof(Uint8Array),
tbl_name: z.instanceof(Uint8Array),
rootpage: natural,
sql: z.instanceof(Uint8Array).nullable().optional(),
});
const tableRow = z.object({
schema: z.string(),
name: z.string(),
type: z.enum(["table", "view", "virtual", "shadow"]),
ncol: natural,
wr: z.bigint(),
strict: z.bigint(),
});
const columnRow = z.object({
cid: natural,
name: z.string(),
type: z.string(),
notnull: z.bigint(),
dflt_value: z.string().nullable(),
pk: natural,
hidden: z
.bigint()
.transform(Number)
.pipe(z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)])),
});
const arrayRow = z.array(
z.union([
z.null(),
z.bigint(),
z.custom<number>(
(value) => typeof value === "number" && !Number.isNaN(value),
),
z.string(),
]),
);
const encodingSchema = z.enum(["UTF-8", "UTF-16le", "UTF-16be"]);
const cellByteLengths = z.array(z.bigint().nonnegative());
type DatabaseEncoding = z.output<typeof encodingSchema>;
type Inspection = Pick<
SqliteDatabase,
"engine" | "database_encoding" | "schema" | "rows" | "limitations"
>;
type SelectedTableFacts = Pick<
SqliteDatabase["schema"]["tables"][number],
"name" | "kind" | "columns"
>;
class OutputBudget {
#bytes = 1024;
retain(value: unknown): void {
// Count bounded encoded parts, including escapes, without allocating a
// document-sized string just to decide whether it fits the reply.
this.#bytes += 1;
for (const part of jsonParts(value)) {
this.#bytes += Buffer.byteLength(part);
if (this.#bytes > SQLITE_DATABASE_LIMITS.outputBytes)
throw new SqliteInspectionFailure(
"output-limit",
"Complete SQLite evidence exceeds the 16 MiB JSON reply budget; no partial success was returned.",
);
}
}
beforeDecode(row: z.output<typeof arrayRow>): void {
let minimumBytes = this.#bytes;
for (const value of row)
if (typeof value === "string") minimumBytes += Buffer.byteLength(value);
if (minimumBytes > SQLITE_DATABASE_LIMITS.outputBytes)
throw new SqliteInspectionFailure(
"output-limit",
"Selected cells exceed the 16 MiB reply budget before text/hex expansion.",
);
}
beforeProjection(lengths: readonly bigint[]): void {
const encodedBytes = lengths.reduce(
(total, length) => total + length * 2n,
BigInt(lengths.length * 64),
);
if (
encodedBytes + BigInt(this.#bytes) >
BigInt(SQLITE_DATABASE_LIMITS.outputBytes)
)
throw new SqliteInspectionFailure(
"output-limit",
"Selected row byte lengths exceed the 16 MiB reply budget before hex projection.",
);
}
}
const quoteIdentifier = (name: string): string =>
`"${name.replaceAll('"', '""')}"`;
// SQLite folds only ASCII letters when matching virtual/shadow table names.
const sqliteIdentifierKey = (name: string): string =>
name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
const textEncoding = (encoding: DatabaseEncoding): string =>
encoding === "UTF-8"
? "utf-8"
: encoding === "UTF-16le"
? "utf-16le"
: "utf-16be";
const decodeSchemaText = (
value: Uint8Array,
encoding: DatabaseEncoding,
label: string,
): string => {
try {
return new TextDecoder(textEncoding(encoding), {
fatal: true,
ignoreBOM: true,
}).decode(value);
} catch (cause: unknown) {
throw new SqliteInspectionFailure(
"format",
`SQLite schema ${label} contains malformed ${encoding} text: ${cause instanceof Error ? cause.message : String(cause)}`,
);
}
};
const cell = (
value: z.output<typeof arrayRow>[number],
encoding: DatabaseEncoding,
): SqliteValue => {
if (value === null) return { type: "null" };
if (typeof value === "bigint")
return { type: "integer", value: String(value) };
if (typeof value === "number")
return {
type: "real",
value:
value === Infinity
? "Infinity"
: value === -Infinity
? "-Infinity"
: Object.is(value, -0)
? "-0"
: value,
};
const hex = value.slice(1).toLowerCase();
if (!/^(?:[0-9a-f]{2})*$/.test(hex))
throw new SqliteInspectionFailure(
"format",
"SQLite returned an invalid encoded cell.",
);
if (value[0] === "b") return { type: "blob", hex };
if (value[0] !== "t")
throw new SqliteInspectionFailure(
"format",
"SQLite returned an unknown encoded cell type.",
);
return {
type: "text",
value: new TextDecoder(textEncoding(encoding), { ignoreBOM: true }).decode(
Buffer.from(hex, "hex"),
),
bytes_hex: hex,
encoding,
};
};
const readColumns = (
db: DatabaseSync,
name: string,
budget: OutputBudget,
): SqliteDatabase["schema"]["tables"][number]["columns"] => {
const columns: SqliteDatabase["schema"]["tables"][number]["columns"] = [];
// Direct PRAGMA syntax cannot be shadowed by a stored table or view.
for (const raw of db
.prepare(`PRAGMA main.table_xinfo(${quoteIdentifier(name)})`)
.iterate()) {
const value = columnRow.parse(raw);
const column = {
cid: value.cid,
name: value.name,
declared_type: value.type,
not_null: value.notnull !== 0n,
default_sql: value.dflt_value,
primary_key_position: value.pk,
hidden: value.hidden,
};
budget.retain(column);
columns.push(column);
}
return columns;
};
const readSchema = (
db: DatabaseSync,
input: InspectSqliteDatabaseInput,
context: {
readonly budget: OutputBudget;
readonly limitations: string[];
readonly encoding: DatabaseEncoding;
},
): {
schema: SqliteDatabase["schema"];
selectedTable: SelectedTableFacts | undefined;
} => {
const { budget, limitations, encoding } = context;
const scope = sqliteSchemaScope(input);
const selectedName = scope === "selected_table" ? input.table : undefined;
if (scope === "selected_table" && selectedName === undefined)
throw new SqliteInspectionFailure(
"selection",
"Selected-table schema scope requires an exact table name.",
);
let selectedTable: SelectedTableFacts | undefined;
const metadata = new Map<string, z.output<typeof tableRow>>();
// Names bound the minimum eventual schema output while metadata is collected.
// The full schema objects below account for them in the actual reply budget.
const metadataBudget = new OutputBudget();
for (const raw of db.prepare("PRAGMA main.table_list").iterate()) {
const value = tableRow.parse(raw);
if (value.schema === "main") {
metadataBudget.retain(value.name);
metadata.set(value.name, value);
}
}
const unresolvedVirtualTables = [...metadata.values()]
.filter((value) => value.type === "virtual" && value.ncol === 0)
.map((value) => ({
name: value.name,
prefix: sqliteIdentifierKey(`${value.name}_`),
}));
const schema: SqliteDatabase["schema"] = {
scope,
completeness: "complete",
tables: [],
indexes: [],
views: [],
triggers: [],
};
// Raw bytes preserve text without hex expansion; avoid sorter records that
// duplicate large names or definitions beyond SQLite's native record limit.
const declaration = scope === "inventory" ? "" : ", CAST(sql AS BLOB) AS sql";
const selection =
scope === "selected_table" ? " WHERE tbl_name = ? COLLATE BINARY" : "";
const statement = db.prepare(
`SELECT type, CAST(name AS BLOB) AS name, CAST(tbl_name AS BLOB) AS tbl_name, rootpage${declaration} FROM main.sqlite_schema${selection}`,
);
for (const raw of statement.iterate(
...(selectedName === undefined ? [] : [selectedName]),
)) {
const parsed = schemaRow.parse(raw);
const value = {
...parsed,
name: decodeSchemaText(parsed.name, encoding, "name"),
tbl_name: decodeSchemaText(parsed.tbl_name, encoding, "table"),
sql:
parsed.sql === undefined
? undefined
: parsed.sql === null
? null
: decodeSchemaText(parsed.sql, encoding, "sql"),
};
if (value.type === "table") {
const listed = metadata.get(value.name);
if (listed === undefined || listed.type === "view")
throw new SqliteInspectionFailure(
"format",
`SQLite schema/table inventory mismatch: ${value.name}`,
);
const identifier = sqliteIdentifierKey(value.name);
const possibleShadowParent =
listed.type === "table"
? unresolvedVirtualTables.find((parent) =>
identifier.startsWith(parent.prefix),
)
: undefined;
const table: SqliteDatabase["schema"]["tables"][number] = {
name: value.name,
...(scope === "inventory" ? {} : { sql: value.sql }),
root_page: value.rootpage,
kind: possibleShadowParent === undefined ? listed.type : "unknown",
without_rowid: listed.wr !== 0n,
strict: listed.strict !== 0n,
column_count:
listed.type === "virtual" && listed.ncol === 0 ? null : listed.ncol,
columns_completeness: "complete",
columns: [],
};
if (possibleShadowParent !== undefined)
limitations.push(
`SQLite could not resolve virtual table ${possibleShadowParent.name}. Table ${value.name} may be its shadow table; its kind is unknown and row inspection is unavailable.`,
);
budget.retain(table);
if (scope === "inventory") table.columns_completeness = "not_requested";
if (listed.type === "virtual" && scope !== "inventory") {
table.columns_completeness = "unsupported";
limitations.push(
`Virtual table column expansion is not performed: ${value.name}. Its complete stored CREATE statement is retained.`,
);
} else if (
listed.type !== "virtual" &&
(scope !== "inventory" || input.table === value.name)
) {
const columns = readColumns(
db,
value.name,
scope === "inventory" ? new OutputBudget() : budget,
);
if (input.table === value.name)
selectedTable = { name: table.name, kind: table.kind, columns };
if (scope !== "inventory") table.columns = columns;
}
if (input.table === value.name && selectedTable === undefined)
selectedTable = {
name: table.name,
kind: table.kind,
columns: table.columns,
};
schema.tables.push(table);
} else if (value.type === "index") {
const index = {
name: value.name,
table: value.tbl_name,
...(scope === "inventory" ? {} : { sql: value.sql }),
root_page: value.rootpage,
};
budget.retain(index);
schema.indexes.push(index);
} else if (value.type === "view") {
const view = {
name: value.name,
...(scope === "inventory" ? {} : { sql: value.sql }),
};
budget.retain(view);
schema.views.push(view);
} else {
const trigger = {
name: value.name,
table: value.tbl_name,
...(scope === "inventory" ? {} : { sql: value.sql }),
};
budget.retain(trigger);
schema.triggers.push(trigger);
}
}
return { schema, selectedTable };
};
const readRows = (
db: DatabaseSync,
input: InspectSqliteDatabaseInput,
table: SelectedTableFacts | undefined,
context: {
readonly encoding: DatabaseEncoding;
readonly budget: OutputBudget;
},
): SqliteDatabase["rows"] => {
const { encoding, budget } = context;
if (input.table === undefined) return null;
if (table === undefined)
throw new SqliteInspectionFailure(
"selection",
`Selected ordinary table does not exist with that exact name: ${input.table}`,
);
if (table.kind === "unknown")
throw new SqliteInspectionFailure(
"selection",
`SQLite cannot determine whether selected table ${input.table} is a shadow table of an unresolved virtual table. Row inspection requires a confirmed ordinary table.`,
);
if (table.kind !== "table")
throw new SqliteInspectionFailure(
"selection",
`Rows from ${table.kind} table ${input.table} are outside the ordinary-table inspection profile.`,
);
const limit = input.row_limit ?? SQLITE_ROW_LIMIT_DEFAULT;
const visibleColumns = table.columns
.filter((column) => column.hidden !== 1)
.map((column) => column.name);
const columns = input.columns ?? visibleColumns;
const available = new Set(visibleColumns);
for (const name of columns)
if (!available.has(name))
throw new SqliteInspectionFailure(
"selection",
`Selected column does not exist with that exact name in table ${input.table}: ${name}`,
);
const projection = columns
.map((name) => {
const column = quoteIdentifier(name);
return `CASE typeof(${column}) WHEN 'text' THEN 't' || hex(CAST(${column} AS BLOB)) WHEN 'blob' THEN 'b' || hex(${column}) ELSE ${column} END`;
})
.join(", ");
const source = `main.${quoteIdentifier(input.table)} NOT INDEXED`;
const lengths = db.prepare(
`SELECT ${columns
.map((name) => {
const column = quoteIdentifier(name);
return `CASE typeof(${column}) WHEN 'text' THEN length(CAST(${column} AS BLOB)) WHEN 'blob' THEN length(${column}) ELSE 0 END`;
})
.join(", ")} FROM ${source} LIMIT ?`,
);
lengths.setReturnArrays(true);
for (const raw of lengths.iterate(limit))
budget.beforeProjection(cellByteLengths.parse(raw));
const statement = db.prepare(`SELECT ${projection} FROM ${source} LIMIT ?`);
statement.setReturnArrays(true);
const rows: NonNullable<SqliteDatabase["rows"]> = {
table: input.table,
columns,
values: [],
row_limit: limit,
returned_rows: 0,
truncated: false,
order: "unspecified",
};
for (const raw of statement.iterate(limit)) {
const rawRow = arrayRow.parse(raw);
// Hex expansion already belongs to the retained-output budget, before decoding/copying cells.
budget.beforeDecode(rawRow);
const values = rawRow.map((value) => cell(value, encoding));
budget.retain(values);
rows.values.push(values);
}
rows.returned_rows = rows.values.length;
rows.truncated =
db.prepare(`SELECT 1 FROM ${source} LIMIT 1 OFFSET ?`).get(limit) !==
undefined;
return rows;
};
/** Query only a provider-owned snapshot; no caller SQL, extensions, views or virtual rows. */
export const inspectSqliteDatabaseSnapshot = (
snapshotPath: string,
input: InspectSqliteDatabaseInput,
): Inspection => {
const db = new DatabaseSync(snapshotPath, {
readOnly: true,
allowExtension: false,
readBigInts: true,
enableDoubleQuotedStringLiterals: false,
timeout: 0,
limits: {
length: SQLITE_DATABASE_LIMITS.outputBytes,
sqlLength: SQLITE_DATABASE_LIMITS.outputBytes,
},
});
try {
const limits: unknown = db.limits;
const supported = z
.object({
length: z
.number()
.int()
.positive()
.max(SQLITE_DATABASE_LIMITS.outputBytes),
sqlLength: z
.number()
.int()
.positive()
.max(SQLITE_DATABASE_LIMITS.outputBytes),
})
.safeParse(limits);
if (!supported.success)
throw new SqliteInspectionFailure(
"unavailable",
"SQLite inspection requires the native DatabaseSync.limits API to bound untrusted values and SQL. Use Node.js 24.15 or newer in the supported 24.x line, or a compatible Node.js 26+ runtime.",
);
db.exec(
"PRAGMA trusted_schema=OFF; PRAGMA query_only=ON; PRAGMA mmap_size=0; PRAGMA cell_size_check=ON; BEGIN;",
);
const version = z
.object({ version: z.string() })
.parse(db.prepare("SELECT sqlite_version() AS version").get()).version;
const encoding = z
.object({ encoding: encodingSchema })
.parse(db.prepare("PRAGMA encoding").get()).encoding;
const limitations = [
"Inspects an offline stable file set. Filesystem identity checks detect observed acquisition changes; they do not establish an atomic snapshot of an actively changing database. Supply an application-created backup or quiescent database/WAL pair.",
"The source database and WAL are never opened by SQLite or modified. A private copy may acquire its own WAL-index sidecar and is removed after inspection.",
"SQLite reports current schema and selected committed rows from its valid database/WAL state. Deleted records, uncommitted or invalid WAL tails, encrypted databases, forensic recovery, and full integrity verification are outside this profile.",
"Stored CREATE statements preserve index/view/trigger definitions. Views, triggers, and virtual/shadow table rows are not executed; virtual-table column expansion is unsupported.",
"Selected rows have unspecified order and are a bounded sample. Text display may replace invalid sequences; bytes_hex and encoding preserve SQLite's text byte representation, not original on-disk page offsets.",
"Resource boundaries: at most two concurrent inspections per provider; combined input 256 MiB per inspection, complete worker JSON 16 MiB, native SQLite value/record and SQL statement lengths 16 MiB, owned-worker JavaScript heap 256 MiB and supervised deadline 30 seconds. These are distinct from total resident memory; an overall native SQLite heap cap is not claimed. Failures return no partial success.",
];
const budget = new OutputBudget();
const { schema, selectedTable } = readSchema(db, input, {
budget,
limitations,
encoding,
});
return {
engine: { name: "SQLite", version },
database_encoding: encoding,
schema,
rows: readRows(db, input, selectedTable, { encoding, budget }),
limitations,
};
} finally {
db.close();
}
};
+23
View File
@@ -0,0 +1,23 @@
/** Bound frozen input, retained JSON and worker allocation before parsing untrusted files. */
export const SQLITE_DATABASE_LIMITS = {
concurrentInspections: 2,
inputBytes: 256 * 1024 * 1024,
outputBytes: 16 * 1024 * 1024,
timeoutMs: 30_000,
diagnosticBytes: 1024 * 1024,
} as const;
/** Internal rejection retains the failed boundary without returning partial success. */
export class SqliteInspectionFailure extends Error {
constructor(
readonly reason:
| "format"
| "selection"
| "unsupported"
| "unavailable"
| "output-limit"
| "memory",
message: string,
) {
super(message);
}
}
+410
View File
@@ -0,0 +1,410 @@
import {
createAnalysisExecution,
type AnalysisExecution,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import type { SqliteDatabasePort } from "../application/sqlite/SqliteDatabasePort.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type {
AnalysisCapturedOutput,
AnalysisError,
} from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { createEvidence } from "../domain/evidence.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok, type Result } from "../domain/result.js";
import {
inspectSqliteDatabaseInputSchema,
sqliteDatabaseSchema,
type InspectSqliteDatabaseInput,
SQLITE_PROVIDER_IDENTITY,
sqliteInspectionParameters,
} from "../domain/sqlite/sqliteDatabase.js";
import { isAbsolute } from "node:path";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
import { sqliteDatabaseFailure } from "./SqliteDatabaseFailures.js";
import { captureSqliteDatabaseSnapshot } from "./SqliteDatabaseSnapshot.js";
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
import {
executeSqliteDatabaseWorker,
type SqliteWorkerLauncher,
} from "./SqliteDatabaseWorkerExecution.js";
const operation = "inspect_sqlite_database";
type SqliteOutcome = Result<AnalysisExecution, AnalysisError>;
type SqliteRuntimeRoot = Pick<PrivateRuntimeRoot, "path" | "close">;
interface PendingSnapshotCleanup {
readonly input: InspectSqliteDatabaseInput;
readonly result: SqliteOutcome;
readonly output: AnalysisCapturedOutput | undefined;
process: ProviderProcessSupervisor | undefined;
}
/** Inspect a provider-owned copy through a cancellable SQLite child, without source writes. */
export class SqliteDatabaseProvider implements SqliteDatabasePort {
readonly #active = new Set<Promise<SqliteOutcome>>();
readonly #artifactResources = new ArtifactResourceScope();
readonly #pendingCleanup = new Map<
SqliteRuntimeRoot,
PendingSnapshotCleanup
>();
#closed = false;
#closePromise: Promise<void> | undefined;
#retryPromise: Promise<Result<null, AnalysisError>> | undefined;
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
readonly launcher?: SqliteWorkerLauncher,
readonly createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-sqlite-database-" }),
) {}
/** Return exact original DB/WAL identities and current schema/selected committed rows. */
async inspect(
input: InspectSqliteDatabaseInput,
options?: ExecutionOptions,
): Promise<SqliteOutcome> {
if (this.#closed || options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
if (this.#active.size >= SQLITE_DATABASE_LIMITS.concurrentInspections)
return err(
new AnalysisResourceConstraintError(
operation,
"capacity",
"SQLite inspection capacity is occupied. Retry after an active inspection completes.",
{
active_inspections: this.#active.size,
max_concurrent_inspections:
SQLITE_DATABASE_LIMITS.concurrentInspections,
input_bytes_per_inspection: SQLITE_DATABASE_LIMITS.inputBytes,
},
{
remediationAction:
"Retry after an active SQLite inspection completes.",
},
),
);
const inspection = this.#artifactResources
.run(() => this.#inspect(input, options))
.catch((cause: unknown) =>
err(
selectedFailure(
sqliteDatabaseFailure(
cause,
input.path,
"artifact-read",
options?.signal,
),
options?.signal,
),
),
);
this.#active.add(inspection);
try {
return await inspection;
} finally {
this.#active.delete(inspection);
}
}
/** Await inspections and retry retained descriptors, workers, and snapshot roots. */
close(): Promise<void> {
this.#closed = true;
this.#closePromise ??= Promise.allSettled(this.#active)
.then(async () => {
let descriptorFailure: AnalysisError | undefined;
try {
await this.#artifactResources.close();
} catch (cause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cause,
"SQLite artifact descriptors",
);
descriptorFailure = new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
cleanup.resources,
{ reason: cleanup.reason },
{ operation, cause },
);
}
const cleaned = await this.#retryCleanup();
if (descriptorFailure !== undefined && !cleaned.ok)
throw new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
[
...descriptorFailure.cleanupResources,
...cleaned.error.cleanupResources,
],
{
failures: [
projectAnalysisError(descriptorFailure),
projectAnalysisError(cleaned.error),
],
},
{ operation },
);
if (descriptorFailure !== undefined) throw descriptorFailure;
if (!cleaned.ok) throw cleaned.error;
})
.catch((cause: unknown) => {
this.#closePromise = undefined;
throw cause;
});
return this.#closePromise;
}
#retryCleanup(): Promise<Result<null, AnalysisError>> {
this.#retryPromise ??= this.#cleanupPending().finally(() => {
this.#retryPromise = undefined;
});
return this.#retryPromise;
}
async #cleanupPending(): Promise<Result<null, AnalysisError>> {
const failures: AnalysisError[] = [];
for (const [root, pending] of [...this.#pendingCleanup]) {
if (pending.process !== undefined) {
const stopped = await pending.process.stop();
if (stopped.status === "incomplete") {
failures.push(
new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
[
pending.process.launch.ownership?.runId ??
"owned-sqlite-worker",
root.path,
],
{
reason: stopped.reason,
previous_error: pending.result.ok
? null
: projectAnalysisError(pending.result.error),
...(pending.output === undefined
? {}
: { captured_output: { ...pending.output } }),
},
{ operation },
),
);
continue;
}
pending.process = undefined;
}
const cleaned = await cleanupSqliteRoot(
root,
pending.result,
pending.input,
pending.output,
);
if (cleaned.ok) this.#pendingCleanup.delete(root);
else failures.push(cleaned.error);
}
if (failures.length === 1 && failures[0] !== undefined)
return err(failures[0]);
return failures.length === 0
? ok(null)
: err(
new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
failures.flatMap((failure) => failure.cleanupResources),
{ failures: failures.map(projectAnalysisError) },
{ operation },
),
);
}
async #inspect(
input: InspectSqliteDatabaseInput,
options?: ExecutionOptions,
): Promise<SqliteOutcome> {
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let processOwner: ProviderProcessSupervisor | undefined;
let retainedOutput: AnalysisCapturedOutput | undefined;
let phase = "configuration";
let result: Result<AnalysisExecution, AnalysisError>;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(operation);
validateSqliteInput(input);
const retired = await this.#retryCleanup();
if (!retired.ok) return retired;
if (this.#closed || options?.signal?.aborted)
throw new AnalysisCancelledError(operation);
root = await this.createRuntime();
phase = "artifact-read";
const snapshot = await captureSqliteDatabaseSnapshot(
input.path,
root.path,
this.#artifactResources,
options?.signal,
);
phase = "worker";
const inspection = await executeSqliteDatabaseWorker({
input,
root: root.path,
snapshotPath: snapshot.snapshotPath,
environment: this.environment,
resourceScope: this.#artifactResources,
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
...(options?.signal === undefined ? {} : { signal: options.signal }),
captured: (output) => {
retainedOutput = output;
},
});
const validated = sqliteDatabaseSchema.safeParse({
artifact: snapshot.artifact,
wal: snapshot.wal,
...inspection,
});
if (!validated.success)
throw new AnalysisOutputError(
operation,
"SQLite worker report dimensions or identity fields are invalid",
retainedOutput === undefined
? undefined
: { capturedOutput: retainedOutput },
);
result = ok(createSqliteObservation(validated.data, input.path));
} catch (cause: unknown) {
if (cause instanceof OwnedCommandFailure)
processOwner = cause.cleanupOwner;
const failure = sqliteDatabaseFailure(
cause,
input.path,
phase,
options?.signal,
);
retainedOutput ??= failure.capturedOutput;
result = err(selectedFailure(failure, options?.signal, retainedOutput));
}
if (root !== undefined) {
if (processOwner !== undefined) {
this.#pendingCleanup.set(root, {
input,
result,
output: retainedOutput,
process: processOwner,
});
return result;
}
const cleaned = await cleanupSqliteRoot(
root,
result,
input,
retainedOutput,
);
if (!cleaned.ok) {
this.#pendingCleanup.set(root, {
input,
result,
output: retainedOutput,
process: undefined,
});
return cleaned;
}
}
// Completion was acknowledged before cleanup. A later abort does not erase it.
return result;
}
}
const selectedFailure = (
failure: AnalysisError,
signal?: AbortSignal,
output?: AnalysisCapturedOutput,
): AnalysisError =>
signal?.aborted &&
failure._tag !== "AnalysisCancelledError" &&
!failure.cleanupIncomplete
? new AnalysisCancelledError(
operation,
output === undefined ? undefined : { capturedOutput: output },
)
: failure;
const createSqliteObservation = (
report: ReturnType<typeof sqliteDatabaseSchema.parse>,
path: string,
): AnalysisExecution => {
const locations: AnalysisExecution["locations"][number][] = [
{ kind: "artifact-path", path },
];
if (report.wal !== null)
locations.push({ kind: "artifact-path", path: report.wal.path });
return createAnalysisExecution(
report,
{ ...SQLITE_PROVIDER_IDENTITY, version: `SQLite ${report.engine.version}` },
{
rawResult: null,
subject: { path, format: "file", sha256: report.artifact.sha256 },
locations,
limitations: report.limitations,
},
);
};
const cleanupSqliteRoot = async (
root: Pick<PrivateRuntimeRoot, "path" | "close">,
result: Result<AnalysisExecution, AnalysisError>,
input: InspectSqliteDatabaseInput,
output?: AnalysisCapturedOutput,
): Promise<Result<null, AnalysisError>> => {
try {
await root.close();
return ok(null);
} catch (cause: unknown) {
return err(
new ProviderCleanupError(
SQLITE_PROVIDER_IDENTITY.id,
[root.path],
{
reason: cause instanceof Error ? cause.message : String(cause),
previous_error: result.ok ? null : projectAnalysisError(result.error),
...(output === undefined ? {} : { captured_output: { ...output } }),
},
{
operation,
cause,
...(result.ok
? {
partialObservation: createEvidence(
result.value.subject ?? undefined,
result.value.provider,
{
operation,
parameters: sqliteInspectionParameters(input),
result: result.value.result,
confidence: "observed",
locations: result.value.locations,
limitations: result.value.limitations,
},
),
}
: result.error.partialObservation === undefined
? {}
: { partialObservation: result.error.partialObservation }),
},
),
);
}
};
const validateSqliteInput = (input: InspectSqliteDatabaseInput): void => {
const parsed = inspectSqliteDatabaseInputSchema.safeParse(input);
if (!parsed.success || !isAbsolute(input.path))
throw new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: parsed.success
? "path must be an absolute local filesystem path"
: parsed.error.message,
},
]);
};
+270
View File
@@ -0,0 +1,270 @@
import { lstat, open, writeFile } from "node:fs/promises";
import { constants, type BigIntStats } from "node:fs";
import { join } from "node:path";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import {
readStableArtifact,
type StableArtifactFileSystem,
} from "../artifacts/readStableArtifact.js";
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
const fileSystem: StableArtifactFileSystem = {
lstat: (path) => lstat(path, { bigint: true }),
open,
};
const optionalStat = async (
path: string,
selectedFileSystem: StableArtifactFileSystem,
): Promise<BigIntStats | null> => {
try {
return await selectedFileSystem.lstat(path);
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
return null;
throw cause;
}
};
const sameState = (
before: BigIntStats | null,
after: BigIntStats | null,
): boolean =>
before === null || after === null
? before === after
: before.dev === after.dev &&
before.ino === after.ino &&
before.mode === after.mode &&
before.size === after.size &&
before.mtimeNs === after.mtimeNs &&
before.ctimeNs === after.ctimeNs;
const duringAcquisition = async <T>(
path: string,
read: () => Promise<T>,
): Promise<T> => {
try {
return await read();
} catch (cause: unknown) {
if (
cause instanceof Error &&
"code" in cause &&
["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code))
)
throw new ArtifactReaderFailure(
"integrity",
`SQLite snapshot file set changed during acquisition: ${path}`,
{ cause },
);
throw cause;
}
};
const readObservedArtifact = (
path: string,
observed: BigIntStats,
maximumBytes: number,
selectedFileSystem: StableArtifactFileSystem,
resourceScope: ArtifactResourceScope,
signal?: AbortSignal,
) =>
duringAcquisition(path, () =>
readStableArtifact(
path,
maximumBytes,
signal,
{
open: (selectedPath, flags) =>
selectedFileSystem.open(selectedPath, flags),
lstat: async (selectedPath) => {
const current = await selectedFileSystem.lstat(selectedPath);
if (!sameState(observed, current))
throw new ArtifactReaderFailure(
"integrity",
`SQLite snapshot file set changed during acquisition: ${selectedPath}`,
);
return current;
},
},
resourceScope,
),
);
const verifyInactiveJournal = async (
path: string,
before: BigIntStats,
selectedFileSystem: StableArtifactFileSystem,
resourceScope: ArtifactResourceScope,
phase: "initial" | "after-copy",
signal?: AbortSignal,
): Promise<void> => {
if (!before.isFile() || before.isSymbolicLink())
throw new ArtifactReaderFailure(
"path",
`Expected a regular journal without a symlink: ${path}`,
);
const file = await duringAcquisition(path, () =>
selectedFileSystem.open(
path,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
),
);
const owner = new OwnedFileHandle(file);
let failure: unknown;
try {
if (!sameState(before, await file.stat({ bigint: true })))
throw new ArtifactReaderFailure(
"integrity",
`SQLite journal changed before open: ${path}`,
);
// TRUNCATE commits leave an empty file; PERSIST commits zero the complete
// 28-byte fixed header. A new active journal may zero only its magic bytes.
const header = Buffer.alloc(28);
let bytesRead = 0;
if (before.size > 0n) {
while (bytesRead < header.length) {
signal?.throwIfAborted();
const read = await file.read(
header,
bytesRead,
header.length - bytesRead,
bytesRead,
);
if (read.bytesRead === 0) break;
bytesRead += read.bytesRead;
}
}
if (!sameState(before, await file.stat({ bigint: true })))
throw new ArtifactReaderFailure(
"integrity",
`SQLite journal changed during inspection: ${path}`,
);
if (
before.size !== 0n &&
(bytesRead !== header.length || header.some((byte) => byte !== 0))
)
throw new ArtifactReaderFailure(
phase === "initial" ? "format" : "integrity",
phase === "initial"
? `Rollback journal may require recovery: ${path}. Supply a clean offline snapshot; only empty journals or a fully zeroed header are supported.`
: `Rollback journal became active or malformed during database acquisition: ${path}`,
);
} catch (cause: unknown) {
failure = cause;
throw cause;
} finally {
const cleanup = await resourceScope.release({
kind: "file-handle",
resource: path,
handle: owner,
});
if (cleanup.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
failure ?? cleanup.cause,
ArtifactReaderFailure.cleanupObservation(cleanup.cause, path),
);
}
};
/** Freeze a stable offline file set without ever opening the source through SQLite. */
export const captureSqliteDatabaseSnapshot = async (
path: string,
root: string,
resourceScope: ArtifactResourceScope,
signal?: AbortSignal,
selectedFileSystem: StableArtifactFileSystem = fileSystem,
) => {
signal?.throwIfAborted();
const paths = [path, `${path}-wal`, `${path}-journal`];
const before = await Promise.all(
paths.map((path) => optionalStat(path, selectedFileSystem)),
);
const database = before[0];
const wal = before[1];
if (database === undefined || wal === undefined || before[2] === undefined)
throw new Error("Incomplete database file-set observation");
if (database === null)
throw new ArtifactReaderFailure(
"path",
`Selected SQLite database does not exist: ${path}`,
);
if (before[2] !== null)
await verifyInactiveJournal(
`${path}-journal`,
before[2],
selectedFileSystem,
resourceScope,
"initial",
signal,
);
const selectedSize = database.size + (wal?.size ?? 0n);
if (selectedSize > BigInt(SQLITE_DATABASE_LIMITS.inputBytes))
throw new ArtifactReaderFailure(
"limit",
`Selected SQLite database and WAL exceed the combined ${String(SQLITE_DATABASE_LIMITS.inputBytes)}-byte snapshot budget: ${path}`,
);
const snapshotPath = join(root, "database.snapshot");
const captured = await readObservedArtifact(
path,
database,
SQLITE_DATABASE_LIMITS.inputBytes,
selectedFileSystem,
resourceScope,
signal,
);
await writeFile(snapshotPath, captured.bytes, {
flag: "wx",
mode: 0o600,
...(signal === undefined ? {} : { signal }),
});
const artifact = {
path,
sha256: captured.sha256,
bytes: captured.bytes.length,
};
let walArtifact: typeof artifact | null = null;
if (wal !== null) {
const capturedWal = await readObservedArtifact(
`${path}-wal`,
wal,
SQLITE_DATABASE_LIMITS.inputBytes - artifact.bytes,
selectedFileSystem,
resourceScope,
signal,
);
await writeFile(`${snapshotPath}-wal`, capturedWal.bytes, {
flag: "wx",
mode: 0o600,
...(signal === undefined ? {} : { signal }),
});
walArtifact = {
path: `${path}-wal`,
sha256: capturedWal.sha256,
bytes: capturedWal.bytes.length,
};
}
// Identity alone does not establish an inactive journal when timestamps are
// coarse. Re-read the header after copying, using the same validity owner.
if (before[2] !== null)
await verifyInactiveJournal(
`${path}-journal`,
before[2],
selectedFileSystem,
resourceScope,
"after-copy",
signal,
);
const after = await Promise.all(
paths.map((path) =>
duringAcquisition(path, () => optionalStat(path, selectedFileSystem)),
),
);
for (const [index, expected] of before.entries())
if (!sameState(expected, after[index] ?? null))
throw new ArtifactReaderFailure(
"integrity",
`SQLite snapshot file set changed during acquisition: ${paths[index] ?? path}`,
);
signal?.throwIfAborted();
return { snapshotPath, artifact, wal: walArtifact };
};
+57
View File
@@ -0,0 +1,57 @@
import { readFile, writeFile } from "node:fs/promises";
import { z } from "zod";
import { inspectSqliteDatabaseInputSchema } from "../domain/sqlite/sqliteDatabase.js";
import { inspectSqliteDatabaseSnapshot } from "./SqliteDatabaseInspection.js";
import {
SQLITE_DATABASE_LIMITS,
SqliteInspectionFailure,
} from "./SqliteDatabaseLimits.js";
const requestSchema = z.strictObject({
snapshot_path: z.string(),
reply_path: z.string(),
input: inspectSqliteDatabaseInputSchema,
});
const main = async (): Promise<void> => {
const requestPath = process.argv[2];
if (requestPath === undefined)
throw new Error("Owned SQLite worker request path missing.");
const request = requestSchema.parse(
JSON.parse(await readFile(requestPath, "utf8")),
);
let reply: unknown;
try {
reply = {
ok: true,
inspection: inspectSqliteDatabaseSnapshot(
request.snapshot_path,
request.input,
),
};
} catch (cause: unknown) {
const code =
cause instanceof Error && "errcode" in cause ? cause.errcode : undefined;
reply = {
ok: false,
reason:
cause instanceof SqliteInspectionFailure
? cause.reason
: code === 7
? "memory"
: code === 18
? "output-limit"
: "format",
message: cause instanceof Error ? cause.message : String(cause),
};
}
let encoded = JSON.stringify(reply);
if (Buffer.byteLength(encoded) > SQLITE_DATABASE_LIMITS.outputBytes)
encoded = JSON.stringify({
ok: false,
reason: "output-limit",
message:
"Complete SQLite evidence exceeds the 16 MiB JSON reply budget; no partial success was returned.",
});
await writeFile(request.reply_path, encoded, { flag: "wx", mode: 0o600 });
};
await main();
+169
View File
@@ -0,0 +1,169 @@
import { randomUUID } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import type { AnalysisCapturedOutput } from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import {
sqliteDatabaseSchema,
type InspectSqliteDatabaseInput,
} from "../domain/sqlite/sqliteDatabase.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { runOwnedCommand } from "../process/OwnedCommand.js";
import { capturedSqliteOutput } from "./SqliteDatabaseFailures.js";
import { SQLITE_DATABASE_LIMITS } from "./SqliteDatabaseLimits.js";
const operation = "inspect_sqlite_database";
const {
artifact: _artifactSchema,
wal: _walSchema,
...inspectionShape
} = sqliteDatabaseSchema.shape;
const inspectionSchema = z.strictObject(inspectionShape);
const replySchema = z.discriminatedUnion("ok", [
z.strictObject({ ok: z.literal(true), inspection: inspectionSchema }),
z.strictObject({
ok: z.literal(false),
reason: z.enum([
"format",
"selection",
"unsupported",
"unavailable",
"output-limit",
"memory",
]),
message: z.string(),
}),
]);
/** Replaceable launcher retains the shared owned-process supervision boundary. */
export type SqliteWorkerLauncher = NonNullable<
Parameters<typeof runOwnedCommand>[2]
>["launcher"];
const rejectedReply = (
reply: z.output<typeof replySchema> & { ok: false },
capturedOutput: AnalysisCapturedOutput,
) => {
if (reply.reason === "unavailable")
return new AnalysisCapabilityUnavailableError(
"sqlite",
operation,
reply.message,
{ capturedOutput, userMessage: reply.message },
);
if (reply.reason === "memory")
return new AnalysisResourceConstraintError(
operation,
"memory",
reply.message,
{
javascript_heap_bytes: 256 * 1024 * 1024,
},
{ capturedOutput },
);
if (reply.reason === "output-limit")
return new AnalysisResourceConstraintError(
operation,
"transport",
reply.message,
{
sqlite_value_or_record_bytes: SQLITE_DATABASE_LIMITS.outputBytes,
worker_reply_bytes: SQLITE_DATABASE_LIMITS.outputBytes,
},
{ capturedOutput },
);
return new AnalysisInputError(operation, { capturedOutput }, [
{
path: [reply.reason === "selection" ? "table" : "path"],
reason: "invalid_format",
message: reply.message,
},
]);
};
/** Execute only the private snapshot and validate the bounded worker protocol. */
export const executeSqliteDatabaseWorker = async (request: {
readonly input: InspectSqliteDatabaseInput;
readonly root: string;
readonly snapshotPath: string;
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly resourceScope: ArtifactResourceScope;
readonly launcher?: SqliteWorkerLauncher;
readonly signal?: AbortSignal;
readonly captured: (output: AnalysisCapturedOutput) => void;
}): Promise<z.output<typeof inspectionSchema>> => {
const requestPath = join(request.root, "request.json");
const replyPath = join(request.root, "reply.json");
await writeFile(
requestPath,
JSON.stringify({
snapshot_path: request.snapshotPath,
reply_path: replyPath,
input: request.input,
}),
{ flag: "wx", mode: 0o600 },
);
const { NODE_OPTIONS: _ambientNodeOptions, ...environment } =
request.environment;
const execution = await runOwnedCommand(
{
command: process.execPath,
arguments: [
"--max-old-space-size=256",
fileURLToPath(new URL("./SqliteDatabaseWorker.js", import.meta.url)),
requestPath,
],
cwd: request.root,
expectedCommand: null,
runId: `rea-sqlite-database-${randomUUID()}`,
hostEnvironment: environment,
},
{
timeoutMs: SQLITE_DATABASE_LIMITS.timeoutMs,
diagnosticBytes: SQLITE_DATABASE_LIMITS.diagnosticBytes,
},
{
...(request.signal === undefined ? {} : { signal: request.signal }),
...(request.launcher === undefined ? {} : { launcher: request.launcher }),
},
);
const capturedOutput = capturedSqliteOutput(execution);
request.captured(capturedOutput);
let reply: z.output<typeof replySchema>;
try {
const file = await readStableArtifact(
replyPath,
SQLITE_DATABASE_LIMITS.outputBytes,
request.signal,
undefined,
request.resourceScope,
);
reply = replySchema.parse(JSON.parse(file.bytes.toString("utf8")));
} catch (cause: unknown) {
const options = {
cause,
capturedOutput,
...(cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined
? { cleanup: cause.cleanup }
: {}),
};
if (request.signal?.aborted)
throw new AnalysisCancelledError(operation, options);
throw new AnalysisOutputError(
operation,
`Owned SQLite worker reply is missing or malformed: ${cause instanceof Error ? cause.message : String(cause)}`,
options,
);
}
if (!reply.ok) throw rejectedReply(reply, capturedOutput);
return reply.inspection;
};