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,
}),
);
}
}