Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
13 changes: 12 additions & 1 deletion docs/repository-audit-v2-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
28 changes: 27 additions & 1 deletion docs/repository-audit.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
88 changes: 76 additions & 12 deletions src/engine/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,7 @@ async function walkFiles(
root: string,
excludes: ReadonlySet<string>,
links?: string[],
includesPath?: (relative: string) => boolean,
): Promise<RepositoryInventory> {
const files: string[] = [];
const directories: string[] = [];
Expand All @@ -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);
Expand Down Expand Up @@ -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<string, number>();
const frameworks = new Set<string>();
Expand Down Expand Up @@ -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<string>();
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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -4251,14 +4316,13 @@ async function auditRepositoryFacts(
let trackedFiles: Set<string> | 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;
Expand Down
Loading
Loading