fix(reference)!: retain source and metadata cleanup owners

Require a caller-owned artifact resource scope for source traversal and Git metadata reads. Preserve cancellation, filesystem reasons, partial entries and bytes, and cleanup observations through import and the CLI. Transfer exact failed file owners at regular-file admission and close boundaries, including multiple failures encountered by Git reference resolution.

Validation: 169 focused tests passed across 26 files; two Windows-only cases skipped. Build, typecheck, lint, formatting, knip, architecture guards, discovery and docs checks passed.

BREAKING CHANGE: Reference source readers and imports require an ArtifactResourceScope. VCS metadata reads return Result, and CLI import failures include observed details and partial evidence.
This commit is contained in:
morluto
2026-10-11 06:10:10 +08:00
parent 215001a1ce
commit 53e7fadbd0
30 changed files with 1450 additions and 222 deletions
+1 -1
View File
@@ -62,7 +62,7 @@ describe("CLI startup imports", () => {
await expect(
resolvedPackages(
evaluate(
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); await readReferenceSourceVcs(${JSON.stringify(source)});`,
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); const { ArtifactResourceScope } = await import("./dist/artifacts/ArtifactResourceScope.js"); const resources = new ArtifactResourceScope(); try { await readReferenceSourceVcs(${JSON.stringify(source)}, resources); } finally { await resources.close(); }`,
),
),
).resolves.toContain("isomorphic-git");
@@ -6,18 +6,12 @@ import { describe, expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const invalidRootOutput = {
error: "Import failed",
category: "invalid_input",
message:
"Reference source directory could not be opened. Check that the path exists, is readable, and points to a directory.",
};
const unsupportedHostOutput = {
error: "Import failed",
category: "unsupported_host",
message:
"Safe no-follow file opens are unavailable on this host. Import the source tree with REA on Linux (including WSL) or macOS.",
message: expect.stringContaining(
"Safe no-follow file opens are unavailable on this host.",
),
};
const permissionChecksUnavailable =
@@ -105,6 +99,15 @@ describe("compiled reference-source import preflight failures", () => {
...(scenario.logging ? { REA_LOG_LEVEL: "info" } : {}),
},
});
const rootReason =
scenario.rootKind === "missing"
? "Reference source root could not be resolved"
: "Reference source root is not a directory";
const invalidRootOutput = {
error: "Import failed",
category: "invalid_input",
message: expect.stringContaining(rootReason),
};
if (scenario.fullOutput) {
// Incur's legacy wrapper remains unchanged; operation status is
// conveyed by the exit code and command log, not this `ok` field.
@@ -113,8 +116,12 @@ describe("compiled reference-source import preflight failures", () => {
data: invalidRootOutput,
});
} else {
expect(result.json).toEqual(invalidRootOutput);
expect(result.json).toMatchObject(invalidRootOutput);
}
expect(JSON.stringify(result.json)).toContain(
"Check that the path exists, is readable, and points to a directory.",
);
expect(JSON.stringify(result.json)).toContain(root);
expect.soft(result.exitCode).toBe(1);
if (scenario.logging) {
const records: unknown[] = result.stderr
@@ -157,12 +164,15 @@ describe("compiled reference-source import preflight failures", () => {
XDG_CACHE_HOME: directory,
},
});
expect(result.json).toEqual({
expect(result.json).toMatchObject({
error: "Import failed",
category: "execution_failure",
message:
"Reference source files could not be read. Check directory permissions and try again.",
message: expect.stringContaining("EACCES: permission denied"),
});
expect(JSON.stringify(result.json)).toContain(root);
expect(JSON.stringify(result.json)).toContain(
"Check directory permissions and try again.",
);
expect(result.exitCode).toBe(1);
} finally {
await chmod(parent, 0o700);
@@ -0,0 +1,304 @@
import {
mkdir,
open as fsOpen,
opendir as fsOpendir,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vitest";
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { readReferenceSource } from "../../../src/reference/ReferenceSourceReader.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
...actual,
open: vi.fn(actual.open),
opendir: vi.fn(actual.opendir),
};
});
const openMock = vi.mocked(fsOpen);
const opendirMock = vi.mocked(fsOpendir);
let actual: typeof import("node:fs/promises");
beforeEach(async () => {
actual =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
openMock.mockImplementation((...args) => actual.open(...args));
opendirMock.mockImplementation((...args) => actual.opendir(...args));
});
afterEach(() => {
openMock.mockReset();
opendirMock.mockReset();
});
it("preserves admission EIO and retains an invalidated failed-close owner", async () => {
const root = await createTestTempDirectory("rea-reference-admission-owner-");
const file = join(root, "source.ts");
await writeFile(file, "export const answer = 42;\n");
const resources = new ArtifactResourceScope();
onTestFinished(() => resources.close().catch(() => undefined));
const statFailure = Object.assign(new Error("injected admission EIO"), {
code: "EIO",
});
const closeFailure = new Error("native close rejected after invalidation");
let closeCalls = 0;
openMock.mockImplementation(async (...args) => {
const handle = await actual.open(...args);
vi.spyOn(handle, "stat").mockRejectedValueOnce(statFailure);
const close = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeCalls += 1;
await close();
throw closeFailure;
});
return handle;
});
const result = await readReferenceSource(root, resources);
expect(result).toMatchObject({
ok: false,
error: {
tag: "reference-source-reader",
code: "io",
message: expect.stringContaining("EIO"),
cleanup: {
resources: [file],
reason: expect.stringContaining(closeFailure.message),
},
partial: {
entries: [
{
status: "failed",
kind: "file",
path: "source.ts",
code: "io",
message: expect.stringContaining("EIO"),
},
],
},
},
});
expect(closeCalls).toBe(1);
await expect(resources.close()).rejects.toMatchObject({
cleanup: {
resources: [file],
reason: expect.stringContaining(closeFailure.message),
},
});
expect(closeCalls).toBe(1);
});
it("retains partial file bytes and retries the same live owner before new work", async () => {
const root = await createTestTempDirectory("rea-reference-file-owner-");
const file = join(root, "source.ts");
const bytes = "export const answer = 'retained';\n";
await writeFile(file, bytes);
const resources = new ArtifactResourceScope();
const closeFailure = new Error("injected close before native close");
let allowClose = false;
onTestFinished(async () => {
allowClose = true;
await resources.close().catch(() => undefined);
});
let closeCalls = 0;
let openCalls = 0;
openMock.mockImplementation(async (...args) => {
openCalls += 1;
const handle = await actual.open(...args);
const close = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeCalls += 1;
if (!allowClose) throw closeFailure;
await close();
});
return handle;
});
const first = await importReferenceSource(
{
root,
caller: "reference-source-cleanup-owner-test",
policy: { secretPatterns: [] },
},
resources,
);
expect(first).toMatchObject({
ok: false,
error: {
code: "io",
cleanup: {
resources: [file],
reason: expect.stringContaining(closeFailure.message),
},
partial: {
entries: [
{
status: "read",
kind: "file",
path: "source.ts",
bytes: Buffer.from(bytes),
},
],
bytesRead: Buffer.byteLength(bytes),
},
},
});
expect(openCalls).toBe(1);
expect(closeCalls).toBe(1);
const blocked = await readReferenceSource(root, resources);
expect(blocked).toMatchObject({
ok: false,
error: {
code: "io",
cleanup: { resources: [file] },
},
});
expect(openCalls).toBe(1);
expect(closeCalls).toBe(2);
allowClose = true;
await resources.close();
expect(openCalls).toBe(1);
expect(closeCalls).toBe(3);
});
it("preserves a directory read failure when closing that directory also fails", async () => {
const root = await createTestTempDirectory(
"rea-reference-directory-read-owner-",
);
const file = join(root, "source.ts");
const bytes = "observed before directory EIO\n";
await writeFile(file, bytes);
const resources = new ArtifactResourceScope();
onTestFinished(() => resources.close().catch(() => undefined));
const readFailure = Object.assign(new Error("injected directory EIO"), {
code: "EIO",
});
const closeFailure = new Error("directory close rejected after invalidation");
let readCalls = 0;
let closeCalls = 0;
opendirMock.mockImplementation(async (...args) => {
const directory = await actual.opendir(...args);
const read = directory.read.bind(directory);
vi.spyOn(directory, "read").mockImplementation(async () => {
if (readCalls++ > 0) throw readFailure;
return read();
});
const close = directory.close.bind(directory);
vi.spyOn(directory, "close").mockImplementation(async () => {
closeCalls += 1;
await close();
throw closeFailure;
});
return directory;
});
const result = await readReferenceSource(root, resources);
if (result.ok) throw new Error("Directory and cleanup failures were ignored");
expect(result).toMatchObject({
ok: false,
error: {
code: "io",
message: expect.stringContaining(readFailure.message),
cleanup: {
resources: [root],
reason: expect.stringContaining(closeFailure.message),
},
partial: {
bytesRead: Buffer.byteLength(bytes),
},
},
});
expect(result.error.partial?.entries).toContainEqual(
expect.objectContaining({
status: "read",
kind: "file",
path: "source.ts",
bytes: Buffer.from(bytes),
}),
);
expect(result.error.partial?.entries).toContainEqual({
status: "failed",
kind: "directory",
path: ".",
code: "io",
message: expect.stringContaining(readFailure.message),
});
expect(closeCalls).toBe(1);
await expect(resources.close()).rejects.toMatchObject({
cleanup: {
resources: [root],
reason: expect.stringContaining(closeFailure.message),
},
});
expect(closeCalls).toBe(1);
});
it("keeps cancelled traversal typed when native directory close rejects after invalidation", async () => {
const root = await createTestTempDirectory("rea-reference-directory-owner-");
await mkdir(join(root, "child"));
const resources = new ArtifactResourceScope();
onTestFinished(() => resources.close().catch(() => undefined));
const controller = new AbortController();
const closeFailure = new Error("native directory close rejected");
let closeCalls = 0;
let openedPath: string | undefined;
opendirMock.mockImplementation(async (...args) => {
const directory = await actual.opendir(...args);
openedPath = String(args[0]);
const read = directory.read.bind(directory);
vi.spyOn(directory, "read").mockImplementation(async () => {
const child = await read();
if (child !== null) controller.abort();
return child;
});
const close = directory.close.bind(directory);
vi.spyOn(directory, "close").mockImplementation(async () => {
closeCalls += 1;
await close();
throw closeFailure;
});
return directory;
});
const result = await readReferenceSource(root, resources, {
signal: controller.signal,
});
expect(result).toMatchObject({
ok: false,
error: {
code: "cancelled",
cleanup: {
resources: [root],
reason: expect.stringContaining(closeFailure.message),
},
partial: { entries: [] },
},
});
expect(openedPath).toBe(root);
expect(closeCalls).toBe(1);
await expect(resources.close()).rejects.toMatchObject({
cleanup: {
resources: [root],
reason: expect.stringContaining(closeFailure.message),
},
});
expect(closeCalls).toBe(1);
});
@@ -6,8 +6,8 @@ import { promisify } from "node:util";
import { expect, it } from "vitest";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
it("distinguishes computed require member values from literal members in source evidence", async () => {
const root = await createTestTempDirectory("rea-reference-require-members-");
@@ -4,8 +4,8 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
it("imports Dockerfile-prefixed TypeScript with ordinary source evidence and uncertainty", async () => {
const root = await createTestTempDirectory("rea-dockerfile-language-");
@@ -3,8 +3,8 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
it("resolves dynamic source imports while retaining computed targets as unknown", async () => {
const root = await createTestTempDirectory("rea-reference-dynamic-import-");
@@ -5,9 +5,11 @@ import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { readReferenceSource } from "../../../src/reference/ReferenceSourceReader.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
importReferenceSource,
readReferenceSource,
} from "../../support/referenceSourceResourceScope.js";
const importTree = (root: string) =>
importReferenceSource({
@@ -7,19 +7,13 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
importReferenceSource,
normalizeHistoricalSourceParseFailures,
} from "../../../src/application/ReferenceSourceImport.js";
import { normalizeHistoricalSourceParseFailures } from "../../../src/application/ReferenceSourceImport.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
import {
parseReferenceSourceEntries,
projectReferenceSourceEntryFailure,
} from "../../../src/application/ReferenceSourceImportEntries.js";
import type { ReferenceSourceRead } from "../../../src/reference/ReferenceSourceReaderTypes.js";
import {
projectReferenceSourceImportError,
type ReferenceSourceImportError,
} from "../../../src/application/ReferenceSourceImportTypes.js";
import { createHistoricalSourceManifest } from "../../../src/domain/referenceSourceGraph.js";
const fixture = async (parent: string, name: string): Promise<string> => {
@@ -49,7 +43,7 @@ const importTree = (
...(signal === undefined ? {} : { signal }),
});
describe("reference source import error projection", () => {
describe("reference source import projections", () => {
it("deduplicates exact parse failures without collapsing distinct reasons", () => {
const malformed = {
path: "src/main.ts",
@@ -92,29 +86,6 @@ describe("reference source import error projection", () => {
expect(message).toMatch(/Check|try again|when ready|Exclude/u);
}
});
it("projects every import failure without raw parser or policy text", () => {
const expectedCategories = {
cancelled: "cancelled",
"invalid-root": "invalid_input",
unsupported: "unsupported_host",
io: "execution_failure",
parse: "execution_failure",
} as const;
for (const [code, category] of Object.entries(expectedCategories)) {
const projected = projectReferenceSourceImportError({
tag: "reference-source-import",
code: code as ReferenceSourceImportError["code"],
message: "SECRET parser stack and /private/path",
});
expect(projected.category).toBe(category);
expect(projected.message).not.toContain("SECRET");
expect(projected.message).not.toContain("/private/path");
expect(projected.message).toMatch(
/try again|when ready|Check that|REA on Linux/u,
);
}
});
});
describe("reference source symlink import", () => {
@@ -0,0 +1,226 @@
import { mkdir, open as fsOpen, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vitest";
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { readReferenceSourceVcs } from "../../../src/application/ReferenceSourceVcsAdapter.js";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return { ...actual, open: vi.fn(actual.open) };
});
const openMock = vi.mocked(fsOpen);
let actual: typeof import("node:fs/promises");
beforeEach(async () => {
actual =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
openMock.mockImplementation((...args) => actual.open(...args));
});
afterEach(() => openMock.mockReset());
const failCloseUntilAllowed = (
target: string,
): { readonly allow: () => void; readonly calls: () => number } => {
const closeFailure = new Error("injected metadata close failure");
let allowClose = false;
let closeCalls = 0;
openMock.mockImplementation(async (...args) => {
const handle = await actual.open(...args);
if (resolve(String(args[0])) !== resolve(target)) return handle;
const close = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeCalls += 1;
if (!allowClose) throw closeFailure;
await close();
});
return handle;
});
return {
allow: () => {
allowClose = true;
},
calls: () => closeCalls,
};
};
it("retains failed .gitignore cleanup under the caller's scope", async () => {
const root = await createTestTempDirectory("rea-reference-ignore-owner-");
const path = join(root, ".gitignore");
await writeFile(path, "generated/\n");
const resources = new ArtifactResourceScope();
const close = failCloseUntilAllowed(path);
onTestFinished(async () => {
close.allow();
await resources.close().catch(() => undefined);
});
const result = await importReferenceSource(
{
root,
caller: "reference-source-metadata-cleanup-test",
policy: { secretPatterns: [] },
},
resources,
);
expect(result).toMatchObject({
ok: false,
error: {
code: "io",
cleanup: {
resources: [path],
reason: expect.stringContaining("injected metadata close failure"),
},
},
});
expect(close.calls()).toBe(2);
close.allow();
await resources.close();
expect(close.calls()).toBe(3);
});
it("preserves Git metadata cleanup failure and the completed source read", async () => {
const root = await createTestTempDirectory("rea-reference-head-owner-");
const repository = join(root, "repository");
const sourceRoot = join(root, "source");
await Promise.all([mkdir(repository), mkdir(sourceRoot)]);
await execFileOutput("git", ["init", "--initial-branch=main"], {
cwd: repository,
});
const source = join(sourceRoot, "main.ts");
const bytes = "export const value = 1;\n";
await writeFile(source, bytes);
await writeFile(join(sourceRoot, ".git"), "gitdir: ../repository/.git\n");
const head = join(sourceRoot, ".git");
const resources = new ArtifactResourceScope();
const close = failCloseUntilAllowed(head);
onTestFinished(async () => {
close.allow();
await resources.close().catch(() => undefined);
});
const result = await importReferenceSource(
{
root: sourceRoot,
excludePaths: [".git"],
caller: "reference-source-metadata-cleanup-test",
policy: { secretPatterns: [] },
},
resources,
);
expect(result).toMatchObject({
ok: false,
error: {
code: "io",
cleanup: {
resources: [head],
reason: expect.stringContaining("injected metadata close failure"),
},
partial: {
entries: [
{
kind: "file",
path: "main.ts",
bytes: Buffer.from(bytes),
},
],
},
},
});
expect(close.calls()).toBe(2);
close.allow();
await resources.close();
expect(close.calls()).toBe(3);
});
it("retains later packed-ref cleanup after an earlier loose-ref read failure", async () => {
const root = await createTestTempDirectory("rea-reference-packed-owner-");
await execFileOutput("git", ["init", "--initial-branch=main"], { cwd: root });
await writeFile(join(root, "main.ts"), "export const value = 1;\n");
await execFileOutput(
"git",
[
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.invalid",
"-c",
"commit.gpgsign=false",
"commit",
"--allow-empty",
"-m",
"fixture",
],
{ cwd: root },
);
const head = (
await execFileOutput("git", ["rev-parse", "HEAD"], { cwd: root })
).stdout.trim();
await execFileOutput("git", ["pack-refs", "--all", "--prune"], { cwd: root });
const looseRef = join(root, ".git", "refs", "heads", "main");
const packedRefs = join(root, ".git", "packed-refs");
await actual.mkdir(join(root, ".git", "refs", "heads"), { recursive: true });
await writeFile(looseRef, `${head}\n`);
const resources = new ArtifactResourceScope();
let allowClose = false;
let looseReadFailed = false;
const packedCloseCalls = new Map<object, number>();
openMock.mockImplementation(async (...args) => {
const handle = await actual.open(...args);
const path = resolve(String(args[0]));
if (path === resolve(looseRef)) {
vi.spyOn(handle, "read").mockImplementation(async () => {
looseReadFailed = true;
throw Object.assign(new Error("injected loose ref EIO"), {
code: "EIO",
});
});
}
if (path === resolve(packedRefs)) {
const close = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
packedCloseCalls.set(handle, (packedCloseCalls.get(handle) ?? 0) + 1);
if (!allowClose) throw new Error("injected packed-refs close failure");
await close();
});
}
return handle;
});
onTestFinished(async () => {
allowClose = true;
await resources.close().catch(() => undefined);
});
const result = await readReferenceSourceVcs(root, resources);
expect(looseReadFailed).toBe(true);
expect(result).toMatchObject({
ok: false,
error: {
code: "io",
cleanup: {
resources: [packedRefs],
reason: expect.stringContaining("injected packed-refs close failure"),
},
},
});
expect([...packedCloseCalls.values()]).toEqual(
Array.from({ length: packedCloseCalls.size }, () => 2),
);
allowClose = true;
await resources.close();
expect([...packedCloseCalls.values()]).toEqual(
Array.from({ length: packedCloseCalls.size }, () => 3),
);
});
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { readReferenceSource } from "../../../src/reference/ReferenceSourceReader.js";
import { readReferenceSource } from "../../support/referenceSourceResourceScope.js";
describe("readReferenceSource entries", () => {
it("returns explicit entries in canonical code-point path order", async () => {
@@ -158,12 +158,17 @@ describe("readReferenceSource failures and exclusions", () => {
},
});
expect(result).toEqual({
expect(result).toMatchObject({
ok: false,
error: {
tag: "reference-source-reader",
code: "io",
message: "Reference source exclusion check failed",
partial: {
root,
entries: [],
bytesRead: 0,
},
},
});
});
@@ -4,12 +4,10 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import {
importReferenceSource,
normalizeHistoricalSourceParseFailures,
} from "../../../src/application/ReferenceSourceImport.js";
import { normalizeHistoricalSourceParseFailures } from "../../../src/application/ReferenceSourceImport.js";
import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
const sources = {
"fatal.js": 'import "./valid";\nconst = ;',
@@ -4,8 +4,8 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
it("imports test-suffixed filenames with unchanged paths, hashes, and languages", async () => {
const root = await createTestTempDirectory("rea-reference-test-filenames-");
@@ -3,8 +3,8 @@ import { join } from "node:path";
import { expect, it } from "vitest";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
it.each([
["main.ts", "dep.js", "dep.ts"],
@@ -3,9 +3,11 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { readReferenceSource } from "../../../src/reference/ReferenceSourceReader.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
importReferenceSource,
readReferenceSource,
} from "../../support/referenceSourceResourceScope.js";
const importTree = (root: string) =>
importReferenceSource({
@@ -2,9 +2,17 @@ import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { readReferenceSourceVcs } from "../../../src/application/ReferenceSourceVcsAdapter.js";
const readVcs = (root: string, signal?: AbortSignal) =>
withArtifactResourceScope(async (resources) => {
const result = await readReferenceSourceVcs(root, resources, signal);
if (!result.ok) throw result.error;
return result.value;
});
it("reads a linked worktree's own branch and detached HEAD through shared Git refs", async () => {
const root = await createTestTempDirectory("rea-reference-worktree-");
const repository = join(root, "repository");
@@ -49,18 +57,18 @@ it("reads a linked worktree's own branch and detached HEAD through shared Git re
await execFileOutput("git", ["rev-parse", "HEAD"], { cwd: linked })
).stdout.trim();
expect(linkedHead).not.toBe(mainHead);
expect(await readReferenceSourceVcs(repository)).toEqual({
expect(await readVcs(repository)).toEqual({
kind: "git",
head: mainHead,
dirty: null,
});
expect(await readReferenceSourceVcs(linked)).toEqual({
expect(await readVcs(linked)).toEqual({
kind: "git",
head: linkedHead,
dirty: null,
});
await git("pack-refs", "--all", "--prune");
expect(await readReferenceSourceVcs(linked)).toEqual({
expect(await readVcs(linked)).toEqual({
kind: "git",
head: linkedHead,
dirty: null,
@@ -68,7 +76,7 @@ it("reads a linked worktree's own branch and detached HEAD through shared Git re
await execFileOutput("git", ["checkout", "--detach", mainHead], {
cwd: linked,
});
expect(await readReferenceSourceVcs(linked)).toEqual({
expect(await readVcs(linked)).toEqual({
kind: "git",
head: mainHead,
dirty: null,
@@ -79,7 +87,7 @@ it("reads a linked worktree's own branch and detached HEAD through shared Git re
join(relativePointer, ".git"),
"gitdir: ../repository/.git\r\n",
);
expect(await readReferenceSourceVcs(relativePointer)).toEqual({
expect(await readVcs(relativePointer)).toEqual({
kind: "git",
head: mainHead,
dirty: null,
@@ -87,14 +95,14 @@ it("reads a linked worktree's own branch and detached HEAD through shared Git re
// A non-regular loose ref must remain unknown even when packed-refs has
// a readable value. The library's promise-API probe is not a source failure.
await mkdir(join(repository, ".git", "refs", "heads", "main"));
expect(await readReferenceSourceVcs(repository)).toEqual({
expect(await readVcs(repository)).toEqual({
kind: "unknown",
head: null,
dirty: null,
});
const controller = new AbortController();
controller.abort();
expect(await readReferenceSourceVcs(linked, controller.signal)).toEqual({
expect(await readVcs(linked, controller.signal)).toEqual({
kind: "unknown",
head: null,
dirty: null,
@@ -4,11 +4,11 @@ import { expect, it } from "vitest";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { parseApplicationGraphEvidence } from "../../../src/application/javascript/JavaScriptApplicationEvidenceGraph.js";
import { importReferenceSource } from "../../../src/application/ReferenceSourceImport.js";
import { findApplicationFeatureSeeds } from "../../../src/domain/javascript/javascriptFeatureSeed.js";
import { compareSourceToBundle } from "../../../src/domain/javascript/sourceToBundleComparison.js";
import { resolveSourceMapSource } from "../../../src/javascript/sourceMaps/DecodedSourceMap.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { importReferenceSource } from "../../support/referenceSourceResourceScope.js";
it("keeps literal hash characters in historical/current filesystem paths", async () => {
const root = await createTestTempDirectory("rea-source-path-");
+28 -18
View File
@@ -9,23 +9,33 @@ if (modulePath === undefined || root === undefined)
throw new Error("Reference reader FIFO probe requires module and root paths");
const { readStableFile } = await import(pathToFileURL(modulePath));
const absolute = join(root, "source.txt");
await writeFile(absolute, "observed regular file\n");
const expected = await lstat(absolute, { bigint: true });
await unlink(absolute);
execFileSync("mkfifo", [absolute]);
const { ArtifactResourceScope } = await import(
new URL("../artifacts/ArtifactResourceScope.js", pathToFileURL(modulePath))
);
const resources = new ArtifactResourceScope();
try {
const absolute = join(root, "source.txt");
await writeFile(absolute, "observed regular file\n");
const expected = await lstat(absolute, { bigint: true });
await unlink(absolute);
execFileSync("mkfifo", [absolute]);
// Capture the directory after replacement to reach the file-open boundary.
// The owning test bounds this child if an O_RDONLY FIFO open blocks again.
const rootIdentity = await lstat(root, { bigint: true });
const result = await readStableFile({
root,
rootIdentity,
absolute,
path: "source.txt",
expected,
});
assert.equal(result.status, "failed");
assert.equal(result.kind, "file");
assert.equal(result.code, "changed");
// Capture the directory after replacement to reach the file-open boundary.
// The owning test bounds this child if an O_RDONLY FIFO open blocks again.
const rootIdentity = await lstat(root, { bigint: true });
const result = await readStableFile({
resources,
root,
rootIdentity,
absolute,
path: "source.txt",
expected,
});
assert.equal(result.cleanup, undefined);
assert.equal(result.entry.status, "failed");
assert.equal(result.entry.kind, "file");
assert.equal(result.entry.code, "changed");
} finally {
await resources.close();
}
process.stdout.write("changed\n");
@@ -0,0 +1,16 @@
import { importReferenceSource as importOwned } from "../../src/application/ReferenceSourceImport.js";
import type { ReferenceSourceImportOptions } from "../../src/application/ReferenceSourceImportTypes.js";
import { readReferenceSource as readOwned } from "../../src/reference/ReferenceSourceReader.js";
import type { ReferenceSourceReaderOptions } from "../../src/reference/ReferenceSourceReaderTypes.js";
import { withArtifactResourceScope } from "../fixtures/artifactInventory.js";
/** Run one reference-source test operation with an awaited resource owner. */
export const importReferenceSource = (options: ReferenceSourceImportOptions) =>
withArtifactResourceScope((resources) => importOwned(options, resources));
/** Read one reference-source test tree with an awaited resource owner. */
export const readReferenceSource = (
root: string,
options: ReferenceSourceReaderOptions = {},
) =>
withArtifactResourceScope((resources) => readOwned(root, resources, options));