diff --git a/.github/projects/active/audit-governance-refactor-2026-09/README.md b/.github/projects/active/audit-governance-refactor-2026-09/README.md index e9a3cb9356..a41a86ed5c 100644 --- a/.github/projects/active/audit-governance-refactor-2026-09/README.md +++ b/.github/projects/active/audit-governance-refactor-2026-09/README.md @@ -10,6 +10,22 @@ **Tasks**: [specs/012-audit-governance-structure/tasks.md](../../../specs/012-audit-governance-structure/tasks.md) +## Related Issues + +**No tracking issue exists for Spec 012 yet.** A repository search across open +and closed issues (`012 audit governance structure`, `audit governance structure`, +`governance structure`, `spec 012`, `governance files audit`, `CLAUDE.md AGENTS.md +audit`) returned no issue scoped to this specification, and +`specs/012-audit-governance-structure/` names none in its own text. + +Do not link [Spec 006's #3366](https://github.com/lightspeedwp/.github/issues/3366) +here: that issue tracks the separate governance-audit implementation, not this +audit of `CLAUDE.md` and `AGENTS.md`. + +**Note:** Add a tracking issue link once one is raised; the specification is +tracked by `specs/012-audit-governance-structure/` and implemented on +`audit/governance-files-refactor`. + ## Kanban Board Status ### Backlog (0) diff --git a/.github/projects/active/changelog-audit-quality-audit-2026-09-12/README.md b/.github/projects/active/changelog-audit-quality-audit-2026-09-12/README.md index cbf8f6c869..bdb6b9f733 100644 --- a/.github/projects/active/changelog-audit-quality-audit-2026-09-12/README.md +++ b/.github/projects/active/changelog-audit-quality-audit-2026-09-12/README.md @@ -17,6 +17,14 @@ owner: "ashley@lightspeedwp.agency" --- +## Related Issues + +| Issue | Type | Purpose | Status | +|-------|------|---------|--------| +| [#1271](https://github.com/lightspeedwp/.github/issues/1271) | epic | Changelog Automation Hardening — master epic | 🟡 In Progress | + +--- + ## 📋 Quick Links ### Core Documents (START HERE) diff --git a/.github/projects/active/workflow-consolidation-master-plan-2026-09/README.md b/.github/projects/active/workflow-consolidation-master-plan-2026-09/README.md index c7dc8a0b65..ef3e6062a5 100644 --- a/.github/projects/active/workflow-consolidation-master-plan-2026-09/README.md +++ b/.github/projects/active/workflow-consolidation-master-plan-2026-09/README.md @@ -19,6 +19,16 @@ timeline_weeks: 4-5 --- +## Related Issues + +| Issue | Type | Purpose | Status | +|-------|------|---------|--------| +| [#2896](https://github.com/lightspeedwp/.github/issues/2896) | epic | Workflow consolidation master plan & execution | ⏰ Planned | + +**Note:** Additional phase tracking issues to be created as execution begins. + +--- + ## Quick Start 1. **Start Here** → [`EXECUTION_SUMMARY.md`](./EXECUTION_SUMMARY.md) (5-min overview) diff --git a/.github/scripts/__tests__/report-generator.test.js b/.github/scripts/__tests__/report-generator.test.js new file mode 100644 index 0000000000..ef4ebc8060 --- /dev/null +++ b/.github/scripts/__tests__/report-generator.test.js @@ -0,0 +1,1052 @@ +#!/usr/bin/env node + +/** + * Tests for the governance audit report generator. + * + * The JSON assertions validate against the real schema in + * .github/specs/006-governance-audit/contracts/audit-report.contract.md, + * which is what task T007 requires ("formats ComplianceReport JSON and + * Markdown per audit-report.contract.md"). Asserting key names alone would + * not catch a wrong type, an out-of-enum value or a pattern mismatch. + */ + +import assert from "assert"; +import fs from "fs"; +import module from "module"; +import os from "os"; +import path from "path"; +import { fileURLToPath } from "url"; + +// `require` and `__dirname` are declared by the CommonJS transform Babel +// applies to this file, so binding them here raises a TDZ error under Jest. +// Use distinct names and `import.meta.url` to locate the repo root. +// +// fileURLToPath decodes percent-encoding and strips the leading slash Windows +// paths carry; `new URL(import.meta.url).pathname` does neither, so a +// checkout whose path contains a space would resolve ROOT to a directory that +// does not exist and the suite would fail while loading. +const load = module.createRequire(import.meta.url); +const TEST_DIR = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.join(TEST_DIR, "../../../"); + +const { ComplianceReport, ReportWriter, SEVERITIES, normaliseSeverity } = + load("../report-generator.cjs"); +const { createViolation } = load("../audit-violation.cjs"); +const governanceRules = load("../governance-rules.json"); + +const Ajv = load("ajv"); +const addFormats = load("ajv-formats"); + +// Under Jest the suite is collected by the runner, so it must not exit the +// worker. Standalone (npm run test:report-generator) it owns the exit code. +const RUNNING_UNDER_JEST = typeof process.env.JEST_WORKER_ID === "string"; + +const GREEN = "\x1b[32m"; +const RED = "\x1b[31m"; +const NC = "\x1b[0m"; + +let testsTotal = 0; +let testsPassed = 0; +let testsFailed = 0; + +function runTest(name, fn) { + testsTotal++; + try { + fn(); + testsPassed++; + console.log(`${GREEN}✓${NC} ${name}`); + } catch (error) { + testsFailed++; + console.log(`${RED}✗ ${name}${NC}`); + console.log(` ${error.message}`); + } +} + +// --- Contract schema -------------------------------------------------------- + +const contractMarkdown = fs.readFileSync( + path.join( + ROOT, + ".github/specs/006-governance-audit/contracts/audit-report.contract.md", + ), + "utf8", +); +const contractSchema = JSON.parse( + contractMarkdown.match(/```json\s*\n([\s\S]*?)\n```/)[1], +); +const ajv = new Ajv({ allErrors: true, strict: false }); +addFormats(ajv); +const validateContract = ajv.compile(contractSchema); + +/** Assert a report's toJSON() satisfies the contract schema. */ +function assertContractConforms(report, label) { + const data = report.toJSON(); + const valid = validateContract(data); + if (!valid) { + const detail = validateContract.errors + .map((e) => `${e.instancePath || "/"} ${e.message}`) + .join("; "); + throw new Error(`${label} failed the contract schema: ${detail}`); + } + return data; +} + +const base = (overrides) => + Object.assign( + { + id: "violation-20260929-001", + ruleId: "label-prefix-validation", + severity: "HIGH", + file: ".github/labels.yml", + message: "test violation", + }, + overrides, + ); + +runTest("default report conforms to the contract schema", () => { + assertContractConforms(new ComplianceReport(), "default report"); +}); + +runTest("report with a real AuditViolation conforms", () => { + assertContractConforms( + new ComplianceReport({ violations: [createViolation("r1", "Rule", "HIGH")] }), + "AuditViolation report", + ); +}); + +runTest("report with null violation fields conforms", () => { + assertContractConforms( + new ComplianceReport({ + violations: [ + { id: null, ruleId: null, severity: null, message: null, file: null }, + ], + }), + "null-field report", + ); +}); + +runTest("report with unrecognised severity conforms", () => { + assertContractConforms( + new ComplianceReport({ violations: [base({ severity: "SEVERE" })] }), + "unrecognised severity report", + ); +}); + +runTest("report with trends, recommendations and file descriptors conforms", () => { + assertContractConforms( + new ComplianceReport({ + filesScanned: [ + { id: "labels-yml", path: ".github/labels.yml", type: "labels" }, + ], + rulesApplied: ["label-prefix-validation", "yaml-syntax-validation"], + trends: { + previousReportId: "audit-20260928-101010", + violationsTrend: "improving", + violationsFixed: 4, + newViolations: 1, + daysImproving: 2, + }, + recommendations: [ + { + priority: "high", + title: "Add a prefix", + description: "desc", + affectedViolations: ["violation-20260929-001"], + estimatedEffort: "simple", + }, + ], + }), + "full report", + ); +}); + +runTest("malformed caller input is rejected rather than serialised", () => { + const report = new ComplianceReport(); + assert.throws(() => report.setTrends("improving"), TypeError); + assert.throws(() => report.setTrends(7), TypeError); + assert.doesNotThrow(() => report.setTrends({ violationsTrend: "stable" })); + assert.doesNotThrow(() => report.setTrends(null)); +}); + +runTest("non-integer and negative counts are coerced to integers", () => { + const decimal = new ComplianceReport({ filesScanned: 3.7 }).toJSON(); + assert.strictEqual(decimal.summary.totalFiles, 3); + assertContractConforms( + new ComplianceReport({ filesScanned: 3.7 }), + "decimal file count", + ); + const negative = new ComplianceReport({ filesScanned: -5 }).toJSON(); + assert.strictEqual(negative.summary.totalFiles, 0); + assertContractConforms( + new ComplianceReport({ filesScanned: -5 }), + "negative file count", + ); +}); + +runTest("non-string rulesApplied and generatedBy are coerced", () => { + assertContractConforms( + new ComplianceReport({ rulesApplied: ["ok", 42], generatedBy: 7 }), + "coerced passthrough fields", + ); +}); + +runTest("a null entry in violations does not throw", () => { + const json = new ComplianceReport({ violations: [null] }).toJSON(); + assert.strictEqual(json.violations.length, 1); + assertContractConforms( + new ComplianceReport({ violations: [null] }), + "null violation", + ); +}); + +runTest("markdown timestamp is UTC and matches the report id", () => { + const report = new ComplianceReport(); + const md = report.toMarkdown(); + const stamp = report.timestamp.replace("Z", ""); + assert.ok( + md.includes(stamp), + `markdown should render the UTC timestamp ${stamp}`, + ); +}); + +// --- Violation id allocation ------------------------------------------------- + +const idPattern = new RegExp( + contractSchema.properties.violations.items.properties.id.pattern, +); + +/** Assert every serialised id is unique. */ +function assertIdsUnique(json, label) { + const ids = json.violations.map((v) => v.id); + const seen = new Set(); + for (const id of ids) { + assert.ok( + !seen.has(id), + `${label}: duplicate violation id ${id} among ${ids.length} violations`, + ); + seen.add(id); + } +} + +runTest("a passed-through id that collides with a generated one is reallocated", () => { + // The first violation arrives already carrying the id the second violation + // would be allocated positionally. Both were conformant, so the old code + // preserved the first and generated the same value for the second. + const date = new Date().toISOString().split("T")[0].replace(/-/g, ""); + const json = new ComplianceReport({ + violations: [ + base({ id: `violation-${date}-002` }), + base({ id: "not-conformant" }), + ], + }).toJSON(); + assertIdsUnique(json, "collision with a generated id"); +}); + +runTest("two violations carrying the same conformant id are both reallocated", () => { + const date = new Date().toISOString().split("T")[0].replace(/-/g, ""); + const json = new ComplianceReport({ + violations: [ + base({ id: `violation-${date}-001` }), + base({ id: `violation-${date}-001` }), + ], + }).toJSON(); + assertIdsUnique(json, "duplicate passed-through id"); +}); + +runTest("a preserved id is still preserved when it does not collide", () => { + const json = new ComplianceReport({ + violations: [base({ id: "violation-20260929-007" })], + }).toJSON(); + assert.strictEqual( + json.violations[0].id, + "violation-20260929-007", + "a unique conformant id should be kept as-is", + ); +}); + +runTest("every reallocated id still matches the contract pattern", () => { + const date = new Date().toISOString().split("T")[0].replace(/-/g, ""); + const json = new ComplianceReport({ + violations: [ + base({ id: `violation-${date}-002` }), + base({ id: `violation-${date}-002` }), + base({ id: `violation-${date}-002` }), + base({ id: "plain" }), + ], + }).toJSON(); + for (const violation of json.violations) { + assert.match(violation.id, idPattern); + } + assertIdsUnique(json, "reallocated ids"); +}); + +runTest("allocation is sequential and never reuses a claimed sequence", () => { + // The first violation is non-conformant and the second arrives carrying 001. + // Allocation runs in order, so the first claims 001 and the second finds it + // taken and steps to 002. The invariant under test is uniqueness, not which + // of the two ends up with which sequence. + const date = new Date().toISOString().split("T")[0].replace(/-/g, ""); + const json = new ComplianceReport({ + violations: [ + base({ id: "plain" }), + base({ id: `violation-${date}-001` }), + ], + }).toJSON(); + assertIdsUnique(json, "sequential allocation"); + for (const violation of json.violations) { + assert.match(violation.id, idPattern); + } + assert.strictEqual(json.violations[0].id, `violation-${date}-001`); + assert.strictEqual(json.violations[1].id, `violation-${date}-002`); +}); + +runTest("an exhausted sequence range fails loudly rather than duplicating", () => { + // All 999 sequences are claimed by passed-through ids, so the next + // violation has nowhere to go and must not silently reuse one. + const date = new Date().toISOString().split("T")[0].replace(/-/g, ""); + const all = Array.from({ length: 999 }, (_, i) => + base({ id: `violation-${date}-${String(i + 1).padStart(3, "0")}` }), + ); + assert.throws( + () => + new ComplianceReport({ + violations: [...all, base({ id: "overflow" })], + }).toJSON(), + RangeError, + "an exhausted sequence range must fail loudly", + ); +}); + +// --- Recommendation references ---------------------------------------------- + +runTest("recommendation references follow the id rewrite", () => { + // Build the violation first so the recommendation can reference its real + // source id, which is not the id the contract receives. + const violation = createViolation("r1", "Rule", "HIGH"); + const sourceId = violation.toJSON().id; + const json = new ComplianceReport({ + violations: [violation], + recommendations: [ + { + priority: "high", + title: "Fix it", + description: "desc", + affectedViolations: [sourceId], + }, + ], + }).toJSON(); + assert.notStrictEqual(json.violations[0].id, sourceId); + assert.strictEqual( + json.recommendations[0].affectedViolations[0], + json.violations[0].id, + `affectedViolations still points at the source id ${sourceId} rather than ` + + `${json.violations[0].id}`, + ); +}); + +runTest("recommendation references follow a reallocated id", () => { + const date = new Date().toISOString().split("T")[0].replace(/-/g, ""); + const json = new ComplianceReport({ + violations: [base({ id: `violation-${date}-002` }), base({ id: "plain" })], + recommendations: [ + { + priority: "high", + title: "t", + description: "d", + affectedViolations: [`violation-${date}-002`, "plain"], + }, + ], + }).toJSON(); + const known = new Set(json.violations.map((v) => v.id)); + for (const ref of json.recommendations[0].affectedViolations) { + assert.ok( + known.has(ref), + `affectedViolations entry ${ref} does not match any serialised violation id`, + ); + } +}); + +runTest("a duplicated source id resolves to the first violation's contract id", () => { + // Two violations share a source id. Last-wins would make a recommendation + // resolve to whichever happened to be serialised last; first-wins is stable + // and matches the allocator, which keeps the first id it is given. + const shared = "violation-20260929-042"; + const json = new ComplianceReport({ + violations: [base({ id: shared }), base({ id: shared })], + recommendations: [ + { + priority: "high", + title: "t", + description: "d", + affectedViolations: [shared], + }, + ], + }).toJSON(); + assert.strictEqual( + json.recommendations[0].affectedViolations[0], + json.violations[0].id, + `reference resolved to ${json.recommendations[0].affectedViolations[0]} rather than the first violation ${json.violations[0].id}`, + ); +}); + +runTest("a violation with no source id creates no mapping entry", () => { + // Several violations with a missing id would otherwise share one map entry + // keyed undefined, and any malformed reference could resolve through it. + const json = new ComplianceReport({ + violations: [ + { ruleId: "r", severity: "HIGH", message: "m", file: "f.yml" }, + { ruleId: "r", severity: "LOW", message: "m", file: "f.yml" }, + ], + recommendations: [ + { + priority: "low", + title: "t", + description: "d", + affectedViolations: [undefined], + }, + ], + }).toJSON(); + assert.strictEqual(json.violations.length, 2); + assert.strictEqual( + json.recommendations[0].affectedViolations[0], + undefined, + "an undefined reference must not resolve through the mapping", + ); +}); + +runTest("unmatched recommendation references are left intact", () => { + const json = new ComplianceReport({ + violations: [base()], + recommendations: [ + { + priority: "low", + title: "t", + description: "d", + affectedViolations: ["an-id-with-no-violation"], + }, + ], + }).toJSON(); + assert.deepStrictEqual(json.recommendations[0].affectedViolations, [ + "an-id-with-no-violation", + ]); +}); + +// --- Deterministic rendering (A1: grouped by severity, sorted by line) ------ + +/** A violation carrying the fields the Markdown renderer reads. */ +function located(overrides = {}) { + return Object.assign( + { + id: "violation-20260929-001", + ruleId: "label-prefix-validation", + severity: "MEDIUM", + file: ".github/labels.yml", + message: "m", + location: { path: ".github/labels.yml", line: 10 }, + }, + overrides, + ); +} + +runTest("Markdown output does not depend on input order", () => { + // Two report instances carry different report ids and timestamps, so compare + // the body with those two volatile header lines removed. The assertion is + // about violation ordering, not about the clock. + const stripVolatile = (markdown) => + markdown + .split("\n") + .filter((line) => !/^\*\*(Report ID|Generated)\*\*/.test(line)) + .join("\n"); + + const violations = [ + located({ id: "violation-20260929-001", file: "b.yml", location: { path: "b.yml", line: 5 }, severity: "LOW" }), + located({ id: "violation-20260929-002", file: "a.yml", location: { path: "a.yml", line: 9 }, severity: "HIGH" }), + located({ id: "violation-20260929-003", file: "a.yml", location: { path: "a.yml", line: 2 }, severity: "CRITICAL" }), + ]; + const forward = stripVolatile(new ComplianceReport({ violations }).toMarkdown()); + const reversed = stripVolatile( + new ComplianceReport({ violations: [...violations].reverse() }).toMarkdown(), + ); + assert.strictEqual( + forward, + reversed, + "reordering the same violations changed the rendered report", + ); +}); + +runTest("violations render grouped by severity, then by ascending line (A1)", () => { + // Real AuditViolation objects so each block renders a distinguishable + // "### " heading. Asserting on bare severity names would match the + // fixed-order summary table at the top of the report instead. + const md = new ComplianceReport({ + violations: [ + createViolation("r", "LowRule", "LOW", { file: "f.yml", line: 1 }), + createViolation("r", "CriticalRule", "CRITICAL", { file: "f.yml", line: 90 }), + createViolation("r", "HighRule", "HIGH", { file: "f.yml", line: 40 }), + createViolation("r", "MediumRule", "MEDIUM", { file: "f.yml", line: 4 }), + ], + }).toMarkdown(); + const order = ["CriticalRule", "HighRule", "MediumRule", "LowRule"].map( + (name) => md.indexOf(`### ${name}`), + ); + for (const [name, index] of [ + ["CriticalRule", order[0]], + ["HighRule", order[1]], + ["MediumRule", order[2]], + ["LowRule", order[3]], + ]) { + assert.ok(index >= 0, `${name} was not rendered`); + } + assert.deepStrictEqual( + [...order].sort((a, b) => a - b), + order, + `severity blocks out of order: ${order.join(", ")}`, + ); +}); + +runTest("within one severity, violations render in ascending line order", () => { + const md = new ComplianceReport({ + violations: [ + createViolation("r", "Late", "HIGH", { file: "f.yml", line: 70 }), + createViolation("r", "Early", "HIGH", { file: "f.yml", line: 12 }), + createViolation("r", "Middle", "HIGH", { file: "f.yml", line: 33 }), + ], + }).toMarkdown(); + const order = ["Early", "Middle", "Late"].map( + (name) => md.indexOf(`### ${name}`), + ); + for (const [name, index] of [ + ["Early", order[0]], + ["Middle", order[1]], + ["Late", order[2]], + ]) { + assert.ok(index >= 0, `${name} was not rendered`); + } + assert.deepStrictEqual( + [...order].sort((a, b) => a - b), + order, + `HIGH violations are not in ascending line order: ${order.join(", ")}`, + ); +}); + +runTest("file sections render in a stable order", () => { + const md = new ComplianceReport({ + violations: [ + located({ id: "violation-20260929-001", file: "z.yml", location: { path: "z.yml", line: 1 } }), + located({ id: "violation-20260929-002", file: "m.yml", location: { path: "m.yml", line: 1 } }), + located({ id: "violation-20260929-003", file: "a.yml", location: { path: "a.yml", line: 1 } }), + ], + }).toMarkdown(); + const at = ["a.yml", "m.yml", "z.yml"].map((f) => md.indexOf(`### ${f}`)); + assert.ok(at.every((i) => i >= 0), "a file section is missing"); + assert.deepStrictEqual( + [...at].sort((x, y) => x - y), + at, + `file sections are not in a stable order: ${at.join(", ")}`, + ); +}); + +runTest("violations with no line sort after those that have one", () => { + // Real violations, so each block renders a distinguishable "### ". + const md = new ComplianceReport({ + violations: [ + createViolation("r", "NoLine", "HIGH", { file: "f.yml" }), + createViolation("r", "HasLine", "HIGH", { file: "f.yml", line: 5 }), + ], + }).toMarkdown(); + const noLine = md.indexOf("### NoLine"); + const withLine = md.indexOf("### HasLine"); + assert.ok(noLine >= 0, "the violation without a line was not rendered"); + assert.ok(withLine >= 0, "the violation with a line was not rendered"); + assert.ok( + withLine < noLine, + "a violation without a line should sort after those that have one", + ); +}); + +runTest("written report file re-validates against the contract", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "report-contract-")); + try { + const written = new ReportWriter(dir).writeJson( + new ComplianceReport({ violations: [createViolation("r", "R", "HIGH")] }), + ); + const reread = JSON.parse(fs.readFileSync(written.filepath, "utf8")); + const valid = validateContract(reread); + assert.ok( + valid, + `written report failed the contract schema: ${JSON.stringify( + validateContract.errors, + )}`, + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +// --- Severity normalisation ------------------------------------------------- + +runTest("uppercase severity is bucketed", () => { + const bySeverity = new ComplianceReport({ + violations: [base()], + }).getViolationsBySeverity(); + assert.strictEqual(bySeverity.HIGH.length, 1); +}); + +runTest("lowercase severity is normalised and bucketed", () => { + const bySeverity = new ComplianceReport({ + violations: [base({ severity: "critical" })], + }).getViolationsBySeverity(); + assert.strictEqual(bySeverity.CRITICAL.length, 1); + assert.strictEqual(bySeverity.UNKNOWN.length, 0); +}); + +runTest("mixed-case severity is normalised and bucketed", () => { + const bySeverity = new ComplianceReport({ + violations: [base({ severity: "Medium" })], + }).getViolationsBySeverity(); + assert.strictEqual(bySeverity.MEDIUM.length, 1); + assert.strictEqual(bySeverity.UNKNOWN.length, 0); +}); + +runTest("unrecognised severity is bucketed as UNKNOWN, not dropped", () => { + const report = new ComplianceReport({ + violations: [ + base(), + base({ id: "violation-20260929-002", severity: "SEVERE" }), + base({ id: "violation-20260929-003", severity: "blocker" }), + ], + }); + const bySeverity = report.getViolationsBySeverity(); + assert.strictEqual(bySeverity.HIGH.length, 1); + assert.strictEqual(bySeverity.UNKNOWN.length, 2); + const stats = report.getViolationStats(); + assert.strictEqual(stats.total, 3, "stats.total must count every violation"); + assert.strictEqual(stats.unknown, 2, "stats must expose the unknown bucket"); +}); + +runTest("every violation lands in exactly one bucket", () => { + const severities = ["CRITICAL", "high", "Medium", "low", "SEVERE", "", null, 7]; + const report = new ComplianceReport({ + violations: severities.map((severity, i) => + base({ id: `violation-20260929-00${i + 1}`, severity }), + ), + }); + const bySeverity = report.getViolationsBySeverity(); + const bucketed = Object.values(bySeverity).reduce((n, list) => n + list.length, 0); + assert.strictEqual( + bucketed, + severities.length, + "buckets must account for every violation exactly once", + ); + for (const bucket of Object.values(bySeverity)) { + for (const violation of bucket) { + assert.ok( + SEVERITIES.includes(normaliseSeverity(violation.severity)), + "violation bucketed outside SEVERITIES", + ); + } + } +}); + +runTest("absent severity defaults, malformed severity is an anomaly", () => { + // Absent means "not supplied", which the contract treats as the default. + assert.strictEqual(normaliseSeverity(undefined), "MEDIUM"); + assert.strictEqual(normaliseSeverity(null), "MEDIUM"); + assert.strictEqual(normaliseSeverity(""), "MEDIUM"); + assert.strictEqual(normaliseSeverity(" "), "MEDIUM"); + // Present but not a recognised string is an anomaly, not a silent default. + assert.strictEqual(normaliseSeverity(7), "UNKNOWN"); + assert.strictEqual(normaliseSeverity({}), "UNKNOWN"); + assert.strictEqual(normaliseSeverity("SEVERE"), "UNKNOWN"); +}); + +runTest("every bucket is present even when empty", () => { + // Asserted against a literal list, not the exported constant, so this + // fails if SEVERITIES loses a bucket rather than tracking the change. + const expected = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "UNKNOWN"]; + const bySeverity = new ComplianceReport().getViolationsBySeverity(); + assert.deepStrictEqual(Object.keys(bySeverity).sort(), expected.slice().sort()); + for (const severity of expected) { + assert.deepStrictEqual(bySeverity[severity], []); + } +}); + +// --- Contract-shaped output ------------------------------------------------- + +runTest("toJSON emits every contract-required key", () => { + const json = new ComplianceReport().toJSON(); + for (const key of contractSchema.required) { + assert.ok( + Object.prototype.hasOwnProperty.call(json, key), + `missing required contract key: ${key}`, + ); + } +}); + +runTest("report id matches the contract pattern", () => { + const json = new ComplianceReport().toJSON(); + assert.match( + json.id, + new RegExp(contractSchema.properties.id.pattern), + ); +}); + +runTest("report id and timestamp come from the same instant", () => { + const json = new ComplianceReport().toJSON(); + const parts = json.id.match(/^audit-(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})$/); + assert.ok(parts, `id did not parse: ${json.id}`); + const fromId = `${parts[1]}-${parts[2]}-${parts[3]}T${parts[4]}:${parts[5]}:${parts[6]}`; + assert.strictEqual(json.timestamp.slice(0, 19), fromId); +}); + +runTest("violations serialise as an array", () => { + const json = new ComplianceReport({ violations: [base()] }).toJSON(); + assert.ok(Array.isArray(json.violations)); + assert.strictEqual(json.violations.length, 1); + assert.strictEqual(json.violations[0].ruleId, "label-prefix-validation"); +}); + +runTest("every serialised severity is in the contract enum", () => { + const severities = ["CRITICAL", "high", "Medium", "low", "SEVERE", "blocker"]; + const json = new ComplianceReport({ + violations: severities.map((severity, i) => + base({ id: `violation-20260929-0${i + 10}`, severity }), + ), + }).toJSON(); + const allowed = contractSchema.properties.violations.items.properties.severity.enum; + for (const violation of json.violations) { + assert.ok( + allowed.includes(violation.severity), + `${violation.severity} is not in the contract enum ${allowed.join(",")}`, + ); + } +}); + +runTest("serialised violation ids all match the contract pattern", () => { + const json = new ComplianceReport({ + violations: [ + { id: "legacy-uuid-style", ruleId: "r", severity: "HIGH", message: "m" }, + { id: "violation-20260929-007", ruleId: "r", severity: "HIGH", message: "m" }, + ], + }).toJSON(); + const pattern = new RegExp( + contractSchema.properties.violations.items.properties.id.pattern, + ); + for (const violation of json.violations) { + assert.match(violation.id, pattern); + } + assert.strictEqual( + json.violations[1].id, + "violation-20260929-007", + "an already-conformant id must be preserved", + ); +}); + +runTest("location carries line and column when supplied", () => { + const json = new ComplianceReport({ + violations: [ + base({ location: { path: "a/b.yml", line: 12, column: 3 } }), + ], + }).toJSON(); + assert.strictEqual(json.violations[0].location.path, "a/b.yml"); + assert.strictEqual(json.violations[0].location.line, 12); + assert.strictEqual(json.violations[0].location.column, 3); +}); + +runTest("location falls back to the legacy file property", () => { + const json = new ComplianceReport({ violations: [base()] }).toJSON(); + assert.strictEqual(json.violations[0].location.path, ".github/labels.yml"); +}); + +runTest("summary counts match the violations", () => { + const json = new ComplianceReport({ + filesScanned: [ + { id: "labels-yml", path: ".github/labels.yml", type: "labels" }, + { id: "issue-types", path: ".github/issue-types.yml", type: "labels" }, + ], + rulesChecked: 8, + rulesPassed: 6, + violations: [base({ severity: "CRITICAL" }), base({ id: "violation-20260929-002", severity: "low" })], + }).toJSON(); + assert.strictEqual(json.summary.totalFiles, 2); + assert.strictEqual(json.summary.totalRules, 8); + assert.strictEqual(json.summary.totalViolations, 2); + assert.strictEqual(json.summary.criticalViolations, 1); + assert.strictEqual(json.summary.compliancePercentage, 75); + assert.strictEqual(json.summary.violationsBySeverity.critical, 1); + assert.strictEqual(json.summary.violationsBySeverity.low, 1); +}); + +runTest("violationsBySeverity partitions violations[] exactly", () => { + const json = new ComplianceReport({ + violations: [ + base({ severity: "CRITICAL" }), + base({ id: "violation-20260929-002", severity: "SEVERE" }), + base({ id: "violation-20260929-003", severity: "blocker" }), + ], + }).toJSON(); + const bySeverity = json.summary.violationsBySeverity; + assert.deepStrictEqual(Object.keys(bySeverity).sort(), [ + "critical", + "high", + "low", + "medium", + ]); + const sum = + bySeverity.critical + bySeverity.high + bySeverity.medium + bySeverity.low; + assert.strictEqual( + sum, + json.summary.totalViolations, + "the four contract buckets must sum to totalViolations", + ); + // The summary must agree with the serialised array, bucket for bucket. + const tally = {}; + for (const violation of json.violations) { + tally[violation.severity] = (tally[violation.severity] || 0) + 1; + } + for (const key of Object.keys(bySeverity)) { + assert.strictEqual( + bySeverity[key], + tally[key] || 0, + `summary.${key} disagrees with violations[]`, + ); + } + assert.strictEqual(json.summary.unknownSeverities, 2); +}); + +runTest("unrecognised severity serialises as low, not as a real bucket", () => { + const json = new ComplianceReport({ + violations: [ + base({ severity: "SEVERE" }), + base({ id: "violation-20260929-002", severity: 3 }), + ], + }).toJSON(); + for (const violation of json.violations) { + assert.strictEqual( + violation.severity, + "low", + "an unrecognised severity must not inflate a real bucket", + ); + } + assert.strictEqual(json.summary.violationsBySeverity.medium, 0); + assert.strictEqual(json.summary.violationsBySeverity.low, 2); + assert.strictEqual(json.summary.unknownSeverities, 2); +}); + +runTest("absent severity is not counted as an anomaly", () => { + const json = new ComplianceReport({ + violations: [base({ severity: undefined })], + }).toJSON(); + assert.strictEqual(json.violations[0].severity, "medium"); + assert.strictEqual(json.summary.unknownSeverities, 0); +}); + +runTest("the contract's 999-violation id limit is enforced", () => { + const build = (n) => + new ComplianceReport({ + violations: Array.from({ length: n }, (_, i) => base({ id: `x-${i}` })), + }); + + const atLimit = build(999).toJSON(); + const pattern = new RegExp( + contractSchema.properties.violations.items.properties.id.pattern, + ); + for (const violation of atLimit.violations) { + assert.match(violation.id, pattern); + } + const ids = new Set(atLimit.violations.map((v) => v.id)); + assert.strictEqual(ids.size, 999, "ids must be unique at the limit"); + + assert.throws( + () => build(1000).toJSON(), + RangeError, + "1000 violations cannot be given unique contract ids and must fail loudly", + ); +}); + +runTest("status maps violation severity onto the contract enum", () => { + const allowed = contractSchema.properties.summary.properties.status.enum; + const cases = [ + [new ComplianceReport(), "compliant"], + [new ComplianceReport({ violations: [base({ severity: "LOW" })] }), "warnings"], + [new ComplianceReport({ violations: [base({ severity: "HIGH" })] }), "violations"], + [new ComplianceReport({ violations: [base({ severity: "CRITICAL" })] }), "violations"], + ]; + for (const [report, expected] of cases) { + const status = report.toJSON().summary.status; + assert.strictEqual(status, expected, `expected ${expected}, got ${status}`); + assert.ok(allowed.includes(status), `${status} is not in the contract enum`); + } +}); + +runTest("filesScanned is an array and defaults to empty", () => { + assert.deepStrictEqual(new ComplianceReport().toJSON().filesScanned, []); + const json = new ComplianceReport({ + filesScanned: [{ id: "labels-yml", path: ".github/labels.yml", type: "labels" }], + }).toJSON(); + assert.ok(Array.isArray(json.filesScanned)); + assert.strictEqual(json.filesScanned[0].type, "labels"); + assert.strictEqual( + json.filesScanned[0].status, + "scanned", + "the contract defines a status enum; descriptors should default to scanned", + ); +}); + +runTest("a filesScanned count is honoured in the summary", () => { + const json = new ComplianceReport({ filesScanned: 7 }).toJSON(); + assert.strictEqual(json.summary.totalFiles, 7); + assert.deepStrictEqual(json.filesScanned, []); +}); + +runTest("omitting rulesPassed reports a clean audit, not zero", () => { + const json = new ComplianceReport({ rulesApplied: ["a", "b"] }).toJSON(); + assert.strictEqual(json.summary.totalRules, 2); + assert.strictEqual(json.summary.compliancePercentage, 100); +}); + +runTest("compliancePercentage is clamped to 0-100", () => { + assert.strictEqual( + new ComplianceReport({ rulesChecked: 2, rulesPassed: 9 }).toJSON().summary + .compliancePercentage, + 100, + ); + assert.strictEqual( + new ComplianceReport({ rulesChecked: 4, rulesPassed: 0 }).toJSON().summary + .compliancePercentage, + 0, + ); +}); + +runTest("violations are not duplicated under a byFile key", () => { + const json = new ComplianceReport({ violations: [base()] }).toJSON(); + assert.strictEqual( + Object.prototype.hasOwnProperty.call(json, "byFile"), + false, + "byFile duplicated every violation and is not in the contract", + ); + assert.strictEqual( + Object.prototype.hasOwnProperty.call(json.violations, "byFile"), + false, + "byFile duplicated every violation and is not in the contract", + ); + const serialised = JSON.stringify(json); + assert.strictEqual( + serialised.split("test violation").length - 1, + 1, + "each violation message must appear exactly once", + ); +}); + +runTest("generatedBy is a non-empty string", () => { + const json = new ComplianceReport().toJSON(); + assert.strictEqual(typeof json.generatedBy, "string"); + assert.ok(json.generatedBy.length > 0); +}); + +// --- Markdown --------------------------------------------------------------- + +runTest("toMarkdown tolerates plain-object violations", () => { + const md = new ComplianceReport({ + violations: [base({ severity: "SEVERE" })], + }).toMarkdown(); + assert.ok(md.includes("SEVERE"), "plain violation was not rendered"); +}); + +runTest("toMarkdown renders the contract trend field names only", () => { + const report = new ComplianceReport(); + report.setTrends({ + previousReportId: "audit-20260928-101010", + violationsTrend: "improving", + violationsFixed: 4, + newViolations: 1, + daysImproving: 2, + }); + const md = report.toMarkdown(); + for (const label of [ + "Previous Report", + "Trend", + "Violations Fixed", + "New Violations", + "Days Improving", + ]) { + assert.ok(md.includes(label), `markdown is missing the ${label} row`); + } + assert.ok(md.includes("improving"), "violationsTrend value not rendered"); + assert.ok( + !md.includes("Compliance |"), + "markdown still renders the removed complianceTrend row", + ); +}); + +runTest("toMarkdown reports the unknown severity count", () => { + const md = new ComplianceReport({ + violations: [base({ severity: "SEVERE" })], + }).toMarkdown(); + assert.ok(md.includes("UNKNOWN")); +}); + +runTest("trends survive toJSON under the contract shape", () => { + const report = new ComplianceReport(); + report.setTrends({ violationsTrend: "declining", newViolations: 7 }); + const json = report.toJSON(); + assert.strictEqual(json.trends.violationsTrend, "declining"); + assert.strictEqual(json.trends.newViolations, 7); +}); + +runTest("absent trends are omitted rather than emitted as null", () => { + const json = new ComplianceReport().toJSON(); + assert.ok( + !Object.prototype.hasOwnProperty.call(json, "trends"), + "trends: null violates the contract's object type", + ); +}); + +// --- ReportWriter naming ---------------------------------------------------- + +runTest("writer filename matches the configured reportFilePattern", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "report-writer-")); + try { + const report = new ComplianceReport(); + const written = new ReportWriter(dir).writeJson(report); + + // Expand the configured pattern from the report's own timestamp, so the + // assertion cannot drift across a second boundary. + const now = new Date(report.timestamp); + const yyyymmdd = now.toISOString().split("T")[0].replace(/-/g, ""); + const hhmmss = now.toISOString().split("T")[1].split(".")[0].replace(/:/g, ""); + const expected = + governanceRules.reporting.reportFilePattern + .replace("{YYYYMMDD}", yyyymmdd) + .replace("{HHMMSS}", hhmmss) + ".json"; + + assert.strictEqual( + written.filename, + expected, + `writer produced ${written.filename}, configured pattern expands to ${expected}`, + ); + assert.ok(fs.existsSync(path.join(dir, expected))); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +console.log(""); +console.log("Test Summary"); +console.log(`Total Tests: ${testsTotal}`); +console.log(`${GREEN}Passed: ${testsPassed}${NC}`); +console.log(`${RED}Failed: ${testsFailed}${NC}`); + +if (RUNNING_UNDER_JEST) { + // This file uses a plain assertion harness so it can also run standalone via + // `npm run test:report-generator`. Under Jest the assertions have already run + // at module scope, so register one test that reports their result. + test("governance audit report generator conforms to the contract", () => { + expect({ + total: testsTotal, + failed: testsFailed, + }).toEqual({ total: testsTotal, failed: 0 }); + }); +} else if (testsFailed > 0) { + process.exit(1); +} diff --git a/.github/scripts/__tests__/run-all-tests.sh b/.github/scripts/__tests__/run-all-tests.sh index b857e68db4..2be08664e2 100755 --- a/.github/scripts/__tests__/run-all-tests.sh +++ b/.github/scripts/__tests__/run-all-tests.sh @@ -104,6 +104,10 @@ run_test_suite \ "Agent Spec Generator CLI Tests" \ "$SCRIPT_DIR/create-agent-spec.test.js" +run_test_suite \ + "Governance Audit Report Generator Tests" \ + "$SCRIPT_DIR/report-generator.test.js" + run_test_suite \ "PRD Agent Test Suite (Mock Fixture Validation)" \ "$REPO_ROOT/agents/prd-agent/tests/test-runner.js" diff --git a/.github/scripts/audit-rule-loader.cjs b/.github/scripts/audit-rule-loader.cjs new file mode 100644 index 0000000000..a1532a149b --- /dev/null +++ b/.github/scripts/audit-rule-loader.cjs @@ -0,0 +1,224 @@ +/** + * AuditRule Loader (T005) + * Loads and manages audit rules from governance-rules.json + * Provides rule validation, filtering, and metadata retrieval + */ + +const fs = require('fs'); +const Ajv = require('ajv'); + +const ajv = new Ajv(); + +class AuditRuleLoader { + constructor(configPath) { + this.configPath = configPath; + this.config = null; + this.rules = []; + this.severity = { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1 }; + } + + /** + * Load configuration from JSON file + */ + loadConfig() { + try { + const content = fs.readFileSync(this.configPath, 'utf8'); + this.config = JSON.parse(content); + this._validateConfig(); + this.rules = this.config.auditRules || []; + return this.config; + } catch (error) { + throw new Error(`Failed to load audit rules config: ${error.message}`, { cause: error }); + } + } + + /** + * Validate configuration schema + */ + _validateConfig() { + const schema = { + type: 'object', + required: ['version', 'auditRules'], + properties: { + version: { type: 'string' }, + description: { type: 'string' }, + auditRules: { + type: 'array', + items: { + type: 'object', + required: ['id', 'name', 'enabled', 'severity'], + properties: { + id: { type: 'string' }, + name: { type: 'string' }, + description: { type: 'string' }, + enabled: { type: 'boolean' }, + severity: { enum: ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'] }, + file: { type: 'string' }, + validation: { type: 'object' }, + }, + }, + }, + compliance: { type: 'object' }, + reporting: { type: 'object' }, + performance: { type: 'object' }, + }, + }; + + const validate = ajv.compile(schema); + if (!validate(this.config)) { + const errors = validate.errors.map((e) => `${e.instancePath} ${e.message}`).join('; '); + throw new Error(`Config validation failed: ${errors}`); + } + } + + /** + * Get all rules + */ + getAllRules() { + return this.rules; + } + + /** + * Get enabled rules only + */ + getEnabledRules() { + return this.rules.filter((rule) => rule.enabled); + } + + /** + * Get rules by severity + */ + getRulesBySeverity(severity) { + return this.rules.filter((rule) => rule.severity === severity); + } + + /** + * Get rules for a specific file type + */ + getRulesByFileType(fileType) { + return this.rules.filter((rule) => { + if (!rule.file) return false; + if (rule.file.includes('/')) { + return rule.file.toLowerCase().includes(fileType.toLowerCase()); + } + return rule.file === fileType; + }); + } + + /** + * Get rule by ID + */ + getRuleById(id) { + return this.rules.find((rule) => rule.id === id); + } + + /** + * Get compliance configuration + */ + getComplianceConfig() { + return this.config.compliance || {}; + } + + /** + * Get reporting configuration + */ + getReportingConfig() { + return this.config.reporting || {}; + } + + /** + * Get performance targets + */ + getPerformanceConfig() { + return this.config.performance || {}; + } + + /** + * Get constitution configuration + */ + getConstitutionConfig() { + return this.config.constitution || {}; + } + + /** + * Calculate compliance percentage formula + */ + getComplianceFormula() { + const compliance = this.getComplianceConfig(); + return compliance.compliancePercentageFormula || '(rulesPassedCount / totalRulesCount) * 100'; + } + + /** + * Get compliance threshold + */ + getComplianceThreshold() { + const compliance = this.getComplianceConfig(); + return compliance.thresholdPercent || 95; + } + + /** + * Get severity weights for compliance calculation + */ + getSeverityWeights() { + const compliance = this.getComplianceConfig(); + return compliance.severityWeights || { CRITICAL: 10, HIGH: 5, MEDIUM: 2, LOW: 1 }; + } + + /** + * Get all principles from constitution + */ + getConstitutionPrinciples() { + const constitution = this.getConstitutionConfig(); + return constitution.principles || []; + } + + /** + * Calculate rule count statistics + */ + getStatistics() { + const allRules = this.getAllRules(); + const enabledRules = this.getEnabledRules(); + + return { + total: allRules.length, + enabled: enabledRules.length, + disabled: allRules.length - enabledRules.length, + bySeverity: { + CRITICAL: this.getRulesBySeverity('CRITICAL').length, + HIGH: this.getRulesBySeverity('HIGH').length, + MEDIUM: this.getRulesBySeverity('MEDIUM').length, + LOW: this.getRulesBySeverity('LOW').length, + }, + }; + } + + /** + * Validate rule configuration + */ + validateRule(rule) { + const errors = []; + + if (!rule.id) errors.push('Rule missing id'); + if (!rule.name) errors.push('Rule missing name'); + if (!rule.severity || !['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'].includes(rule.severity)) { + errors.push('Rule missing or invalid severity'); + } + if (typeof rule.enabled !== 'boolean') errors.push('Rule enabled must be boolean'); + + return { valid: errors.length === 0, errors }; + } +} + +/** + * Create loader and load config + */ +function createAuditRuleLoader(configPath) { + const loader = new AuditRuleLoader(configPath); + loader.loadConfig(); + return loader; +} + +module.exports = { + AuditRuleLoader, + createAuditRuleLoader, +}; diff --git a/.github/scripts/audit-violation.cjs b/.github/scripts/audit-violation.cjs new file mode 100644 index 0000000000..cd126927bc --- /dev/null +++ b/.github/scripts/audit-violation.cjs @@ -0,0 +1,303 @@ +/** + * AuditViolation Builder (T006) + * Creates and manages governance audit violations + * Provides violation metadata, remediation guidance, and affected system tracking + */ + +const { randomUUID } = require('crypto'); + +class AuditViolation { + constructor(options = {}) { + this.id = this._generateId(options); + this.ruleId = options.ruleId || null; + this.ruleName = options.ruleName || null; + this.severity = options.severity || 'MEDIUM'; + this.file = options.file || null; + this.line = options.line || null; + this.column = options.column || null; + this.message = options.message || null; + this.remediation = options.remediation || null; + this.affectedSystems = options.affectedSystems || []; + this.context = options.context || null; + this.timestamp = new Date().toISOString(); + this.metadata = options.metadata || {}; + } + + /** + * Generate unique violation ID + */ + _generateId(options) { + const ruleId = options.ruleId || 'unknown'; + return `${ruleId}-${randomUUID()}`; + } + + /** + * Set location information + */ + setLocation(file, line = null, column = null) { + this.file = file; + if (line !== null) this.line = line; + if (column !== null) this.column = column; + return this; + } + + /** + * Set violation message + */ + setMessage(message) { + this.message = message; + return this; + } + + /** + * Set remediation guidance + */ + setRemediation(remediation) { + this.remediation = remediation; + return this; + } + + /** + * Add affected system + */ + addAffectedSystem(system) { + if (!this.affectedSystems.includes(system)) { + this.affectedSystems.push(system); + } + return this; + } + + /** + * Add multiple affected systems + */ + addAffectedSystems(systems) { + for (const system of systems) { + this.addAffectedSystem(system); + } + return this; + } + + /** + * Set context (additional details) + */ + setContext(context) { + this.context = context; + return this; + } + + /** + * Add metadata + */ + addMetadata(key, value) { + this.metadata[key] = value; + return this; + } + + /** + * Get location string + */ + getLocationString() { + let location = this.file || 'unknown'; + if (this.line) { + location += `:${this.line}`; + if (this.column) { + location += `:${this.column}`; + } + } + return location; + } + + /** + * Check if violation is critical + */ + isCritical() { + return this.severity === 'CRITICAL'; + } + + /** + * Check if violation is high priority + */ + isHighPriority() { + return ['CRITICAL', 'HIGH'].includes(this.severity); + } + + /** + * Serialize to JSON + */ + toJSON() { + return { + id: this.id, + ruleId: this.ruleId, + ruleName: this.ruleName, + severity: this.severity, + location: this.getLocationString(), + file: this.file, + line: this.line, + column: this.column, + message: this.message, + remediation: this.remediation, + affectedSystems: this.affectedSystems, + context: this.context, + timestamp: this.timestamp, + metadata: this.metadata, + }; + } + + /** + * Serialize to Markdown + */ + toMarkdown() { + let md = `### ${this.ruleName || 'Unnamed Rule'}\n\n`; + md += `**Severity**: ${this.severity}\n\n`; + md += `**Location**: ${this.getLocationString()}\n\n`; + md += `**Message**: ${this.message || 'No message provided'}\n\n`; + + if (this.remediation) { + md += `**Remediation**: ${this.remediation}\n\n`; + } + + if (this.affectedSystems.length > 0) { + md += `**Affected Systems**: ${this.affectedSystems.join(', ')}\n\n`; + } + + if (this.context) { + md += `**Context**: ${this.context}\n\n`; + } + + return md; + } +} + +/** + * Create a violation builder + */ +function createViolation(ruleId, ruleName, severity, options = {}) { + return new AuditViolation({ + ruleId, + ruleName, + severity, + ...options, + }); +} + +/** + * Builder pattern for creating violations + */ +class ViolationBuilder { + constructor() { + this.violations = []; + } + + /** + * Start building a new violation + */ + add(ruleId, ruleName, severity) { + const violation = new AuditViolation({ + ruleId, + ruleName, + severity, + }); + return new ViolationBuilderStep(violation, this); + } + + /** + * Get all violations + */ + build() { + return this.violations; + } + + /** + * Clear all violations + */ + clear() { + this.violations = []; + return this; + } + + /** + * Get violations by severity + */ + getBySeverity(severity) { + return this.violations.filter((v) => v.severity === severity); + } + + /** + * Get violations by file + */ + getByFile(file) { + return this.violations.filter((v) => v.file === file); + } + + /** + * Get total violation count + */ + count() { + return this.violations.length; + } + + /** + * Get critical violation count + */ + criticalCount() { + return this.violations.filter((v) => v.isCritical()).length; + } + + /** + * Get high priority violation count + */ + highPriorityCount() { + return this.violations.filter((v) => v.isHighPriority()).length; + } +} + +/** + * Helper for fluent violation building + */ +class ViolationBuilderStep { + constructor(violation, parent) { + this.violation = violation; + this.parent = parent; + } + + location(file, line, column) { + this.violation.setLocation(file, line, column); + return this; + } + + message(message) { + this.violation.setMessage(message); + return this; + } + + remediation(remediation) { + this.violation.setRemediation(remediation); + return this; + } + + affectedSystems(systems) { + this.violation.addAffectedSystems(systems); + return this; + } + + context(context) { + this.violation.setContext(context); + return this; + } + + metadata(key, value) { + this.violation.addMetadata(key, value); + return this; + } + + end() { + this.parent.violations.push(this.violation); + return this.parent; + } +} + +module.exports = { + AuditViolation, + ViolationBuilder, + createViolation, +}; diff --git a/.github/scripts/governance-file.cjs b/.github/scripts/governance-file.cjs new file mode 100644 index 0000000000..f3bb1e0f58 --- /dev/null +++ b/.github/scripts/governance-file.cjs @@ -0,0 +1,190 @@ +/** + * GovernanceFile Parser (T004) + * Reads and parses governance files (YAML, Markdown, JSON) + * Returns structured representation with metadata and content + */ + +const fs = require('fs'); +const path = require('path'); +const yaml = require('js-yaml'); + +class GovernanceFile { + constructor(filePath, content, metadata = {}) { + this.id = this._generateId(filePath); + this.path = filePath; + this.type = this._detectType(filePath); + this.format = this._detectFormat(filePath); + this.content = content; + this.locked = metadata.locked !== false; // Default to locked + this.metadata = metadata; + } + + /** + * Generate unique identifier from file path + */ + _generateId(filePath) { + return path + .basename(filePath) + .replace(/\.[^/.]+$/, '') + .replace(/[^a-z0-9-]/gi, '-') + .toLowerCase(); + } + + /** + * Detect governance file type + */ + _detectType(filePath) { + const filename = path.basename(filePath); + + if (filename === 'labels.yml' || filename === 'labels.yaml') { + return 'labels'; + } + if (filename === 'issue-types.yml' || filename === 'issue-types.yaml') { + return 'issue-types'; + } + if (filename.endsWith('.md') && filePath.includes('TEMPLATE')) { + return 'template'; + } + const normalized = filePath.split(path.sep).join('/'); + if ( + /(^|\/)\.github\/workflows\//.test(normalized) && + (filename.endsWith('.yml') || filename.endsWith('.yaml')) + ) { + return 'workflow'; + } + if (filename.endsWith('.json')) { + return 'json-config'; + } + return 'unknown'; + } + + /** + * Detect file format + */ + _detectFormat(filePath) { + const ext = path.extname(filePath).toLowerCase(); + if (ext === '.yml' || ext === '.yaml') return 'yaml'; + if (ext === '.md' || ext === '.markdown') return 'markdown'; + if (ext === '.json') return 'json'; + return 'text'; + } + + /** + * Parse YAML content + */ + static parseYaml(content) { + try { + return yaml.load(content); + } catch (error) { + throw new Error(`YAML parse error: ${error.message}`, { cause: error }); + } + } + + /** + * Parse JSON content + */ + static parseJson(content) { + try { + return JSON.parse(content); + } catch (error) { + throw new Error(`JSON parse error: ${error.message}`, { cause: error }); + } + } + + /** + * Parse Markdown frontmatter + */ + static parseMarkdownFrontmatter(content) { + const frontmatterRegex = /^---\r?\n([\s\S]*?)(?:\r?\n)?---(?:\r?\n|$)([\s\S]*)$/; + const match = content.match(frontmatterRegex); + + if (!match) { + return { metadata: {}, body: content }; + } + + try { + const loaded = yaml.load(match[1]); + const metadata = loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {}; + return { metadata, body: match[2] }; + } catch (error) { + throw new Error(`Frontmatter parse error: ${error.message}`, { cause: error }); + } + } + + /** + * Get parsed content based on format + */ + getParsedContent() { + switch (this.format) { + case 'yaml': + return GovernanceFile.parseYaml(this.content); + case 'json': + return GovernanceFile.parseJson(this.content); + case 'markdown': { + const { metadata, body } = GovernanceFile.parseMarkdownFrontmatter(this.content); + return { metadata, body }; + } + default: + return { raw: this.content }; + } + } + + /** + * Serialize to JSON + */ + toJSON() { + return { + id: this.id, + path: this.path, + type: this.type, + format: this.format, + locked: this.locked, + metadata: this.metadata, + contentLength: this.content.length, + }; + } +} + +/** + * Load governance file from disk + */ +async function loadGovernanceFile(filePath, options = {}) { + try { + const resolvedPath = path.resolve(filePath); + const content = fs.readFileSync(resolvedPath, 'utf8'); + + return new GovernanceFile(filePath, content, { + locked: options.locked !== false, + ...options.metadata, + }); + } catch (error) { + throw new Error(`Failed to load governance file ${filePath}: ${error.message}`, { + cause: error, + }); + } +} + +/** + * Load multiple governance files + */ +async function loadGovernanceFiles(filePaths, options = {}) { + const files = []; + const errors = []; + + for (const filePath of filePaths) { + try { + const file = await loadGovernanceFile(filePath, options); + files.push(file); + } catch (error) { + errors.push({ filePath, error: error.message }); + } + } + + return { files, errors }; +} + +module.exports = { + GovernanceFile, + loadGovernanceFile, + loadGovernanceFiles, +}; diff --git a/.github/scripts/governance-rules.json b/.github/scripts/governance-rules.json new file mode 100644 index 0000000000..8f30ff10ad --- /dev/null +++ b/.github/scripts/governance-rules.json @@ -0,0 +1,194 @@ +{ + "version": "1.0.0", + "description": "Governance audit rules configuration for LightSpeed .github", + "auditRules": [ + { + "id": "label-prefix-validation", + "name": "Label Prefix Validation", + "description": "Ensures all labels in .github/labels.yml include required prefix (type:, status:, priority:, area:, meta:)", + "enabled": true, + "severity": "HIGH", + "file": ".github/labels.yml", + "validation": { + "type": "label-prefix", + "requiredPrefixes": ["ai-ops:", "area:", "comp:", "compat:", "contrib:", "cpt:", "discussion:", "env:", "lang:", "meta:", "openspec:", "priority:", "release:", "status:", "type:"], + "pattern": "^[a-z-]+:[a-z0-9-]+$" + } + }, + { + "id": "label-documented-purpose", + "name": "Label Documented Purpose", + "description": "Verifies each label has a documented purpose in YAML comment above definition", + "enabled": true, + "severity": "MEDIUM", + "file": ".github/labels.yml", + "validation": { + "type": "documented-purpose", + "requireComment": true, + "maxCommentLength": 100 + } + }, + { + "id": "label-active-usage", + "name": "Label Active Usage Detection", + "description": "Detects if label is used in templates, workflows, or specifications", + "enabled": true, + "severity": "MEDIUM", + "file": ".github/labels.yml", + "validation": { + "type": "active-usage", + "checkTemplates": true, + "checkWorkflows": true, + "checkSpecifications": true, + "templatePaths": [ + ".github/ISSUE_TEMPLATE/", + ".github/PULL_REQUEST_TEMPLATE/" + ], + "workflowPaths": [".github/workflows/"], + "specPaths": [".github/specs/"] + } + }, + { + "id": "label-duplicate-detection", + "name": "Duplicate Label Detection", + "description": "Identifies labels with similar meanings or near-duplicate names", + "enabled": true, + "severity": "HIGH", + "file": ".github/labels.yml", + "validation": { + "type": "duplicate-detection", + "algorithm": "semantic-similarity", + "thresholdPercent": 75 + } + }, + { + "id": "issue-type-usage", + "name": "Issue Type Usage Validation", + "description": "Verifies all issue types in .github/issue-types.yml are used in at least one template", + "enabled": true, + "severity": "MEDIUM", + "file": ".github/issue-types.yml", + "validation": { + "type": "usage-check", + "templatePaths": [".github/ISSUE_TEMPLATE/"] + } + }, + { + "id": "template-content-validation", + "name": "Template Content Validation", + "description": "Checks template content for UK English spelling, WCAG 2.2 AA guidance, and no implementation details", + "enabled": true, + "severity": "MEDIUM", + "file": ".github/ISSUE_TEMPLATE/", + "validation": { + "type": "template-content", + "checkSpelling": "uk-english", + "checkAccessibility": "wcag2.2-aa", + "forbiddenPatterns": ["TODO", "FIXME", "HACK", "XXX"] + } + }, + { + "id": "pr-template-routing", + "name": "PR Template Routing Validation", + "description": "Verifies each branch prefix maps to exactly one PR template and mapping is documented", + "enabled": true, + "severity": "HIGH", + "file": ".github/PULL_REQUEST_TEMPLATE/", + "validation": { + "type": "routing-validation", + "configPath": ".github/PULL_REQUEST_TEMPLATE/config.yml", + "branchTypes": [ + "feat", + "fix", + "hotfix", + "release", + "refactor", + "chore", + "task", + "doc", + "docs", + "test", + "perf", + "ci", + "build", + "deps", + "security", + "design", + "a11y", + "ux", + "i18n", + "ops", + "proto", + "ds", + "api", + "schema", + "telemetry", + "content", + "seo", + "config", + "migrate", + "qa", + "uat", + "audit", + "codex", + "revert", + "research", + "automation", + "epic", + "aiops" + ] + } + }, + { + "id": "yaml-syntax-validation", + "name": "YAML Syntax Validation", + "description": "Validates YAML syntax and required field presence in governance files", + "enabled": true, + "severity": "CRITICAL", + "file": ".github/labels.yml", + "validation": { + "type": "yaml-syntax", + "requiredFields": ["name", "color", "description"], + "reportLineNumbers": true + } + } + ], + "compliance": { + "compliancePercentageFormula": "(rulesPassedCount / totalRulesCount) * 100", + "thresholdPercent": 95, + "severityWeights": { + "CRITICAL": 10, + "HIGH": 5, + "MEDIUM": 2, + "LOW": 1 + } + }, + "reporting": { + "outputFormats": ["json", "markdown"], + "outputDirectory": ".github/reports", + "reportFilePattern": "audit-{YYYYMMDD}-{HHMMSS}", + "retentionDays": 90, + "summarizeAfterDays": 30 + }, + "performance": { + "targetAuditDurationSeconds": 30, + "targetValidationDurationSeconds": 2, + "targetReportGenerationSeconds": 5 + }, + "constitution": { + "source": ".specify/memory/constitution.md", + "alignmentCheckEnabled": true, + "principles": [ + "organisation-wide-governance-authority", + "curated-assets-locked-governance", + "clear-asset-boundaries", + "technology-agnostic-guidance", + "branch-naming-strategy", + "uk-english-accessibility-security", + "specification-quality-standards", + "branch-strategy-compliance", + "requirements-driven-quality", + "automated-validation-metrics" + ] + } +} diff --git a/.github/scripts/report-generator.cjs b/.github/scripts/report-generator.cjs new file mode 100644 index 0000000000..8873912cad --- /dev/null +++ b/.github/scripts/report-generator.cjs @@ -0,0 +1,740 @@ +/** + * Report Generator (T007) + * Generates compliance reports in JSON and Markdown formats + * Handles compliance metrics, violation summaries, and trend analysis + */ + +const fs = require('fs'); +const path = require('path'); + +/** + * Canonical severity buckets, in descending order of weight. + * + * The contract (audit-report.contract.md) defines severity values as + * lowercase, while AuditViolation and governance-rules.json use uppercase. + * Buckets are keyed uppercase here and lowercased on serialisation, so both + * spellings are accepted from callers without either source being rewritten. + */ +const SEVERITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'UNKNOWN']; + +const DEFAULT_SEVERITY = 'MEDIUM'; + +/** + * The contract's violation id pattern (^violation-\d{8}-\d{3}$) has a + * three-digit sequence, capping a single report at 999 violations. + */ +const MAX_CONTRACT_VIOLATIONS = 999; + +/** + * Format a date as the YYYYMMDD stamp the contract's id patterns use. + * + * @param {Date} date - Date to format. + * @returns {string} Eight-digit date stamp. + */ +function dateStamp(date) { + return date.toISOString().split('T')[0].replace(/-/g, ''); +} + +/** + * Format a date as the HHMMSS stamp the contract's id patterns use. + * + * @param {Date} date - Date to format. + * @returns {string} Six-digit time-of-day stamp. + */ +function timeStamp(date) { + return date.toISOString().split('T')[1].split('.')[0].replace(/:/g, ''); +} + +/** + * Build the report id required by the contract pattern ^audit-\d{8}-\d{6}$. + * + * @param {Date} date - Date the audit ran. + * @returns {string} Report identifier. + */ +function generateReportId(date) { + return `audit-${dateStamp(date)}-${timeStamp(date)}`; +} + +/** + * Coerce a value to a string, falling back when it is not a usable string. + * + * @param {*} value - Value to coerce. + * @param {string} fallback - Value used when the input is not a string. + * @returns {string} A non-empty string. + */ +function text(value, fallback) { + return typeof value === 'string' && value !== '' ? value : fallback; +} + +/** + * Return a violation id matching the contract pattern ^violation-\d{8}-\d{3}$. + * + * AuditViolation builds ids as `-`, which the contract does not + * accept, so a conformant id is derived from the report date and the + * violation's position instead. + * + * @param {*} id - Id supplied by the caller, used when already conformant. + * @param {number} index - Zero-based position within the report. + * @param {string} timestamp - Report timestamp, ISO 8601. + * @param {Set} used - Ids already allocated in this report. + * @returns {string} Contract-conformant violation identifier unique within the report. + */ +function contractViolationId(id, index, timestamp, used) { + const stamp = dateStamp(new Date(timestamp)); + const isTaken = (candidate) => + used instanceof Set && used.has(candidate); + + // Keep a conformant id only when nothing else in the report claims it. + // A passed-through id can otherwise collide with the positional id a later + // violation would be given, or with another passed-through id. + if ( + typeof id === 'string' && + /^violation-\d{8}-\d{3}$/.test(id) && + !isTaken(id) + ) { + return id; + } + + // The contract's id pattern has a three-digit sequence, so a single report + // can carry at most 999 violations. Search the whole range rather than + // deriving from the index, which can land on a taken sequence. + for (let sequence = 1; sequence <= MAX_CONTRACT_VIOLATIONS; sequence += 1) { + const candidate = `violation-${stamp}-${String(sequence).padStart(3, '0')}`; + if (!isTaken(candidate)) { + return candidate; + } + } + + throw new RangeError( + `Report carries more than ${MAX_CONTRACT_VIOLATIONS} violations; ` + + "the audit-report contract's violation id pattern " + + "(^violation-\\d{8}-\\d{3}$) cannot express a unique id beyond that.", + ); +} + +/** + * Map any casing of a known severity onto its canonical bucket. + * + * @param {string} severity - Severity as supplied by the caller. + * @returns {string} One of SEVERITIES; UNKNOWN when unrecognised. + */ +function normaliseSeverity(severity) { + if (severity === undefined || severity === null || severity === '') { + return DEFAULT_SEVERITY; + } + if (typeof severity !== 'string') { + return 'UNKNOWN'; + } + const upper = severity.trim().toUpperCase(); + if (upper === '') { + return DEFAULT_SEVERITY; + } + return SEVERITIES.includes(upper) ? upper : 'UNKNOWN'; +} + +/** + * Display order for the severity buckets, most severe first. + * + * UNKNOWN ranks last: an unrecognised severity is not treated as more urgent + * than a recognised one. + */ +const SEVERITY_RANK = { + CRITICAL: 0, + HIGH: 1, + MEDIUM: 2, + LOW: 3, + UNKNOWN: 4, +}; + +/** + * Read a violation's line number from either location shape. + * + * AuditViolation exposes `line`; a plain object may carry `location.line`. + * + * @param {Object} violation - Violation to inspect. + * @returns {number|null} The line, or null when absent or not a number. + */ +function violationLine(violation) { + const raw = + violation && violation.location && violation.location.line !== undefined + ? violation.location.line + : violation && violation.line; + // Number(null) is 0 and Number("") is 0, so an absent line has to be + // rejected before coercion or it would sort as line 0. + if (raw === undefined || raw === null || raw === '') { + return null; + } + const parsed = Number(raw); + return Number.isFinite(parsed) ? parsed : null; +} + +/** + * Order violations for rendering, per clarification A1: grouped by severity, + * then ascending by line number within each file. + * + * The id is a final tiebreak so the order is total: two violations with the + * same severity and line would otherwise be ordered by input, which would make + * the rendered report depend on the order the violations happened to arrive in. + * + * @param {Object} a - First violation. + * @param {Object} b - Second violation. + * @returns {number} Negative, zero or positive, for Array.sort. + */ +function compareViolations(a, b) { + const rank = + (SEVERITY_RANK[normaliseSeverity(a && a.severity)] ?? + SEVERITY_RANK.UNKNOWN) - + (SEVERITY_RANK[normaliseSeverity(b && b.severity)] ?? + SEVERITY_RANK.UNKNOWN); + if (rank !== 0) { + return rank; + } + + const lineA = violationLine(a); + const lineB = violationLine(b); + // A violation with no line sorts after those that have one. + const lineRank = (lineA === null ? Number.MAX_SAFE_INTEGER : lineA) - + (lineB === null ? Number.MAX_SAFE_INTEGER : lineB); + if (lineRank !== 0) { + return lineRank; + } + + return String(text(a && a.id, '')).localeCompare(String(text(b && b.id, ''))); +} + +class ComplianceReport { + constructor(options = {}) { + // Read the clock once so reportId and timestamp cannot disagree. + const now = new Date(); + this.reportId = generateReportId(now); + this.timestamp = now.toISOString(); + this.auditDuration = options.auditDuration || 0; + // The contract types filesScanned as an array of file descriptors. + // A caller may pass only a count, so keep the count for the summary + // and default the descriptor list to empty. + this.filesScanned = Array.isArray(options.filesScanned) + ? options.filesScanned + : []; + this.filesScannedCount = Array.isArray(options.filesScanned) + ? options.filesScanned.length + : Math.max(0, Math.trunc(Number(options.filesScanned)) || 0); + this.rulesApplied = Array.isArray(options.rulesApplied) + ? options.rulesApplied.map(String) + : []; + this.rulesChecked = + options.rulesChecked === undefined + ? this.rulesApplied.length + : options.rulesChecked; + // Default to a clean audit so a caller that omits rulesPassed is not + // reported as 0% compliant. + this.rulesPassed = + options.rulesPassed === undefined + ? this.rulesChecked + : options.rulesPassed; + this.violations = options.violations || []; + this.trends = options.trends || null; + this.recommendations = options.recommendations || []; + this.generatedBy = text(options.generatedBy, 'governance-audit-v1.0.0'); + this.metadata = options.metadata || {}; + } + + /** + * Calculate compliance percentage + */ + getCompliancePercentage() { + if (this.rulesChecked === 0) return 100; + const percentage = Math.round((this.rulesPassed / this.rulesChecked) * 100); + return Math.min(100, Math.max(0, percentage)); + } + + /** + * Check if audit passed (no violations found) + */ + hasPassed() { + return this.violations.length === 0; + } + + /** + * Check if compliance percentage meets threshold (progress target, not pass/fail) + */ + meetsComplianceTarget(threshold = 95) { + return this.getCompliancePercentage() >= threshold; + } + + /** + * Get violations by severity + * + * Every violation lands in exactly one bucket. Unrecognised severities + * are kept under UNKNOWN rather than dropped, so the buckets always sum + * to violations.length. + */ + getViolationsBySeverity() { + const bySeverity = {}; + for (const severity of SEVERITIES) { + bySeverity[severity] = []; + } + + for (const violation of this.violations) { + bySeverity[normaliseSeverity(violation && violation.severity)].push( + violation, + ); + } + + return bySeverity; + } + + /** + * Get violations by file + */ + getViolationsByFile() { + const grouped = new Map(); + + for (const violation of this.violations) { + const file = violation.file || 'unknown'; + if (!grouped.has(file)) { + grouped.set(file, []); + } + grouped.get(file).push(violation); + } + + // Both levels are sorted so the rendered report does not depend on the + // order the violations were supplied in: files by path, then violations + // within each file per compareViolations (A1). + const byFile = {}; + for (const file of [...grouped.keys()].sort((a, b) => a.localeCompare(b))) { + byFile[file] = grouped.get(file).sort(compareViolations); + } + + return byFile; + } + + /** + * Get violation count statistics + */ + getViolationStats() { + const bySeverity = this.getViolationsBySeverity(); + return { + total: this.violations.length, + critical: bySeverity.CRITICAL.length, + high: bySeverity.HIGH.length, + medium: bySeverity.MEDIUM.length, + low: bySeverity.LOW.length, + unknown: bySeverity.UNKNOWN.length, + }; + } + + /** + * Overall audit status per the contract summary.status enum + */ + getStatus() { + const stats = this.getViolationStats(); + if (stats.total === 0) { + return 'compliant'; + } + if (stats.critical > 0 || stats.high > 0) { + return 'violations'; + } + return 'warnings'; + } + + /** + * Describe a violation in the contract's violation shape. + * + * The contract requires id (^violation-\d{8}-\d{3}$), ruleId, severity + * (lowercase enum) and message as strings, so values that arrive null or + * out of range are coerced rather than passed through. + * + * @param {Object} violation - AuditViolation instance or plain object. + * @param {string} contractId - Contract-conformant id allocated by the + * caller, unique within the report. + * @returns {Object} Violation in the contract shape. + */ + _violationToContract(violation, contractId) { + const source = + violation && typeof violation.toJSON === 'function' + ? violation.toJSON() + : violation || {}; + const bucket = normaliseSeverity(source.severity); + const described = { + // Allocated by the caller, which holds the set of ids already claimed + // in this report. + id: contractId, + ruleId: text(source.ruleId, 'unknown-rule'), + // UNKNOWN is not in the contract enum, so an unrecognised severity + // serialises as the default and is counted in the summary instead. + // UNKNOWN is not a contract value, so an unrecognised severity + // serialises as the lowest contract severity rather than inflating + // a real bucket. The count is reported separately as + // summary.unknownSeverities. + severity: (bucket === 'UNKNOWN' ? 'LOW' : bucket).toLowerCase(), + message: text(source.message, 'No message provided'), + location: this._locationToContract(source), + }; + + for (const [key, fallback] of [ + ['fileId', 'unknown-file'], + ['currentValue', ''], + ['expectedValue', ''], + ['remediation', ''], + ]) { + if (source[key] !== undefined && source[key] !== null) { + described[key] = String(source[key]); + } else if (key === 'fileId') { + described.fileId = fallback; + } + } + + if (Array.isArray(source.affectedSystems)) { + described.affectedSystems = source.affectedSystems.map(String); + } + + return described; + } + + /** + * Rewrite recommendation references to the contract violation ids. + * + * Recommendations are supplied against the source violation ids, which are + * replaced during serialisation, so a reference left as-is would not + * resolve against the emitted violations. References that match no + * violation are left untouched. + * + * @param {Map} idMap - Source id to contract id. + * @returns {Array} Recommendations in the contract shape. + */ + _translateRecommendations(idMap) { + return this.recommendations.map((recommendation) => { + if ( + !recommendation || + !Array.isArray(recommendation.affectedViolations) + ) { + return recommendation; + } + return { + ...recommendation, + affectedViolations: recommendation.affectedViolations.map( + (reference) => idMap.get(reference) || reference, + ), + }; + }); + } + + /** + * Build the contract's location object, preferring an explicit location + * path over the legacy file property. + * + * @param {Object} source - Serialised violation. + * @returns {Object} Location with at least a path. + */ + _locationToContract(source) { + const location = { + path: text( + source.location && source.location.path + ? source.location.path + : source.file, + 'unknown', + ), + }; + + for (const axis of ['line', 'column']) { + const value = + source.location && source.location[axis] !== undefined + ? source.location[axis] + : source[axis]; + const parsed = Number(value); + if (Number.isInteger(parsed) && parsed > 0) { + location[axis] = parsed; + } + } + + return location; + } + + /** + * Add trend data + */ + /** + * Attach trend data. + * + * @param {Object} trends - Trend object per the contract's trends shape. + * @returns {ComplianceReport} This report, for chaining. + * @throws {TypeError} When trends is not a plain object. + */ + setTrends(trends) { + if (trends !== null && trends !== undefined && typeof trends !== 'object') { + throw new TypeError( + `trends must be an object per the contract, received ${typeof trends}`, + ); + } + this.trends = trends; + return this; + } + + /** + * Serialize to JSON + * + * The shape is defined by + * .github/specs/006-governance-audit/contracts/audit-report.contract.md + * (task T007). Required top-level keys are id, timestamp, filesScanned, + * rulesApplied, summary, violations and generatedBy. + */ + toJSON() { + const stats = this.getViolationStats(); + // Allocate ids in one pass so each can be checked against the ones + // already claimed, and record the source-to-contract mapping so + // recommendation references can be translated. + const usedIds = new Set(); + const idMap = new Map(); + const serialised = this.violations.map((violation, index) => { + const source = + violation && typeof violation.toJSON === 'function' + ? violation.toJSON() + : violation || {}; + const contractId = contractViolationId( + source.id, + index, + this.timestamp, + usedIds, + ); + usedIds.add(contractId); + // Only map ids that can actually be referenced. Several violations + // with no source id would otherwise share one entry keyed undefined, + // and when two share a source id the first wins, so a reference + // resolves the same way on every run. + if (source.id !== undefined && source.id !== null && !idMap.has(source.id)) { + idMap.set(source.id, contractId); + } + return this._violationToContract(violation, contractId); + }); + // Tallied from the serialised severities, so the four contract buckets + // always describe violations[] exactly. + const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 }; + let unknownSeverities = 0; + for (const violation of serialised) { + bySeverity[violation.severity] += 1; + } + for (const violation of this.violations) { + if (normaliseSeverity(violation && violation.severity) === 'UNKNOWN') { + unknownSeverities += 1; + } + } + + return { + id: this.reportId, + timestamp: this.timestamp, + filesScanned: this.filesScanned + .filter((file) => file && typeof file === 'object') + .map((file) => ({ status: 'scanned', ...file })), + rulesApplied: this.rulesApplied, + summary: { + totalFiles: this.filesScannedCount, + totalRules: this.rulesChecked, + totalViolations: stats.total, + criticalViolations: stats.critical, + // A true partition of violations[], so the four buckets always sum + // to totalViolations. Unrecognised severities are counted + // separately below. + violationsBySeverity: bySeverity, + // Violations whose severity was not recognised, so the anomaly is + // visible without distorting the severity partition. + unknownSeverities, + compliancePercentage: this.getCompliancePercentage(), + status: this.getStatus(), + }, + violations: serialised, + // The contract types trends as an object and does not require it, so + // an absent trend is omitted rather than emitted as null. + ...(this.trends ? { trends: this.trends } : {}), + recommendations: this._translateRecommendations(idMap), + generatedBy: this.generatedBy, + metadata: this.metadata, + }; + } + + /** + * Serialize to Markdown + */ + toMarkdown() { + const compliance = this.getCompliancePercentage(); + const stats = this.getViolationStats(); + const byFile = this.getViolationsByFile(); + const totalFiles = this.filesScannedCount; + const auditPassed = this.hasPassed() ? '✅' : '❌'; + const meetsTarget = this.meetsComplianceTarget() ? '✅' : '⚠️'; + + let md = `# Governance Audit Report\n\n`; + md += `**Report ID**: ${this.reportId}\n`; + md += `**Generated**: ${new Date(this.timestamp).toISOString()}\n\n`; + + md += `## Summary\n\n`; + md += `| Metric | Value |\n`; + md += `|--------|-------|\n`; + md += `| **Audit Status** | ${this.getStatus()} ${auditPassed} |\n`; + md += `| **Compliance Target** | ${compliance}% ${meetsTarget} |\n`; + md += `| **Files Scanned** | ${totalFiles} |\n`; + md += `| **Audit Duration** | ${this.auditDuration}ms |\n`; + md += `| **Rules Checked** | ${this.rulesChecked} |\n`; + md += `| **Rules Passed** | ${this.rulesPassed} |\n\n`; + + md += `## Violations\n\n`; + md += `**Total**: ${stats.total} violations\n\n`; + md += `| Severity | Count |\n`; + md += `|----------|-------|\n`; + md += `| 🔴 CRITICAL | ${stats.critical} |\n`; + md += `| 🟠 HIGH | ${stats.high} |\n`; + md += `| 🟡 MEDIUM | ${stats.medium} |\n`; + md += `| 🔵 LOW | ${stats.low} |\n`; + md += `| ⚪ UNKNOWN | ${stats.unknown} |\n\n`; + + // Violations by file. getViolationsByFile() has already ordered the + // files by path and the violations within each by severity then line, + // so this loop inherits a stable, input-order-independent rendering. + if (Object.keys(byFile).length > 0) { + md += `## Violations by File\n\n`; + for (const [file, violations] of Object.entries(byFile)) { + md += `### ${file}\n\n`; + md += `${violations.length} violations found\n\n`; + + for (const violation of violations) { + md += + typeof violation.toMarkdown === 'function' + ? violation.toMarkdown() + : `### ${text(violation.severity, DEFAULT_SEVERITY)} - ${text(violation.message, 'No message provided')}\n\n`; + } + } + } + + // Trends — field names follow the contract's trends object + if (this.trends) { + md += `## Trends\n\n`; + md += `| Metric | Change |\n`; + md += `|--------|--------|\n`; + + if (this.trends.previousReportId !== undefined) { + md += `| Previous Report | ${this.trends.previousReportId} |\n`; + } + + if (this.trends.violationsTrend !== undefined) { + const icon = + this.trends.violationsTrend === 'improving' + ? '📈' + : this.trends.violationsTrend === 'declining' + ? '📉' + : '➡️'; + md += `| Trend | ${icon} ${this.trends.violationsTrend} |\n`; + } + + if (this.trends.violationsFixed !== undefined) { + md += `| Violations Fixed | ${this.trends.violationsFixed} |\n`; + } + + if (this.trends.newViolations !== undefined) { + md += `| New Violations | ${this.trends.newViolations} |\n`; + } + + if (this.trends.daysImproving !== undefined) { + md += `| Days Improving | ${this.trends.daysImproving} |\n`; + } + + md += '\n'; + } + + return md; + } +} + +/** + * Report writer - saves reports to disk + */ +class ReportWriter { + constructor(outputDir) { + this.outputDir = outputDir; + this._ensureDirectory(); + } + + /** + * Ensure output directory exists + */ + _ensureDirectory() { + if (!fs.existsSync(this.outputDir)) { + fs.mkdirSync(this.outputDir, { recursive: true }); + } + } + + /** + * Write report to JSON file + */ + writeJson(report) { + const filename = `${report.reportId}.json`; + const filepath = path.join(this.outputDir, filename); + const content = JSON.stringify(report.toJSON(), null, 2); + fs.writeFileSync(filepath, content, 'utf8'); + return { format: 'json', filename, filepath }; + } + + /** + * Write report to Markdown file + */ + writeMarkdown(report) { + const filename = `${report.reportId}.md`; + const filepath = path.join(this.outputDir, filename); + const content = report.toMarkdown(); + fs.writeFileSync(filepath, content, 'utf8'); + return { format: 'markdown', filename, filepath }; + } + + /** + * Write both formats + */ + writeBoth(report) { + const json = this.writeJson(report); + const markdown = this.writeMarkdown(report); + return { json, markdown }; + } + + /** + * Get recent reports + */ + getRecentReports(limit = 10) { + if (!fs.existsSync(this.outputDir)) { + return []; + } + + try { + const files = fs.readdirSync(this.outputDir); + const jsonFiles = files + .filter((f) => f.endsWith('.json')) + .map((f) => ({ + filename: f, + filepath: path.join(this.outputDir, f), + mtime: fs.statSync(path.join(this.outputDir, f)).mtime, + })) + .sort((a, b) => b.mtime - a.mtime) + .slice(0, limit); + + return jsonFiles.map((f) => { + try { + const content = fs.readFileSync(f.filepath, 'utf8'); + return JSON.parse(content); + } catch (error) { + console.error(`Failed to read report ${f.filename}: ${error.message}`); + return null; + } + }).filter((r) => r !== null); + } catch (error) { + console.error(`Failed to read reports directory: ${error.message}`); + return []; + } + } +} + +module.exports = { + ComplianceReport, + ReportWriter, + SEVERITIES, + normaliseSeverity, + generateReportId, + contractViolationId, + compareViolations, + SEVERITY_RANK, +}; diff --git a/.github/specs/006-governance-audit/CLARIFICATIONS.md b/.github/specs/006-governance-audit/CLARIFICATIONS.md new file mode 100644 index 0000000000..c8d017b748 --- /dev/null +++ b/.github/specs/006-governance-audit/CLARIFICATIONS.md @@ -0,0 +1,305 @@ +# Phase 0 Clarifications: Governance Audit Implementation + +**Status**: Critical Ambiguities Resolved +**Date**: 2026-09-17 +**Branch**: `audit/governance-audit-implementation` + +--- + +## Overview + +Three critical ambiguities identified during specification analysis require resolution before Phase 1 implementation begins. This document captures decisions and rationale for each. + +--- + +## A1: FR-001 — "Completion Status" Definition (CRITICAL) + +### Original Ambiguity + +**FR-001**: "Audit system MUST scan all LOCKED governance files and report completion status" + +**Problem**: "completion status" undefined. Does it mean: + +- Binary pass/fail (audit finished or not)? +- Detailed metrics (files scanned, rules checked, violations found)? +- Compliance percentage (100/100 rules passed)? + +### Decision + +**Completion Status = Detailed Audit Report** + +The audit "completion status" is a comprehensive JSON and Markdown report containing: + +1. **Audit Metadata** + - Report ID: `audit-[YYYYMMDD]-[HHMMSS]` + - Timestamp: ISO 8601 + - Files scanned (count): `x of y LOCKED files` + - Scan duration: milliseconds + +2. **Validation Results** + - Total rules checked: `n` + - Rules passed: `m` + - Compliance percentage: `(m/n) * 100%` + - Violations found: `v` (grouped by severity) + +3. **Violation Details** + - Each violation: {file, line, rule, message, remediation} + - Grouped by: severity (CRITICAL, HIGH, MEDIUM, LOW) + - Sorted by: line number within each file + +4. **Trends** (if prior reports exist) + - Violations fixed (count): since last audit + - New violations (count): since last audit + - Trend direction: improving / stable / declining + - Compliance trend: % change since last audit + +5. **Accessibility** + - JSON format (machine-readable): `.github/reports/audit-[DATE].json` + - Markdown format (human-readable): `.github/reports/audit-[DATE].md` + +### Impact on Tasks + +- **T012** (Main audit entrypoint): Updated to output JSON + Markdown report per above schema +- **T014** (Report writer): Explicitly saves both formats +- **T013** (Compliance metrics): Computes percentage, summary stats, violations by severity +- **T015** (Trend analysis): Compares to prior report, calculates trend direction + +### Rationale + +Comprehensive reporting enables: + +- Automated monitoring (CI gates can check compliance %) +- Historical tracking (trends show improvement over time) +- Actionable remediation (each violation includes location + fix guidance) +- Governance audit trail (timestamped reports for compliance proof) + +--- + +## A2: FR-003 — "Documented Purpose" & "Usage Detection" (CRITICAL) + +### Original Ambiguity + +**FR-003**: "Audit MUST verify that each label in the canonical set has a documented purpose and is used at least once in active workflows or templates" + +**Problem**: Two undefined concepts: + +1. **Where documentation lives**: Labels.yml comment? Separate registry? Inline docs? +2. **How to detect "active usage"**: PR/issues applied? Workflow reference? Code mention? + +### Decision + +#### Part A: Documentation Location + +**Labels MUST have documented purpose in `.github/labels.yml`** + +Format: YAML comment immediately above each label definition + +**Example**: + +```yaml +# Primary issue classification: used when initial triage determines this is a defect vs. feature +- name: type:bug + color: FF0000 + description: Bug report or defect needing resolution +``` + +Comment format: + +- Single line preferred (max 100 chars) +- Lowercase first letter (UK English convention) +- Explains: what the label is, why it exists, primary use case +- Avoid: implementation details, just state the governance purpose + +#### Part B: Active Usage Detection + +**Label is "actively used" if ANY of the following are true:** + +1. **Used in active templates** (highest priority) + - Applied in `.github/ISSUE_TEMPLATE/*.md` frontmatter + - Applied in `.github/PULL_REQUEST_TEMPLATE/*.md` frontmatter + - Example: `labels: ["type:bug"]` in template frontmatter + +2. **Referenced in workflows** + - Used in `.github/workflows/*.yml` label filters + - Applied by labeler automation or CI gates + - Example: `github.event.label.name == 'type:bug'` + +3. **Documented in specification** + - Explicitly listed in `.github/specs/*/spec.md` requirements + - Example: "Audit validates `type:bug` labels per FR-002" + - Evidence: grep in spec files + +**Audit algorithm**: + +``` +for each label in canonical set { + if label in any active template → USED ✓ + else if label in any workflow → USED ✓ + else if label in any spec.md → USED ✓ + else → UNUSED ✗ (violation: label-not-actively-used) +} +``` + +### Impact on Tasks + +- **T004** (GovernanceFile parser): Extract YAML comments as documented purpose +- **T008** (Label validation): Check for documented purpose comment; report violations +- **T013** (Compliance metrics): Count active vs. unused labels +- **New acceptance criterion**: All labels in canonical set have documented purpose + active usage + +### Rationale + +Documented purposes: + +- Enable governance clarity (why does this label exist?) +- Support auditing (can verify label taxonomy aligns with constitution) +- Aid new team members (understand governance structure without code diving) + +Active usage detection: + +- Prevents orphaned labels (labels with no real purpose clogging the taxonomy) +- Keeps the audit tied to actual governance rather than intention +- Reveals drift (labels in taxonomy but not used = governance drift) + +--- + +## A6: FR-010 — "Prevent Commits" Enforcement Mechanism (CRITICAL) + +### Original Ambiguity + +**FR-010**: "Validation system MUST prevent commits that violate established governance rules" + +**Problem**: Enforcement layer undefined. Options: + +1. **Pre-commit hook only**: Developer-side, can bypass (`git commit --no-verify`) +2. **CI gate only**: Server-side, so a skipped local hook does not skip it; blocks a merge only where the target branch requires the check +3. **Both**: Defense-in-depth (catch early locally, enforce server-side) + +### Decision + +**BOTH: Pre-commit Hook + CI Gate (Defense-in-Depth)** + +#### Layer 1: Pre-commit Hook (Fast, Developer-Facing) + +**File**: `.husky/pre-commit` + +**Triggers**: On `git commit` (before commit is created) + +**Behavior**: + +- Runs validation on staged governance files only (fast feedback) +- If violations found: refuse commit, show remediation guidance +- If no violations: commit proceeds normally + +**User experience**: + +```bash +$ git commit -m "Update labels" +✓ Validating staged governance files... +✗ VIOLATION: label 'bug' missing 'type:' prefix at .github/labels.yml:42 + Remediation: Change 'bug:' to 'type:bug' and retry + +$ git commit # after fix +✓ Validation passed. Commit created. +``` + +**Can be bypassed**: `git commit --no-verify` (documented as "for emergencies only") + +#### Layer 2: CI Gate (Server-Side, Enforcement) + +**File**: `.github/workflows/validate-governance.yml` + +**Triggers**: On every push + PR + +**Behavior**: + +- Full validation of all governance files (not just staged) +- If violations found: check fails, comments on PR with violations +- Merge blocked until the check passes, but only once `validate-governance` + is a required status check on the target branch. A push-triggered check + cannot prevent the push itself, and without the branch-protection + requirement a failing check does not block a normal merge. + +This clarification describes the intended behaviour only. This PR adds no CI +workflow and no enforcement, so no such check exists yet. + +**User experience**: + +``` +❌ validate-governance + VIOLATION: label 'bug' missing 'type:' prefix at .github/labels.yml:42 + VIOLATION: duplicate labels: 'type:feature' and 'type:feature-request' (similar meaning) + + Fix violations and push again to re-run check. +``` + +**Merge blocking**: Applies only once the check is a required status check on the target branch. Before that a failing run does not stop a merge, and administrator overrides remain possible either way + +### Impact on Tasks + +- **T027** (Pre-commit hook integration): Create `.husky/pre-commit` that runs validation on staged files +- **T028** (GitHub Actions workflow): Create `.github/workflows/validate-governance.yml` that runs full validation +- **FR-010 updated**: Explicitly states "via pre-commit hook and CI gate" (not OR, AND) + +### Rationale + +**Why both?** + +Pre-commit hook alone: + +- ✗ Can be bypassed with `--no-verify` +- ✗ Slow feedback if developer commits bad changes and waits for CI to fail +- ✓ Fast (prevents bad commits from reaching CI at all) +- ✓ Good developer experience (immediate feedback) + +CI gate alone: + +- ✓ Runs where a skipped local hook cannot skip it +- ✓ Blocks a merge where the target branch requires the check (branch protection is a prerequisite, not a given) +- ✗ Slower feedback (developer commits, waits for CI) +- ✗ Wastes CI resources validating locally-fixable issues + +Both together: + +- ✓ Fast developer feedback (pre-commit catches issues immediately) +- ✓ Server-side enforcement (CI prevents bad pushes) +- ✓ Defense-in-depth (even if pre-commit is bypassed, CI catches it) +- ✓ Audit trail (CI logs show all validation runs) + +--- + +## Implementation Summary + +| Item | Before | After | Tasks | +|------|--------|-------|-------| +| **A1: Completion Status** | Undefined | Comprehensive JSON+Markdown report with trends | T012, T013, T014, T015 | +| **A2: Documentation** | Unclear | YAML comments + active usage detection | T004, T008, T013 | +| **A6: Enforcement** | Missing | Pre-commit hook + CI gate (both required) | T027, T028 | + +--- + +## Approval & Next Steps + +✅ **Phase 0 Clarifications Complete** + +Ready to proceed with: + +- ✅ Phase 1: Setup (T001-T003) +- ✅ Phase 2: Foundational (T004-T007) +- ✅ Phase 3: User Story 1 (T008-T020) + +**Blockers Resolved**: All 3 critical ambiguities clarified. No blockers remain for Phase 1 start. + +**Outstanding Items** (can resolve during implementation): + +- A3: Provide duplicate detection examples (test dataset for T025) +- A4: Define WCAG validation scope for Markdown (design task for T010) +- A5: Define "active" templates definition (implementation detail for T009) +- C2: Confirm UK English requirement (optional FR if in scope) +- D1: Secret scanning scope (Phase 2+ decision) + +--- + +**Document Version**: 1.0 +**Last Updated**: 2026-09-17 +**Status**: Ready for Implementation diff --git a/.github/specs/006-governance-audit/PHASE_0_DESIGN.md b/.github/specs/006-governance-audit/PHASE_0_DESIGN.md new file mode 100644 index 0000000000..c9009fd009 --- /dev/null +++ b/.github/specs/006-governance-audit/PHASE_0_DESIGN.md @@ -0,0 +1,322 @@ +# Phase 0: Design & Clarifications + +**Status**: Complete +**Date**: 2026-09-17 +**Branch**: `audit/governance-audit-implementation` +**Next Phase**: Phase 1 Setup (Ready to start) + +--- + +## Overview + +Phase 0 completed specification analysis and resolved all critical ambiguities. This document summarizes design decisions, constitution alignment verification, and approval gates. + +--- + +## Analysis Summary + +| Dimension | Result | Status | +|-----------|--------|--------| +| **Spec Coverage** | 11/11 FRs mapped to tasks; 8/8 SCs mapped | ✅ PASS | +| **Requirement Clarity** | 3 critical ambiguities resolved | ✅ PASS | +| **Constitution Alignment** | 8/10 ALIGNED, 1 PARTIAL (VI), 1 out of scope (IX) | ✅ PASS | +| **Task Organization** | 51 tasks with clear dependencies | ✅ PASS | +| **Implementation Feasibility** | All tasks scoped and achievable | ✅ PASS | + +**Overall Assessment**: Specification is **ready for implementation** after clarifications. + +--- + +## Critical Decisions Made + +### Decision 1: Completion Status = Detailed Report (A1) + +**What**: Audit produces JSON + Markdown reports with compliance %, violations grouped by severity, and trends. + +**Why**: Enables automated monitoring, historical tracking, and actionable remediation. + +**Impact**: + +- Compliance reports archive daily in `.github/reports/` +- CI can query compliance % to enforce gates +- Trends tracked over 30+ days (SC-008) + +**Tasks Updated**: T012, T013, T014, T015 + +--- + +### Decision 2: Documentation in YAML Comments + Active Usage Detection (A2) + +**What**: + +- Label documentation lives in `.github/labels.yml` as YAML comments above each label +- Active usage = found in templates, workflows, or specs (audit algorithm defined) + +**Why**: + +- Keeps documentation with the data (no separate registry) +- Auditable (YAML comments are part of the file) +- Active usage detection catches orphaned labels + +**Impact**: + +- Labeling team documents purpose when creating labels +- Audit flags unused labels (governance drift indicator) + +**Tasks Updated**: T004, T008, T013 + +--- + +### Decision 3: Defense-in-Depth Validation = Pre-commit Hook + CI Gate (A6) + +**What** (design intent; neither component is implemented in this phase): + +- Pre-commit hook (`.husky/pre-commit`): catches issues locally, fast feedback +- CI gate (`.github/workflows/validate-governance.yml`, to be added): server-side check. It blocks a merge only once it is a required status check on the target branch; a push-triggered run cannot prevent the push + +**Why**: + +- Pre-commit: catches issues before they reach CI (saves resources, fast feedback) +- CI gate: still runs when pre-commit is bypassed, which is the defense-in-depth case. Acting on that run depends on the branch-protection or ruleset configuration +- Together: both developer experience and governance enforcement + +**Impact**: + +- Bad governance files are caught on the pull request; blocking them from reaching the protected branch additionally depends on the gate being a required status check +- Audit trail of the validation runs CI produces, once the gate workflow exists +- Compliance tracking across PRs, once the gate workflow exists + +**Tasks Updated**: T027, T028 + +--- + +## Constitution Alignment Verification + +### Principles Verified + +| Principle | Validation | Result | +|-----------|-----------|--------| +| **I. Org-Wide Governance Authority** | Designed to treat `.github/` as the authoritative source | ✅ ALIGNED | +| **II. Curated Assets with Locked Governance** | Designed to validate the LOCKED files and detect drift | ✅ ALIGNED | +| **III. Clear Asset Boundaries** | Audit scripts in `.specify/scripts/bash/` (portable) + `.github/scripts/` (repo-local) | ✅ ALIGNED | +| **IV. Tech-Agnostic Guidance** | Governance principles apply across all tech stacks | ✅ ALIGNED | +| **V. Branch Naming Strategy** | FR-005 validates branch prefix → template routing | ✅ ALIGNED | +| **VI. UK English & A11y & Security** | A11y validation in FR-007; UK English can be explicit in Phase 1 if needed | ⚠️ PARTIAL | +| **VII. Specification Quality Standards** | Constitution check GATE in plan.md; quality dimensions validated | ✅ ALIGNED | +| **VIII. Branch Strategy Compliance** | PR template routing validation explicit in T011 | ✅ ALIGNED | +| **IX. Requirements-Driven Quality & Changelog** | Compliance metrics tracked daily (SC-008); changelog not in scope for Phase 1 | ⚠️ OUT OF SCOPE | +| **X. Automated Validation & Metrics** | SC-008 specifies daily dashboard; T047 generates compliance trends | ✅ ALIGNED | + +**Assessment**: 8 of 10 principles ALIGNED, 1 PARTIAL (VI, UK English & A11y & Security) and 1 correctly out of scope (IX, project changelog rather than governance files). + +**No constitution violations**. + +--- + +## Unresolved Items (Deferred to Implementation) + +These can be resolved during Phase 1 design or implementation without blocking start: + +### High Priority (Phase 1 Design) + +| Item | Issue | Resolution Path | Target Phase | +|------|-------|-----------------|---------------| +| **A3: Duplicate Detection** | How to measure "same meaning"? | Add test dataset of near-duplicate examples to quickstart.md | Phase 1 (T025 design) | +| **A4: WCAG Validation Scope** | How to validate Markdown for accessibility? | Define scope: semantic Markdown, prose clarity, or generated HTML? | Phase 1 (T010 design) | +| **A5: "Active" Templates** | What defines an "active" template? | Confirm: all templates in `.github/ISSUE_TEMPLATE/` or filtered? | Phase 1 (T009 implementation) | +| **C2: UK English Requirement** | Should FR-007 include UK English check? | Add FR-012 if yes; confirm it's covered by template review otherwise | Phase 1 (T010 scope) | + +### Medium Priority (Phase 0/1 Boundary) + +| Item | Issue | Resolution Path | Target Phase | +|------|-------|-----------------|---------------| +| **D1: Secret Scanning** | Edge case mentions secrets; no FR addresses it | Scope decision: Phase 1 or defer to Phase 2? | Phase 0/1 planning | +| **D2: 95%+ Duplicate Detection** | Why not 100%? | Document acceptable false negative rate during T025 implementation | Phase 1 (T025) | +| **G1: Test Scenarios Validation** | Verify quickstart.md scenarios 1-4 exist | Read quickstart.md before T020 implementation | Phase 1 (T020 checkpoint) | + +--- + +## Requirement-to-Task Mapping + +### All Functional Requirements Mapped + +``` +FR-001 (Scan files) → T012, T014, T018 ✅ +FR-002 (Label prefix validation) → T008 ✅ +FR-003 (Documented purpose) → T004, T008, T013 ✅ [CLARIFIED] +FR-004 (Duplicate detection) → T008, T025 ✅ +FR-005 (Template routing) → T011, T063 ✅ +FR-006 (Issue types usage) → T009 ✅ +FR-007 (Template content) → T010 ✅ +FR-008 (Compliance report) → T014, T015 ✅ +FR-009 (YAML syntax) → T022 ✅ +FR-010 (Prevent commits) → T027, T028 ✅ [CLARIFIED] +FR-011 (Remediation guidance) → T033-T044 ✅ +``` + +**Coverage**: 11/11 (100%) + +### All Success Criteria Mapped + +``` +SC-001 (<30s performance) → T018, T051 ✅ +SC-002 (100% label violations) → T008, T020 ✅ +SC-003 (95%+ duplicate detection)→ T025, T032 ✅ +SC-004 (100% routing accuracy) → T011, T020 ✅ +SC-005 (Actionable violations) → T006, T026 ✅ +SC-006 (80% time-to-fix) → T033-T044 ✅ +SC-007 (100% compliance) → T045 ✅ +SC-008 (Daily dashboard, 30+ days)→ T047 ✅ +``` + +**Coverage**: 8/8 (100%) + +--- + +## Phase 1 Readiness Checklist + +- [x] Specification analysis complete +- [x] All critical ambiguities resolved +- [x] Constitution alignment verified +- [x] Requirement-to-task mapping validated +- [x] Clarifications documented (CLARIFICATIONS.md) +- [x] Design decisions captured (this file) +- [x] Task organization reviewed +- [x] Blockers removed; ready to implement + +**Status**: ✅ READY FOR PHASE 1 START + +--- + +## Phase 1 Start Conditions + +**Go-Ahead**: All conditions met + +- ✅ Spec reviewed and approved +- ✅ Critical ambiguities resolved +- ✅ Constitution alignment verified +- ✅ Implementation tasks scoped (T001-T051) +- ✅ Team understanding confirmed — recorded as a reviewer sign-off step, not yet evidenced by a named reviewer in this document + +**Phase 1 Goals**: + +1. Setup directory structure and dependencies (T001-T003) +2. Implement foundational data structures (T004-T007) +3. Begin User Story 1: Governance Audit (T008-T020) + +**Phase 1 Success Criteria**: + +- Directory structure ready +- All foundational utilities implemented +- Audit MVP functional (can scan files and produce report) +- Validation scenarios 1-3 passing + +--- + +## Architecture Overview + +### Three-Layer Approach + +**Layer 1: Portable Audit Scripts** (`.specify/scripts/bash/`) + +- `audit-governance.sh` — Main entrypoint +- `generate-remediation.sh` — Remediation planning +- Discoverable and reusable across repositories + +**Layer 2: Repo-Local Validation** (`.github/scripts/`) + +- `.cjs` (CommonJS) modules for Node.js +- Utilities: parser, validators, reporters, mappers +- Pre-commit hook integration +- CI workflow integration + +**Layer 3: GitHub Actions Integration** (`.github/workflows/`, not yet present) + +- `validate-governance.yml` — to be added; will run on every PR/push +- Runs at the repository boundary rather than on the contributor's machine, so a skipped local hook does not skip it +- Blocks a merge only where the target branch lists it as a required status check; bypass actors and administrator overrides remain a branch-protection concern + +### Data Flow + +``` +governance files (.github/labels.yml, etc.) + ↓ +GovernanceFile parser (T004) + ↓ +AuditRule loader (T005) + Validators (T008-T011) + ↓ +AuditViolation builder (T006) + ↓ +Report generator (T007, T014) + ↓ +Compliance report (JSON + Markdown) + ↓ +[Output: .github/reports/governance-audit-[DATE].{json,md}] + ↓ +[Remediation mapper (T033-T041) — separate flow] +``` + +--- + +## Known Constraints & Trade-offs + +### Constraints (Non-Negotiable) + +- **Read-only audit**: Audit never modifies governance files (safety constraint) +- **LOCKED files focus**: Phase 1 audits LOCKED files only (templates, labels, issue-types) +- **No network calls**: Audit runs offline (no external API calls) +- **GitHub Actions compatible**: Must run in GitHub Actions environment + +### Trade-offs (Deliberate Choices) + +| Trade-off | Chosen | Alternative | Rationale | +|-----------|--------|-------------|-----------| +| **Duplicate detection** | 95%+ (not 100%) | 100% detection | Some ambiguous cases (synonyms) require human review; 95%+ automation + 5% manual is cost-effective | +| **Pre-commit + CI** | Both (defense-in-depth) | CI-only enforcement | Pre-commit saves developer time; CI ensures governance; both together maximize effect | +| **Active usage detection** | 3-point algorithm | Always require usage | Allows "strategic" labels documented but not yet used; audits flag them as drift (good visibility) | +| **Remediation guidance only** | Guidance-only in Phase 1 | Automated execution | Manual execution in Phase 1 reduces risk; Phase 2 can add automated remediation if approval gates proven safe | + +--- + +## Next Steps + +### Immediately (Before Phase 1 Start) + +1. ✅ Clarifications documented (CLARIFICATIONS.md created) +2. ✅ Design decisions captured (PHASE_0_DESIGN.md — this file) +3. ⏳ Share with team for final approval (optional review gate) + +### Phase 1 Kickoff + +1. Setup team environment (npm install, dependencies) +2. Start T001-T003 (directory structure, configuration) +3. Parallel: Start T004-T007 (foundational data structures) +4. Phase 1 checkpoint: All foundational utilities ready + +### Phase 1 Execution + +- Developer A: User Story 1 (T008-T020) — Audit capability +- Developer B: User Story 2 (T021-T032) — Validation automation +- Developer C: User Story 3 (T033-T044) — Remediation planning + +**Parallel work possible after T007 complete** (foundational infrastructure ready) + +--- + +## Success Metrics (Phase 0) + +- [x] Specification analysis complete (13 findings identified, categorized) +- [x] All critical ambiguities resolved (A1, A2, A6 with detailed rationale) +- [x] Constitution alignment verified (8/10 ALIGNED, 1 PARTIAL, 1 correctly deferred) +- [x] Requirement coverage 100% (11 FRs + 8 SCs mapped to tasks) +- [x] Blockers removed (no "go/no-go" items blocking Phase 1) +- [x] Documentation complete (CLARIFICATIONS.md + PHASE_0_DESIGN.md) + +**Phase 0 Status**: ✅ **COMPLETE** + +--- + +**Document Version**: 1.0 +**Generated**: 2026-09-17 +**Status**: Ready for Phase 1 Implementation +**Approval**: Design decisions finalized; implementation can proceed diff --git a/.specify/scripts/bash/.gitkeep b/.specify/scripts/bash/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 96fb6b7cdd..8c099c841b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Governance Audit Phase 0-2 Infrastructure** — Added audit rule loader, violation tracker and report generator scripts with governance rules, plus Spec 006 design docs. (#3367) +- **Governance audit report ids are unique and self-consistent** — Fixed duplicate violation ids and recommendation references that no longer resolved, plus Spec 006 count and enforcement wording. (#3367) +- **Governance audit reports now render in a stable order** — Fixed report output changing with the order findings arrived, so two runs of the same audit are comparable. (#3367) - **Footer Shape Signal** — `npm run validate:footers:shape` reports files holding two or more footer-shaped blocks the wording-based deduper cannot see. Advisory only: never edits a file, never fails a build. (#3682) - **CI and Changelog Agent Specs** — Added the CI failure remediation spec (017) and changelog agent quality spec (016), and updated the agent consolidation spec (014) tasks. (#3500) - **Code Graphs for OpenCode** — OpenCode can use locally built graft and graphify code graphs to locate code before searching files. The graphs are not committed. (#3569) diff --git a/package.json b/package.json index 3124df587f..7568ed1b37 100644 --- a/package.json +++ b/package.json @@ -139,6 +139,7 @@ "test:agent-spec-validation": "node .github/scripts/__tests__/validate-agent-specs.test.js", "test:index-generator": "node .github/scripts/__tests__/generate-agent-index.test.js", "test:create-agent-spec": "node .github/scripts/__tests__/create-agent-spec.test.js", + "test:report-generator": "node .github/scripts/__tests__/report-generator.test.js", "test:pre-commit": "bash hooks/__tests__/pre-commit-agent-spec-validation.test.sh", "test:prd-agent": "node agents/prd-agent/tests/test-runner.js --provider claude --suite all --json", "test:phase-5": "bash .github/scripts/__tests__/run-all-tests.sh",