merge: integrate main and retain per-slice FAT alignment

This commit is contained in:
64579525
2026-10-13 16:21:36 +08:00
74 changed files with 2682 additions and 566 deletions
@@ -0,0 +1,88 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
snapshotBinding,
snapshotTarget,
} from "../../../src/domain/analysisSnapshot.js";
import {
ANALYSIS_SNAPSHOT_PROFILE,
ANALYSIS_SNAPSHOT_TARGET,
} from "../../../src/domain/analysisSnapshot.fixture.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe.each([
{ mode: "native", paddingBytes: 0 },
{ mode: "streamed", paddingBytes: 9 * 1024 * 1024 },
])("analysis snapshot input ($mode)", ({ paddingBytes }) => {
it.each(["[]", "null", "5", '"x"', "true"])(
"classifies a readable %s root as invalid content, not an I/O failure",
async (document) => {
const root = await createTestTempDirectory("rea-snapshot-root-");
const path = join(root, "snapshot.json");
const encoded = `${" ".repeat(paddingBytes)}${document}`;
await writeFile(path, encoded);
const loaded = await readAnalysisSnapshot(path);
if (loaded.ok) throw new Error("Expected a non-object root rejection");
const projected = projectAnalysisError(loaded.error);
expect(projected).toMatchObject({
code: "evidence_integrity_mismatch",
details: { reason: "invalid-json" },
});
expect(projected.message).toContain("Repair or recreate");
expect(loaded.error.cause).toMatchObject({
message: "JSON document root must be an object",
});
expect(await readFile(path, "utf8")).toBe(encoded);
},
);
it("retains syntax and snapshot-member validation and loads valid objects", async () => {
const root = await createTestTempDirectory("rea-snapshot-validation-");
const path = join(root, "snapshot.json");
const prefix = " ".repeat(paddingBytes);
await writeFile(path, `${prefix}[`);
expect(await readAnalysisSnapshot(path)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "invalid-json" },
});
await writeFile(path, `${prefix}{}`);
expect(await readAnalysisSnapshot(path)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
const snapshot = {
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
binding: snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE),
entries: [],
workflow_entries: [],
evidence_bundle: createEvidenceBundle([]),
};
await writeFile(path, `${prefix}${JSON.stringify(snapshot)}`);
expect(await readAnalysisSnapshot(path)).toEqual({
ok: true,
value: snapshot,
});
});
});
it("keeps file-selection failures distinct from invalid snapshot contents", async () => {
const root = await createTestTempDirectory("rea-snapshot-selection-");
for (const [path, reason] of [
[join(root, "missing.json"), "missing"],
[root, "not-file"],
] as const) {
const loaded = await readAnalysisSnapshot(path);
if (loaded.ok) throw new Error("Expected a file-selection failure");
expect(projectAnalysisError(loaded.error)).toMatchObject({
code: "invalid_request",
details: { reason },
});
}
});
@@ -152,7 +152,7 @@ describe("TypeScript source module loader semantics", () => {
});
});
describe("CommonJS and ESM module relationships", () => {
describe("JavaScript module relationships", () => {
it("composes bindings, re-exports, dynamic imports, and JSON modules", async () => {
const root = await moduleFixture();
const first = await reconstructJavaScriptFixture(root);
@@ -288,6 +288,122 @@ describe("CommonJS and ESM module relationships", () => {
});
});
describe("Compiler-dependent TypeScript resolution", () => {
it("retains only compiler-independent targets for .ts static imports", async () => {
const root = await createTestTempDirectory("rea-ts-conditional-loader-");
await writeFixtureFiles(root, {
"package.json": '{"type":"commonjs"}',
"main.ts": `import { value as different } from "different";
import { value as same } from "same";
void different; void same;`,
"node_modules/different/package.json": JSON.stringify({
exports: {
".": {
import: "./import.mjs",
require: "./require.cjs",
},
},
}),
"node_modules/different/import.mjs": "export const value = 'import';",
"node_modules/different/require.cjs": "exports.value = 'require';",
"node_modules/same/package.json": JSON.stringify({
exports: { ".": { import: "./shared.js", require: "./shared.js" } },
}),
"node_modules/same/shared.js": "export const value = 'shared';",
});
const { graph } = await reconstructJavaScriptFixture(root);
const different = findRelationshipEdge(graph, {
kind: "import",
specifier: "different",
localName: "different",
});
const same = findRelationshipEdge(graph, {
kind: "import",
specifier: "same",
localName: "same",
resolvedPath: "node_modules/same/shared.js",
});
const staticFinding = (specifier: string) =>
graph.edges.find(
({ relation, properties }) =>
relation === "imports" &&
properties.kind === "static-import" &&
properties.specifier === specifier,
);
expect(
findSourceModule(graph, "main.ts")?.observations[0]?.properties,
).toMatchObject({ module_format: "unknown" });
expect(different).toMatchObject({
properties: {
resolution_mode: "compiler-dependent",
resolution_status: "unavailable",
resolved_path: null,
conditional_resolutions: [
{
mode: "import",
resolution_status: "resolved",
resolved_path: "node_modules/different/import.mjs",
},
{
mode: "require",
resolution_status: "resolved",
resolved_path: "node_modules/different/require.cjs",
},
],
},
});
expect(same).toMatchObject({
properties: {
resolution_mode: "compiler-dependent",
resolved_path: "node_modules/same/shared.js",
resolution_status: "resolved",
},
evidence: {
limitations: expect.arrayContaining([
expect.stringContaining(
"compiler-dependent without retained compiler options",
),
]),
},
});
expect(staticFinding("different")).toMatchObject({
properties: {
resolution_mode: "compiler-dependent",
resolution_status: "unavailable",
conditional_resolutions: [
{
mode: "import",
resolved_path: "node_modules/different/import.mjs",
},
{
mode: "require",
resolved_path: "node_modules/different/require.cjs",
},
],
},
evidence: {
limitations: expect.arrayContaining([
expect.stringContaining(
"compiler-dependent without retained compiler options",
),
]),
},
});
expect(staticFinding("same")).toMatchObject({
properties: { resolved_path: "node_modules/same/shared.js" },
evidence: {
limitations: expect.arrayContaining([
expect.stringContaining(
"compiler-dependent without retained compiler options",
),
]),
},
});
});
});
it("does not assign one module origin to an export with colliding path encodings", async () => {
const root = await createTestTempDirectory("rea-ambiguous-module-origin-");
await writeFixtureFiles(root, {
@@ -31,9 +31,12 @@ it("reads exact binary and empty bytes and rejects symlink/size/cancellation bou
});
const controller = new AbortController();
controller.abort();
await expect(readStableArtifact(real, 3, controller.signal)).rejects.toBe(
controller.signal.reason,
);
await expect(
readStableArtifact(real, 3, controller.signal),
).rejects.toMatchObject({
reason: "cancelled",
cause: controller.signal.reason,
});
});
const checkChange = async (
@@ -0,0 +1,96 @@
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
const injected = vi.hoisted(() => ({
sourcePath: undefined as string | undefined,
abortController: undefined as AbortController | undefined,
failClose: false,
closeAttempts: 0,
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
...actual,
open: async (...args: Parameters<typeof actual.open>) => {
const handle = await actual.open(...args);
if (args[0] !== injected.sourcePath) return handle;
const createReadStream = handle.createReadStream.bind(handle);
handle.createReadStream = (options) => {
injected.abortController?.abort();
return createReadStream(options);
};
const close = handle.close.bind(handle);
handle.close = async () => {
injected.closeAttempts += 1;
if (injected.failClose) throw new Error("fixture close refusal");
await close();
};
return handle;
},
};
});
import { WebModuleTraceService } from "../../../src/application/WebModuleTraceService.js";
import { LocalWebModuleArtifacts } from "../../../src/browser/modules/WebModuleArtifacts.js";
import { webModuleArtifactsFixture } from "../../fixtures/webModuleTrace.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("retains cancelled source read ownership until service close retries it", async () => {
const root = await createTestTempDirectory("rea-web-artifact-read-owner-");
onTestFinished(async () => {
injected.sourcePath = undefined;
injected.abortController = undefined;
injected.failClose = false;
injected.closeAttempts = 0;
await rm(root, { recursive: true, force: true });
});
const source = 'import "./dep.js";';
const fixture = webModuleArtifactsFixture(source);
const manifestPath = join(root, "manifest.json");
const sourcePath = join(root, "files", "modules", "main.js");
await mkdir(join(root, "files", "modules"), { recursive: true });
await writeFile(sourcePath, source);
await writeFile(manifestPath, JSON.stringify(fixture.manifest));
injected.sourcePath = sourcePath;
injected.failClose = true;
const controller = new AbortController();
injected.abortController = controller;
const resolver = {
resolve: vi.fn(),
close: vi.fn(async () => undefined),
};
const service = new WebModuleTraceService(
new LocalWebModuleArtifacts(),
resolver,
);
const input = { manifest_path: manifestPath, script_index: 0 };
const cancelled = await service.trace(input, { signal: controller.signal });
expect(cancelled.ok).toBe(false);
if (cancelled.ok) throw new Error("Expected cancelled source read");
expect(cancelled.error.cleanupIncomplete).toBe(true);
expect(cancelled.error.cleanupResources).toContain(sourcePath);
expect(resolver.resolve).not.toHaveBeenCalled();
injected.abortController = undefined;
const blocked = await service.trace(input);
expect(blocked.ok).toBe(false);
if (blocked.ok) throw new Error("Expected retained cleanup to block load");
expect(blocked.error.cleanupIncomplete).toBe(true);
expect(injected.closeAttempts).toBe(2);
await expect(service.close()).rejects.toThrow(
"Web module trace cleanup failed",
);
expect(resolver.close).toHaveBeenCalledTimes(1);
expect(injected.closeAttempts).toBe(3);
injected.failClose = false;
const attemptsBeforeRetry = injected.closeAttempts;
await service.close();
expect(injected.closeAttempts).toBeGreaterThan(attemptsBeforeRetry);
expect(resolver.close).toHaveBeenCalledTimes(2);
});