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
7 changes: 6 additions & 1 deletion .archgate/config.json
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
{ "domains": { "ci": "CI" }, "baseBranch": "origin/main", "strict": true }
{
"domains": { "ci": "CI" },
"baseBranch": "origin/main",
"strict": true,
"briefingMaxSectionChars": 4200
}
7 changes: 6 additions & 1 deletion docs/public/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5284,7 +5284,8 @@ This file is created automatically by `archgate init` (to store the auto-detecte
"domains": { "security": "SEC", "compliance": "COMP" },
"paths": { "adrs": "docs/adrs", "rules": "docs/adrs" },
"baseBranch": "main",
"strict": true
"strict": true,
"briefingMaxSectionChars": 4200
}
```

Expand Down Expand Up @@ -5330,6 +5331,10 @@ Resolution order is CLI flag, then this config value, then `false`. There is no
{ "strict": true }
```

### `briefingMaxSectionChars`

Maximum characters per ADR `Decision` and `Do's and Don'ts` section in `archgate review-context --verbose`. `archgate check` and `archgate review-context --run-checks` report sections exceeding the same limit, and strict mode still fails on those findings. Set a positive integer; the default is `2000`.

### `paths`

Override default directories for ADRs and rules.
Expand Down
7 changes: 6 additions & 1 deletion docs/src/content/docs/nb/reference/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ Denne filen opprettes automatisk av `archgate init` (for å lagre den autodetekt
"domains": { "security": "SEC", "compliance": "COMP" },
"paths": { "adrs": "docs/adrs", "rules": "docs/adrs" },
"baseBranch": "main",
"strict": true
"strict": true,
"briefingMaxSectionChars": 4200
}
```

Expand Down Expand Up @@ -60,6 +61,10 @@ Løsningsrekkefølgen er kommandolinjevalg, deretter denne konfigurasjonsverdien
{ "strict": true }
```

### `briefingMaxSectionChars`

Maksimalt antall tegn per `Decision`- og `Do's and Don'ts`-del i en ADR ved bruk av `archgate review-context --verbose`. `archgate check` og `archgate review-context --run-checks` rapporterer deler som overskrider den samme grensen. Streng modus feiler fortsatt ved slike funn. Bruk et positivt heltall. Standardverdien er `2000`.

### `paths`

Overstyr standardkataloger for ADR-er og regler.
Expand Down
7 changes: 6 additions & 1 deletion docs/src/content/docs/pt-br/reference/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ Este arquivo é criado automaticamente pelo `archgate init` (para armazenar o br
"domains": { "security": "SEC", "compliance": "COMP" },
"paths": { "adrs": "docs/adrs", "rules": "docs/adrs" },
"baseBranch": "main",
"strict": true
"strict": true,
"briefingMaxSectionChars": 4200
}
```

Expand Down Expand Up @@ -60,6 +61,10 @@ A ordem de resolução é: flag de linha de comando, depois este valor de config
{ "strict": true }
```

### `briefingMaxSectionChars`

Limite de caracteres para cada seção `Decision` e `Do's and Don'ts` de um ADR em `archgate review-context --verbose`. `archgate check` e `archgate review-context --run-checks` relatam as seções que ultrapassam o mesmo limite, e o modo estrito continua falhando quando há esses diagnósticos. Use um número inteiro positivo; o padrão é `2000`.

### `paths`

Sobrescreve os diretórios padrão para ADRs e regras.
Expand Down
7 changes: 6 additions & 1 deletion docs/src/content/docs/reference/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ This file is created automatically by `archgate init` (to store the auto-detecte
"domains": { "security": "SEC", "compliance": "COMP" },
"paths": { "adrs": "docs/adrs", "rules": "docs/adrs" },
"baseBranch": "main",
"strict": true
"strict": true,
"briefingMaxSectionChars": 4200
}
```

Expand Down Expand Up @@ -60,6 +61,10 @@ Resolution order is CLI flag, then this config value, then `false`. There is no
{ "strict": true }
```

### `briefingMaxSectionChars`

Maximum characters per ADR `Decision` and `Do's and Don'ts` section in `archgate review-context --verbose`. `archgate check` and `archgate review-context --run-checks` report sections exceeding the same limit, and strict mode still fails on those findings. Set a positive integer; the default is `2000`.

### `paths`

Override default directories for ADRs and rules.
Expand Down
16 changes: 14 additions & 2 deletions src/engine/adr-sections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { relative } from "node:path";

import type { AdrDocument } from "../formats/adr";
import { loadProjectConfig } from "../helpers/project-config";
import { getSkippedAdrs, parseAllAdrs } from "./loader";

/**
Expand All @@ -14,6 +15,17 @@ export const BRIEFED_SECTIONS = ["Decision", "Do's and Don'ts"] as const;
/** Max chars per briefed section before truncation. 0 = unlimited. */
export const DEFAULT_MAX_SECTION_CHARS = 2000;

export function resolveBriefingSectionLimit(
projectRoot: string,
override?: number
): number {
return (
override ??
loadProjectConfig(projectRoot).briefingMaxSectionChars ??
DEFAULT_MAX_SECTION_CHARS
);
}

/**
* Extract named `##` sections from ADR markdown body.
* Missing sections map to empty strings. Matching is case-insensitive.
Expand Down Expand Up @@ -119,7 +131,7 @@ export function collectBriefingBudgetWarnings(
/**
* Budget diagnostics for a project, project-relative, covering every ADR.
*
* @param maxChars - Cap the caller truncates at; defaults to the engine's.
* @param maxChars - Cap the caller truncates at; otherwise uses project config.
* @returns Over-budget sections, plus ADRs that failed to parse.
*/
export async function collectBriefingDiagnostics(
Expand All @@ -132,7 +144,7 @@ export async function collectBriefingDiagnostics(
const parsed = await parseAllAdrs(projectRoot);
const briefingWarnings = collectBriefingBudgetWarnings(
parsed.map((entry) => entry.adr),
maxChars
resolveBriefingSectionLimit(projectRoot, maxChars)
).map((w) => ({
adrId: w.adrId,
file: relative(projectRoot, w.file).replaceAll("\\", "/"),
Expand Down
6 changes: 5 additions & 1 deletion src/engine/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
DEFAULT_MAX_SECTION_CHARS,
collectBriefingDiagnostics,
extractAdrSections,
resolveBriefingSectionLimit,
truncateSection,
} from "./adr-sections";
import {
Expand Down Expand Up @@ -200,7 +201,10 @@ export async function buildReviewContext(
): Promise<ReviewContext> {
const staged = options?.staged ?? false;
const maxFiles = options?.maxChangedFiles ?? 200;
const maxSectionChars = options?.maxSectionChars ?? DEFAULT_MAX_SECTION_CHARS;
const maxSectionChars = resolveBriefingSectionLimit(
projectRoot,
options?.maxSectionChars
);
const maxViolationsPerRule = options?.maxViolationsPerRule ?? 20;

const base = options?.base;
Expand Down
3 changes: 3 additions & 0 deletions src/formats/project-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ export const ProjectConfigSchema = z
paths: PathsConfigSchema.optional(),
baseBranch: z.string().min(1).optional(),
strict: z.boolean().optional(),
// An invalid optional cap must leave other settings, including strict, usable.
// oxlint-disable-next-line unicorn/no-useless-undefined
briefingMaxSectionChars: z.int().positive().optional().catch(undefined),
})
.default({ domains: {} });

Expand Down
19 changes: 11 additions & 8 deletions src/helpers/binary-upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,11 +276,9 @@ export async function downloadReleaseBinary(
);
}
} else {
// Bun.Archive reads tar and tar.gz only, so the Windows `.zip` release
// keeps PowerShell; switching the artifact to tar.gz would break every
// shim, each of which downloads `.zip` for win32 (ARCH-017).
// `-ErrorAction Stop` promotes Expand-Archive's non-terminating error to
// a terminating one; without it PowerShell exits 0 on a corrupt archive.
// Windows releases use ZIP for the shims (ARCH-017). Call the
// two-argument .NET Framework API because PowerShell 5.1 lacks the
// overwrite overload used by newer Microsoft.PowerShell.Archive versions.
const windowsPowerShell = join(
usableEnv(Bun.env.SystemRoot) ?? "C:\\Windows",
"System32",
Expand All @@ -297,15 +295,20 @@ export async function downloadReleaseBinary(
}
const archivePath = join(tmpDir, `archgate${artifact.ext}`);
await Bun.write(archivePath, buffer);
const { exitCode } = await runCapture([
const source = archivePath.replaceAll("'", "''");
const destination = tmpDir.replaceAll("'", "''");
const { exitCode, stderr } = await runCapture([
shell,
"-NoProfile",
"-Command",
`Expand-Archive -Path '${archivePath}' -DestinationPath '${tmpDir}' -Force -ErrorAction Stop`,
"$ErrorActionPreference = 'Stop'; " +
"Add-Type -AssemblyName System.IO.Compression.FileSystem; " +
`[System.IO.Compression.ZipFile]::ExtractToDirectory('${source}', '${destination}')`,
]);
if (exitCode !== 0) {
const detail = stderr.trim();
throw new UserError(
`Failed to extract archive (PowerShell exit code ${exitCode})`
`Failed to extract archive (PowerShell exit code ${exitCode})${detail ? `:\n${detail}` : ""}`
);
}
}
Expand Down
18 changes: 18 additions & 0 deletions tests/engine/adr-sections.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,4 +225,22 @@ describe("collectBriefingDiagnostics", () => {
const loose = await collectBriefingDiagnostics(dir, 0);
expect(loose.briefingWarnings).toEqual([]);
});

test("checks every briefed section against the configured cap", async () => {
await Bun.write(
join(dir, ".archgate", "config.json"),
JSON.stringify({ strict: true, briefingMaxSectionChars: 8 })
);
await writeAdrFile(
"ARCH-001-x.md",
"---\nid: ARCH-001\ntitle: X\ndomain: architecture\nrules: false\n---\n\n## Decision\n12345678\n\n## Do's and Don'ts\n123456789\n"
);
const { briefingWarnings } = await collectBriefingDiagnostics(dir);
expect(briefingWarnings).toHaveLength(1);
expect(briefingWarnings[0]).toMatchObject({
section: "Do's and Don'ts",
cap: 8,
length: 9,
});
});
});
22 changes: 21 additions & 1 deletion tests/engine/context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
buildReviewContext,
} from "../../src/engine/context";
import type { AdrDocument, AdrDomain } from "../../src/formats/adr";
import { safeRmSync } from "../test-utils";
import { git, safeRmSync } from "../test-utils";

function makeAdr(
overrides: Partial<AdrDocument["frontmatter"]> = {},
Expand Down Expand Up @@ -372,6 +372,26 @@ export default {
expect(ctx.checkSummary!.total).toBe(0);
});

test("uses the configured limit for both briefings and strict diagnostics", async () => {
await git(["init"], tempDir);
writeAdr("ARCH-001", "architecture");
writeFileSync(
join(tempDir, ".archgate", "config.json"),
JSON.stringify({ briefingMaxSectionChars: 8 })
);
await git(["add", "."], tempDir);
const ctx = await buildReviewContext(tempDir, {
briefings: true,
runChecks: true,
staged: true,
strict: true,
});
expect(ctx.domains[0].adrs[0].decision).toStartWith("Use ARCH\n\n");
expect(ctx.truncatedBriefings).toEqual(["ARCH-001"]);
expect(ctx.checkSummary?.briefingWarnings).toHaveLength(2);
expect(ctx.checkSummary?.strictAdvisoryExceeded).toBe(true);
});

test("omits check summary when runChecks: false", async () => {
writeAdr("ARCH-001", "architecture");
const ctx = await buildReviewContext(tempDir, { runChecks: false });
Expand Down
12 changes: 12 additions & 0 deletions tests/formats/project-config-fuzz.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,18 @@ describe("ProjectConfigSchema fuzz", () => {
expect(ProjectConfigSchema.safeParse(c).success).toBe(true);
});

test.each([0, -1, 1.5, "8"])(
"preserves strict mode when the briefing cap is %j",
(briefingMaxSectionChars) => {
const config = ProjectConfigSchema.parse({
strict: true,
briefingMaxSectionChars,
});
expect(config.strict).toBe(true);
expect(config.briefingMaxSectionChars).toBeUndefined();
}
);

test.each([
{ domains: {}, strict: "yes" },
{ domains: {}, strict: 1 },
Expand Down
26 changes: 16 additions & 10 deletions tests/helpers/binary-upgrade-archive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ async function rejectionWithoutLeak(run: Promise<unknown>): Promise<string> {
interface SpawnReply {
exitCode: number;
stdout?: string;
stderr?: string;
}

/**
Expand All @@ -180,10 +181,10 @@ function stubSpawn(
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
spawnSpy.mockImplementation(((argv: string[]) => {
calls.push(argv);
const { exitCode, stdout }: SpawnReply = respond(argv);
const { exitCode, stdout, stderr }: SpawnReply = respond(argv);
return {
stdout: stdout ?? "",
stderr: "",
stderr: stderr ?? "",
exited: Promise.resolve(exitCode),
};
}) as unknown as typeof Bun.spawn);
Expand Down Expand Up @@ -299,17 +300,22 @@ describe("downloadReleaseBinary archive handling", () => {
expect(message).toContain("Failed to extract archive (");
});

test("reports the PowerShell exit code when zip extraction fails", async () => {
test("reports the PowerShell exit code and stderr when zip extraction fails", async () => {
mockArchiveDownload(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));
// Stubbing the spawn reaches the failure branch on every runner rather
// than only on Windows, the sole platform shipping `.zip` releases.
stubSpawn(3);
stubSpawn(() => ({
exitCode: 3,
stderr: "ExtractToDirectory: Invalid archive.\r\n",
}));

const message = await rejectionWithoutLeak(
downloadReleaseBinary("v1.0.0", ZIP_ARTIFACT)
);

expect(message).toBe("Failed to extract archive (PowerShell exit code 3)");
expect(message).toBe(
"Failed to extract archive (PowerShell exit code 3):\nExtractToDirectory: Invalid archive."
);
});

test("uses the resolved PATH executable before the standard installation", async () => {
Expand Down Expand Up @@ -357,7 +363,9 @@ describe("downloadReleaseBinary archive handling", () => {
);
const calls = stubSpawn((argv) => {
const script = argv.at(-1)!;
const destination = /-DestinationPath '([^']+)'/u.exec(script)![1];
const destination = /ExtractToDirectory\('.+', '(.+)'\)$/u
.exec(script)![1]
.replaceAll("''", "'");
writeFileSync(join(destination, "archgate.exe"), "binary payload");
return { exitCode: 0 };
});
Expand Down Expand Up @@ -400,16 +408,14 @@ describe("downloadReleaseBinary archive handling", () => {
expect(readdirSync(sandbox)).toEqual([]);
});

test("stops PowerShell on a non-terminating Expand-Archive error", async () => {
test("makes ZIP extraction errors terminate PowerShell", async () => {
mockArchiveDownload(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));
const calls = stubSpawn(0);

await rejectionWithoutLeak(downloadReleaseBinary("v1.0.0", ZIP_ARTIFACT));

// Without `-ErrorAction Stop`, Expand-Archive reports a corrupt archive as
// a non-terminating error and `powershell -Command` still exits 0.
expect(calls[0]).toContain("powershell");
expect(calls[0].at(-1)).toContain("-ErrorAction Stop");
expect(calls[0].at(-1)).toContain("$ErrorActionPreference = 'Stop'");
});

test("rejects when extraction reports success but produces no binary", async () => {
Expand Down
Loading