diff --git a/docs/architecture.md b/docs/architecture.md index 63de1d3..33f2886 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -134,7 +134,10 @@ verification request's exclusions when the snapshot is copied. With a request, ` those same exclusions plus defaults, independent of configuration. Without a request, `audit` uses the valid configuration's exclusions, like the public `analyze` entry point, or defaults. Audit v2 reports the effective names and their source and reuses one snapshot for both inventories. -An analyze digest can therefore differ from a campaign audit or manifest digest of the same tree. +Git audits additionally select tracked and non-ignored untracked files; `--no-git` and non-Git +audits retain the disk inventory. Audit costs describe that selected inventory, which can be smaller +than a campaign copy containing ignored files. See [audit inventory rules](repository-audit.md). +An analyze digest can therefore differ from an audit or manifest digest of the same tree. Candidate contents and world overlays have separate digests. Preserve the snapshot and resolved dependency identities for stronger provenance. diff --git a/docs/repository-audit-v2-migration.md b/docs/repository-audit-v2-migration.md index 767f0da..cffb2ec 100644 --- a/docs/repository-audit-v2-migration.md +++ b/docs/repository-audit-v2-migration.md @@ -13,7 +13,7 @@ schema to the existing conformance rail without regenerating any frozen lock. V2 adds `appliedExcludes: { source, entries }`. Entries are sorted, unique portable entry names, including the defaults `.git`, `.testforge`, and `node_modules`. With a verification request, source is `request` and entries derive exclusively -from `request.repository.exclude` plus defaults, exactly as campaign copying does. +from `request.repository.exclude` plus defaults, as campaign copying does. Configuration never removes additional files from a campaign audit. Without a request, a valid `assertledger.config.json` supplies source `config`; otherwise source is `defaults`. CLI explicit requests and automatic @@ -32,3 +32,14 @@ This changes the audited inventory and may change its digest, byte count, and campaign cost projection compared with v1. Campaign execution and its manifest and decision digest projections are unchanged. Consumers validating audit JSON must select the v2 schema; do not strip disclosure and relabel current output as v1. + +## Git ignore correction + +Current Git audits additionally filter their inventory through Git's tracked and non-ignored +untracked file list. This corrects local ignored caches affecting audit digests and counts without +changing the v2 schema or digest byte encoding. Trees with the same selected files retain their +previous audit digest. Ignored extras and submodule contents are no longer selected, so they can +change the digest and cost estimate compared with previous audits, even in a clean checkout. Historical +v1/v2 artifacts remain readable. Campaign manifests, decision and artifact digest projections, +and the disk-based `analyze` operation are unchanged. See [audit inventory rules](repository-audit.md) +for disk fallbacks, working-tree edits, links, and the limits of audit cost estimates. diff --git a/docs/repository-audit.md b/docs/repository-audit.md index ace52e3..92aaf91 100644 --- a/docs/repository-audit.md +++ b/docs/repository-audit.md @@ -6,11 +6,37 @@ verification verdict. Current output uses [audit v2](repository-audit-v2-migration.md), which preserves the factual measurements and adds `appliedExcludes: { source, entries }`. With a verification request, its -exclusions plus defaults define the inventory, matching the campaign copy; configuration adds no +exclusions plus defaults filter the inventory; configuration adds no exclusions. Without a request, audit uses a valid initialization configuration, otherwise defaults. Both inventories reuse the same exclusion snapshot. Historical v1 artifacts remain readable with the unchanged v1 parser and schema. +In a Git worktree, audit selects tracked files and non-ignored untracked files using +`git -c core.precomposeUnicode=false ls-files --cached --others --exclude-standard -z`, +then applies the exclusions above. Disabling Git's macOS name precomposition for this listing +preserves disk spellings: admitted non-NFC names retain the existing portable-path refusal rather +than being silently omitted. Ignore patterns are evaluated against these literal spellings. +When `core.ignorecase` is true, ASCII case differences between the index and disk names are +reconciled while retaining the disk spelling. This includes case-only file and directory renames; +it does not normalize Unicode aliases. Once a Git inventory is selected, a failed or invalid case +configuration query refuses with `GIT_INDEX_UNAVAILABLE`. +Git's nested `.gitignore`, `.git/info/exclude`, and global ignore rules apply to untracked files; +tracked files remain included even if an ignore rule matches them. Audit reads current disk bytes, +including staged and unstaged edits, and omits deleted files. It does not recurse into submodules. +Included symlinks, including directory links, still refuse the inventory. Filenames retain their +spelling and must satisfy the existing portable-path rules. + +Outside a Git worktree, when Git is unavailable, or with `--no-git`, audit retains the disk inventory; +ignore rules do not apply. Once a Git inventory is selected, a failed index listing refuses with +`GIT_INDEX_UNAVAILABLE` instead of silently widening the inventory. Both inventories requery Git. + +An ignored local index cache such as `.semctx/semctx.db` can be created, rebuilt, or removed without +changing the Git audit's `repositoryDigest`, `fileCount`, or byte-based cost estimate. For comparable +proof epochs, preserve the working-tree content, ignore rules, and explicit exclusions: an audit +digest is not solely a commit identifier. Campaign copying and manifest digest projections remain +unchanged and can still include ignored caches unless explicitly excluded in the request; audit +costs describe its own inventory rather than the campaign's complete disk copy. + ```sh assertledger audit . --json assertledger audit . --verification-request request.json --json diff --git a/src/engine/index.ts b/src/engine/index.ts index 9d249e1..c9e89a6 100644 --- a/src/engine/index.ts +++ b/src/engine/index.ts @@ -675,6 +675,7 @@ async function walkFiles( root: string, excludes: ReadonlySet, links?: string[], + includesPath?: (relative: string) => boolean, ): Promise { const files: string[] = []; const directories: string[] = []; @@ -685,8 +686,9 @@ async function walkFiles( const entries = await readdir(directory, { withFileTypes: true }); entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0)); for (const entry of entries) { - if (excludes.has(portablePathKey(entry.name))) continue; const relative = path.posix.join(relativeDirectory.split(path.sep).join("/"), entry.name); + if (includesPath !== undefined && !includesPath(relative)) continue; + if (excludes.has(portablePathKey(entry.name))) continue; const entryStats = await lstat(path.join(root, ...relative.split("/"))); if (entryStats.isSymbolicLink()) { if (links === undefined) throw repositoryLinkError(relative); @@ -3987,6 +3989,10 @@ export async function analyzeRepository( options.excludes ?? (options.configuredExcludes === true ? await configuredRepositoryExcludes(root) : []); const { files } = await walkFiles(root, effectiveExcludes(declaredExcludes)); + return analyzeRepositoryFiles(root, files); +} + +async function analyzeRepositoryFiles(root: string, files: string[]) { const digest = createHash("sha256"); const languageCounts = new Map(); const frameworks = new Set(); @@ -4139,17 +4145,68 @@ async function auditGit(root: string, args: string[]): Promise<{ ok: boolean; st cwd: root, shell: false, windowsHide: true, + timeout: 10_000, + env: Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => + !["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE"].includes( + name.toUpperCase(), + ), + ), + ), stdio: ["ignore", "pipe", "ignore"], }); const chunks: Buffer[] = []; child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk)); child.on("error", () => resolve({ ok: false, stdout: "" })); - child.on("close", (code) => - resolve({ ok: code === 0, stdout: Buffer.concat(chunks).toString("utf8").trim() }), - ); + child.on("close", (code) => { + try { + resolve({ + ok: code === 0, + stdout: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode( + Buffer.concat(chunks), + ), + }); + } catch { + resolve({ ok: false, stdout: "" }); + } + }); }); } +async function auditGitPaths(root: string): Promise<(relative: string) => boolean> { + const caseConfig = await auditGit(root, [ + "config", + "--type=bool", + "--default=false", + "--get", + "core.ignorecase", + ]); + const caseValue = caseConfig.stdout.trim(); + if (!caseConfig.ok || (caseValue !== "true" && caseValue !== "false")) + throw new Error(knownDiagnosticCode("GIT_INDEX_UNAVAILABLE")); + const pathKey = (relative: string): string => + caseValue === "true" ? relative.replace(/[A-Z]/gu, (letter) => letter.toLowerCase()) : relative; + const result = await auditGit(root, [ + "-c", + "core.precomposeUnicode=false", + "ls-files", + "--cached", + "--others", + "--exclude-standard", + "-z", + ]); + if (!result.ok || (result.stdout.length > 0 && !result.stdout.endsWith("\0"))) + throw new Error(knownDiagnosticCode("GIT_INDEX_UNAVAILABLE")); + const paths = new Set(); + for (const file of result.stdout.split("\0").filter(Boolean)) { + const segments = file.split("/"); + for (let length = 1; length <= segments.length; length += 1) + paths.add(pathKey(segments.slice(0, length).join("/"))); + } + return (relative) => paths.has(pathKey(relative)); +} + function associatedAuditTests(source: string, tests: readonly string[]): string[] { const basename = path.posix.basename(source).replace(/\.[^.]+$/u, ""); return tests @@ -4203,12 +4260,20 @@ async function auditRepositoryFacts( } } const appliedExcludes = { source, entries: [...effectiveExcludes(declaredExcludes)].sort() }; + const worktree = options.noGit + ? { ok: false, stdout: "" } + : await auditGit(root, ["rev-parse", "--is-inside-work-tree"]); + const gitInventory = worktree.ok && worktree.stdout.trim() === "true"; const inventory = async () => { try { - return (await analyzeRepository(root, { excludes: appliedExcludes.entries })) as { - repositoryDigest: string; - files: string[]; - }; + const includedPaths = gitInventory ? await auditGitPaths(root) : undefined; + const { files } = await walkFiles( + root, + effectiveExcludes(appliedExcludes.entries), + undefined, + includedPaths, + ); + return await analyzeRepositoryFiles(root, files); } catch (error) { if (error instanceof Error && error.message === "UNSUPPORTED_REPOSITORY_SYMLINK") { throw new RepositoryAuditInventoryError( @@ -4251,14 +4316,13 @@ async function auditRepositoryFacts( let trackedFiles: Set | null = null; if (options.noGit) reasonCodes.add("GIT_DISABLED"); else { - const worktree = await auditGit(root, ["rev-parse", "--is-inside-work-tree"]); - if (!worktree.ok || worktree.stdout !== "true") reasonCodes.add("GIT_UNAVAILABLE"); + if (!gitInventory) reasonCodes.add("GIT_UNAVAILABLE"); else { const head = await auditGit(root, ["show", "-s", "--format=%ct", "HEAD"]); const shallowResult = await auditGit(root, ["rev-parse", "--is-shallow-repository"]); - if (head.ok && /^\d+$/u.test(head.stdout) && shallowResult.ok) { + if (head.ok && /^\d+$/u.test(head.stdout.trim()) && shallowResult.ok) { headTimestamp = Number(head.stdout); - shallow = shallowResult.stdout === "true"; + shallow = shallowResult.stdout.trim() === "true"; if (shallow) reasonCodes.add("GIT_HISTORY_SHALLOW"); else { gitSupported = true; diff --git a/tests/repository-audit.test.ts b/tests/repository-audit.test.ts index dfb2f12..c7e638b 100644 --- a/tests/repository-audit.test.ts +++ b/tests/repository-audit.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; -import childProcess, { execFile } from "node:child_process"; -import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import childProcess, { execFile, type SpawnOptions } from "node:child_process"; +import { mkdir, mkdtemp, rename, rm, symlink, writeFile } from "node:fs/promises"; import { syncBuiltinESMExports } from "node:module"; import os from "node:os"; import path from "node:path"; @@ -11,7 +11,7 @@ import { parseRepositoryAuditV2, repositoryAuditJsonSchema, } from "../src/contracts/index.js"; -import { auditRepository, initializeRepository } from "../src/engine/index.js"; +import { analyzeRepository, auditRepository, initializeRepository } from "../src/engine/index.js"; import { explainReasonCodes } from "../src/diagnostics.js"; import { AssertLedger } from "../src/sdk/index.js"; import { runPublicCli } from "./support/public-surface.js"; @@ -20,6 +20,361 @@ const temporaryDirectories: string[] = []; const execFileAsync = promisify(execFile); describe("audit exclusions", () => { + async function gitFixture() { + const root = await fixture(); + await execFileAsync("git", ["init", "-q"], { cwd: root }); + await execFileAsync("git", ["add", "."], { cwd: root }); + return root; + } + + async function cliAudit(root: string) { + let stdout = ""; + let stderr = ""; + const exit = await runPublicCli(["audit", ".", "--json"], { + cwd: root, + writeStdout: (text) => { + stdout += text; + }, + writeStderr: (text) => { + stderr += text; + }, + }); + assert.equal(exit, 0, stderr); + return parseRepositoryAuditV2(JSON.parse(stdout)); + } + + it("keeps the digest and count stable across local index-cache writes", async () => { + const root = await fixture(); + await writeFile(path.join(root, ".gitignore"), ".semctx/\n"); + await execFileAsync("git", ["init", "-q"], { cwd: root }); + await execFileAsync("git", ["add", "."], { cwd: root }); + await execFileAsync( + "git", + [ + "-c", + "user.name=Audit Fixture", + "-c", + "user.email=audit@example.invalid", + "commit", + "-qm", + "initial", + ], + { cwd: root }, + ); + const before = await auditRepository(root); + assert.equal((await cliAudit(root)).repositoryDigest, before.repositoryDigest); + assert.equal(before.fileCount, 4); + const diskBefore = (await analyzeRepository(root)) as { repositoryDigest: string }; + assert.equal(before.repositoryDigest, diskBefore.repositoryDigest); + await mkdir(path.join(root, ".semctx")); + for (const content of ["first index", "rebuilt index"]) { + await writeFile(path.join(root, ".semctx", "semctx.db"), content); + const after = await auditRepository(root); + assert.equal(after.repositoryDigest, before.repositoryDigest); + assert.equal(after.fileCount, before.fileCount); + assert.equal(after.repositoryBytes, before.repositoryBytes); + const cli = await cliAudit(root); + assert.equal(cli.repositoryDigest, before.repositoryDigest); + assert.equal(cli.fileCount, before.fileCount); + assert.deepEqual(after.files, before.files); + const diskAfter = (await analyzeRepository(root)) as { repositoryDigest: string }; + assert.notEqual(diskAfter.repositoryDigest, before.repositoryDigest); + } + await rm(path.join(root, ".semctx"), { recursive: true }); + assert.equal((await auditRepository(root)).repositoryDigest, before.repositoryDigest); + }); + + it("reads working-tree bytes for tracked, staged and permitted untracked files", async () => { + const root = await gitFixture(); + const before = await auditRepository(root); + await writeFile(path.join(root, "README.md"), "staged\n"); + await execFileAsync("git", ["add", "README.md"], { cwd: root }); + const staged = await auditRepository(root); + assert.notEqual(staged.repositoryDigest, before.repositoryDigest); + await writeFile(path.join(root, "README.md"), "unstaged\n"); + const unstaged = await auditRepository(root); + assert.notEqual(unstaged.repositoryDigest, staged.repositoryDigest); + await writeFile(path.join(root, ".gitignore"), "README.md\n*.local\n"); + await writeFile(path.join(root, "new.ts"), "export const added = true;\n"); + await writeFile(path.join(root, "ignored.local"), "ignored\n"); + const added = await auditRepository(root); + assert.deepEqual( + added.files.map((file) => file.path), + [".gitignore", "new.ts", "README.md", "src/choice.ts", "tests/choice.test.ts"], + ); + await rm(path.join(root, "README.md")); + const deleted = await auditRepository(root); + assert.equal(deleted.fileCount, added.fileCount - 1); + assert(!deleted.files.some((file) => file.path === "README.md")); + assert.notEqual(deleted.repositoryDigest, added.repositoryDigest); + }); + + for (const renamed of [ + { from: "README.md", to: "readme.md", file: "readme.md" }, + { from: "src", to: "SRC", file: "SRC/choice.ts" }, + ]) { + it(`retains tracked bytes after a case-only rename of ${renamed.from}`, async () => { + const root = await gitFixture(); + await execFileAsync("git", ["config", "core.ignorecase", "true"], { cwd: root }); + await writeFile(path.join(root, ".gitignore"), `${renamed.to}\n`); + const before = await auditRepository(root); + await rename(path.join(root, renamed.from), path.join(root, "rename-temporary")); + await rename(path.join(root, "rename-temporary"), path.join(root, renamed.to)); + const after = await auditRepository(root); + assert.equal(after.fileCount, before.fileCount); + assert(after.files.some((file) => file.path === renamed.file)); + await writeFile(path.join(root, renamed.file), "export const changed = true;\n"); + assert.notEqual((await auditRepository(root)).repositoryDigest, after.repositoryDigest); + }); + } + + it("does not admit an ignored case alias when Git uses case-sensitive paths", async () => { + const root = await gitFixture(); + await execFileAsync("git", ["config", "core.ignorecase", "false"], { cwd: root }); + await writeFile(path.join(root, ".gitignore"), "readme.md\n"); + await rm(path.join(root, "README.md")); + const before = await auditRepository(root); + await writeFile(path.join(root, "readme.md"), "ignored replacement\n"); + assert.equal((await auditRepository(root)).repositoryDigest, before.repositoryDigest); + }); + + it("uses nested ignores, negations, local excludes and explicit request exclusions", async () => { + const root = await gitFixture(); + await writeFile(path.join(root, ".gitignore"), "*.cache\n"); + await writeFile(path.join(root, "src", ".gitignore"), "!kept.cache\n"); + await writeFile(path.join(root, ".git", "info", "exclude"), "local.db\n"); + const globalIgnore = path.join(root, ".git", "global-ignore"); + await writeFile(globalIgnore, "global.tmp\n"); + await execFileAsync("git", ["config", "core.excludesFile", globalIgnore], { cwd: root }); + await writeFile(path.join(root, "global.tmp"), "ignored\n"); + await writeFile(path.join(root, "local.db"), "ignored\n"); + await writeFile(path.join(root, "src", "hidden.cache"), "ignored\n"); + if (process.platform !== "win32") + await writeFile(path.join(root, "src", "nonportable?.cache"), "ignored\n"); + await writeFile(path.join(root, "src", "kept.cache"), "included\n"); + const verificationRequest = request(root); + verificationRequest.repository.exclude = ["tests"]; + const result = await auditRepository(root, { verificationRequest }); + assert.deepEqual( + result.files.map((file) => file.path), + [".gitignore", "README.md", "src/.gitignore", "src/choice.ts", "src/kept.cache"], + ); + assert.equal(result.appliedExcludes.source, "request"); + }); + + it("retains disk inventory outside Git and when Git is explicitly disabled", async () => { + const root = await fixture(); + await writeFile(path.join(root, ".gitignore"), "cache.db\n"); + await writeFile(path.join(root, "cache.db"), "local index\n"); + const outsideGit = await auditRepository(root); + assert.equal(outsideGit.fileCount, 5); + assert(outsideGit.reasonCodes.includes("GIT_UNAVAILABLE")); + await execFileAsync("git", ["init", "-q"], { cwd: root }); + const disabled = await auditRepository(root, { noGit: true }); + assert.equal(disabled.repositoryDigest, outsideGit.repositoryDigest); + assert(disabled.reasonCodes.includes("GIT_DISABLED")); + assert.equal((await auditRepository(root)).fileCount, 4); + }); + + it("ignores excluded links but refuses admitted links and linked ancestors", async () => { + const root = await gitFixture(); + await writeFile(path.join(root, ".gitignore"), "ignored-link\n"); + await symlink(path.join(root, "src"), path.join(root, "ignored-link"), "junction"); + assert.equal((await auditRepository(root)).fileCount, 4); + await symlink(path.join(root, "src"), path.join(root, "admitted-link"), "junction"); + await assert.rejects(auditRepository(root), (error: unknown) => { + assert.match(String(error), /UNSUPPORTED_REPOSITORY_SYMLINK/u); + assert.equal((error as Error).cause, "admitted-link"); + return true; + }); + await rm(path.join(root, "admitted-link")); + await rename(path.join(root, "src"), path.join(root, "original-src")); + await symlink(path.join(root, "original-src"), path.join(root, "src"), "junction"); + await assert.rejects(auditRepository(root), (error: unknown) => { + assert.match(String(error), /UNSUPPORTED_REPOSITORY_SYMLINK/u); + assert.equal((error as Error).cause, "src"); + return true; + }); + }); + + it("refuses a tracked ancestor replaced by a case-renamed directory link", async () => { + const root = await gitFixture(); + await execFileAsync("git", ["config", "core.ignorecase", "true"], { cwd: root }); + await rename(path.join(root, "src"), path.join(root, "original-src")); + await symlink(path.join(root, "original-src"), path.join(root, "SRC"), "junction"); + await assert.rejects(auditRepository(root), (error: unknown) => { + assert.match(String(error), /UNSUPPORTED_REPOSITORY_SYMLINK/u); + assert.equal((error as Error).cause, "SRC"); + return true; + }); + }); + + it("preserves spaces and Unicode in Git filenames and audits a subdirectory", async () => { + const root = await gitFixture(); + await writeFile(path.join(root, " leading-space.ts"), "export const value = 1;\n"); + await writeFile(path.join(root, "src", "café.ts"), "export const cafe = 1;\n"); + await execFileAsync("git", ["add", "."], { cwd: root }); + const result = await auditRepository(root); + assert.equal(result.fileCount, 5); + assert(result.files.some((file) => file.path === " leading-space.ts")); + const nested = await auditRepository(path.join(root, "src")); + assert.equal(nested.fileCount, 2); + assert(nested.files.every((file) => !file.path.startsWith("src/"))); + }); + + it("never admits an ignored Unicode alias of a missing tracked file", async () => { + const root = await gitFixture(); + await execFileAsync("git", ["config", "core.precomposeUnicode", "false"], { cwd: root }); + await writeFile(path.join(root, ".gitignore"), "cafe\u0301.ts\n"); + await writeFile(path.join(root, "café.ts"), "tracked\n"); + await execFileAsync("git", ["add", "."], { cwd: root }); + await rm(path.join(root, "café.ts")); + const before = await auditRepository(root); + await writeFile(path.join(root, "cafe\u0301.ts"), "ignored\n"); + let after: Awaited> | undefined; + await assert.doesNotReject(async () => { + after = await auditRepository(root); + }); + assert.equal(after?.repositoryDigest, before.repositoryDigest); + assert.equal(after?.fileCount, before.fileCount); + }); + + it("refuses a nonportable tracked name even when Git precomposes Unicode", async () => { + const root = await gitFixture(); + await execFileAsync("git", ["config", "core.precomposeUnicode", "true"], { cwd: root }); + await writeFile(path.join(root, "cafe\u0301.ts"), "tracked\n"); + await execFileAsync("git", ["add", "."], { cwd: root }); + await assert.rejects(auditRepository(root), /Ambiguous Unicode path segment must use NFC/u); + }); + + it("rechecks Git membership while tolerating writes to ignored files", async () => { + const root = await gitFixture(); + await writeFile(path.join(root, ".gitignore"), "cache.db\n"); + const before = await auditRepository(root); + const during = await auditRepository(root, { + afterInitialInventory: () => writeFile(path.join(root, "cache.db"), "new cache\n"), + }); + assert.equal(during.repositoryDigest, before.repositoryDigest); + await assert.rejects( + auditRepository(root, { + afterInitialInventory: () => + writeFile(path.join(root, "new.ts"), "export const value = 1;\n"), + }), + /REPOSITORY_CHANGED_DURING_AUDIT/u, + ); + await assert.rejects( + auditRepository(root, { + afterInitialInventory: () => + writeFile(path.join(root, ".git", "info", "exclude"), "new.ts\n"), + }), + /REPOSITORY_CHANGED_DURING_AUDIT/u, + ); + }); + + it("refuses a broken Git index instead of silently inventorying ignored files", async () => { + const root = await gitFixture(); + await writeFile(path.join(root, ".git", "index"), "corrupt index"); + await assert.rejects(auditRepository(root), /GIT_INDEX_UNAVAILABLE/u); + }); + + it("audits empty Git repositories and linked worktrees", async () => { + const root = await gitFixture(); + const emptyRoot = await mkdtemp(path.join(os.tmpdir(), "assertledger-audit-empty-")); + temporaryDirectories.push(emptyRoot); + await execFileAsync("git", ["init", "-q"], { cwd: emptyRoot }); + assert.equal((await auditRepository(emptyRoot)).fileCount, 0); + await writeFile(path.join(root, ".gitignore"), "cache.db\n"); + await execFileAsync("git", ["add", "."], { cwd: root }); + await execFileAsync( + "git", + [ + "-c", + "user.name=Audit Fixture", + "-c", + "user.email=audit@example.invalid", + "commit", + "-qm", + "initial", + ], + { cwd: root }, + ); + const linkedRoot = path.join(root, ".testforge", "linked"); + await execFileAsync( + "git", + ["-c", "core.autocrlf=false", "worktree", "add", "--detach", linkedRoot], + { cwd: root }, + ); + await writeFile(path.join(linkedRoot, "cache.db"), "ignored cache\n"); + const linked = await auditRepository(linkedRoot); + assert.equal(linked.fileCount, 4); + assert.equal(linked.repositoryDigest, (await auditRepository(root)).repositoryDigest); + }); + + it("does not use an inherited Git index for a different repository", async () => { + const root = await gitFixture(); + await writeFile(path.join(root, ".gitignore"), "README.md\n"); + const previous = process.env.GIT_INDEX_FILE; + process.env.GIT_INDEX_FILE = path.join(root, ".git", "other-index"); + try { + const result = await auditRepository(root); + assert.equal(result.fileCount, 4); + assert(result.files.some((file) => file.path === "README.md")); + } finally { + if (previous === undefined) delete process.env.GIT_INDEX_FILE; + else process.env.GIT_INDEX_FILE = previous; + } + }); + + it("refuses unavailable or malformed Git case configuration", async (context) => { + const root = await gitFixture(); + const spawn = childProcess.spawn; + let program = "process.exit(2)"; + const replacement = context.mock.method( + childProcess, + "spawn", + (command: string, args: string[], options: SpawnOptions) => + command === "git" && args[0] === "config" + ? spawn(process.execPath, ["-e", program], options) + : spawn(command, args, options), + ); + syncBuiltinESMExports(); + try { + await assert.rejects(auditRepository(root), /GIT_INDEX_UNAVAILABLE/u); + program = "process.stdout.write('maybe\\n')"; + await assert.rejects(auditRepository(root), /GIT_INDEX_UNAVAILABLE/u); + } finally { + replacement.mock.restore(); + syncBuiltinESMExports(); + } + }); + + it("refuses incomplete or invalid UTF-8 Git listings", async (context) => { + const root = await gitFixture(); + const spawn = childProcess.spawn; + let output = Buffer.from("README.md"); + const replacement = context.mock.method( + childProcess, + "spawn", + (command: string, args: string[], options: SpawnOptions) => + command === "git" && args.includes("ls-files") + ? spawn( + process.execPath, + ["-e", `process.stdout.write(Buffer.from('${output.toString("hex")}', 'hex'))`], + options, + ) + : spawn(command, args, options), + ); + syncBuiltinESMExports(); + try { + await assert.rejects(auditRepository(root), /GIT_INDEX_UNAVAILABLE/u); + output = Buffer.from([0xff, 0x00]); + await assert.rejects(auditRepository(root), /GIT_INDEX_UNAVAILABLE/u); + } finally { + replacement.mock.restore(); + syncBuiltinESMExports(); + } + }); + it("exposes the new audit schema in the CLI and retains the v1 selector", async () => { const ledger = new AssertLedger(); for (const name of ["repository-audit", "repository-audit-v2"] as const) {