diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 7696d62..aaf16a3 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.10.3", + "version": "0.11.0", "description": "Generische agentische Dev-Loop-Kette: /devloop:specify|spec-to-tests|implement|critic|loop + Bindungs-Anker (Wächter-Vorbedingung, content-gebundene Stopps, CI-Required-Check). Projektübergreifend.", "author": { "name": "Tobias Mogdans" } } diff --git a/.github/actions/precondition-check/action.yml b/.github/actions/precondition-check/action.yml index 688b1da..6419c2d 100644 --- a/.github/actions/precondition-check/action.yml +++ b/.github/actions/precondition-check/action.yml @@ -32,14 +32,16 @@ runs: run: | set -o pipefail DIFF=$(git diff --no-renames -z --name-only "origin/$BASE"...HEAD | jq -Rs 'split("\u0000") | map(select(length>0))') - jq -n --argjson touched "$DIFF" '{touched:$touched, repo:"."}' \ - | node "$GITHUB_ACTION_PATH/../../../dist/cli/derive-tier.js" > tier.json + jq -n --argjson touched "$DIFF" --arg baseRef "origin/$BASE" '{touched:$touched, repo:".", baseRef:$baseRef}' \ + | node "$GITHUB_ACTION_PATH/../../../dist/cli/derive-tier.js" > tier.json || exit 1 cat tier.json - name: Drift guard — tier-map T2/T3 paths covered by CODEOWNERS (§9) shell: bash run: node "$GITHUB_ACTION_PATH/../../../dist/cli/check-codeowners.js" . + # protected-globs.json und bot-logins.json liest verify-review selbst aus der Basis (baseRef); + # ein PR kann sich die Regeln, nach denen er geprueft wird, nicht selbst setzen (#13). - name: Verify HUMAN approval on HEAD + no gate-tamper (fail-closed) shell: bash env: @@ -62,10 +64,8 @@ runs: --arg headRef "$HEAD_REF" \ --arg baseRef "origin/$BASE" \ --arg tier "$(jq -r .tier tier.json)" \ - --argjson bots "$(cat .devloop/bot-logins.json)" \ --argjson diff "$DIFF" \ - --argjson protected "$(cat .devloop/protected-globs.json)" \ - '{reviews:$reviews, prAuthor:$prAuthor, headSha:$headSha, tier:$tier, botLogins:$bots, diffPaths:$diff, protectedGlobs:$protected, headRef:$headRef, baseRef:$baseRef, repo:"."}' \ + '{reviews:$reviews, prAuthor:$prAuthor, headSha:$headSha, tier:$tier, diffPaths:$diff, headRef:$headRef, baseRef:$baseRef, repo:"."}' \ | node "$GITHUB_ACTION_PATH/../../../dist/cli/verify-review.js" - name: Verify implement only un-skipped tests (test<->code seam, §11 #3) diff --git a/USAGE.md b/USAGE.md index 99e06cd..cccc929 100644 --- a/USAGE.md +++ b/USAGE.md @@ -63,6 +63,18 @@ Danach **von Hand** (das ist der Anker, der Selbst-Freigabe verhindert): ungültige (Bot, Autor, veraltet) → `ok:false`. Ein `devloop/spec/*`-PR ohne erkennbaren Spec-Pfad (z.B. nur Tests) schlägt ebenfalls mit `spec-unguarded` fehl. **Bestehende Ziel-Repos ohne Spec-Deckung werden bei Spec-PRs rot** — vor dem Upgrade CODEOWNERS ergänzen; + - **`/.devloop/`** (und eine tier-map außerhalb davon, z.B. `/tools/tier-map.json`) → Config-Änderungen + brauchen ein Review. **Pflicht seit v0.11.0 und wird erzwungen:** Die Precondition-Action liest + `tier-map.json`, `protected-globs.json` und `bot-logins.json` aus der **Basis** (`origin/`, per `git show`), + nie aus dem PR-HEAD; ein PR kann sich die Regeln, nach denen er geprüft wird, nicht selbst setzen. Fehlt eine + Datei in der Basis, gilt sie aus dem HEAD (Arbeitsbaum), dann stdin, sonst `config-missing`; ist die Basis-Datei + unlesbar (kein JSON, kein String-Array, kein reguläres Blob), schlägt der Check mit `config-invalid` fehl (kein + Rückfall). Config-Pfade sind `.devloop/**`, `tools/tier-map.json`, `tier-map.json`. Ein PR, der einen davon + ändert (hinzufügt, ändert, löscht), umgeht die T0/T1-Abkürzung nicht: Sind die Pfade nicht von der + **CODEOWNERS der Basis** gedeckt, `ok:false` mit `config-unguarded`; sonst gilt die Approval-Bewertung wie ab T2. + Ausgenommen ist die **Erstaufnahme** (die Basis enthält keinen Config-Pfad, der PR richtet devloop ein). + **Nach dem Update auf v0.11.0 ist die erste Config-Änderung rot**, bis `/.devloop/ @OWNER` in der CODEOWNERS + der Basis steht; `/devloop:init` legt die Zeile an bzw. meldet die Lücke in `notes`; - **alle T2/T3-Pfade aus deiner `tier-map`** (auth, migrations, contracts, `src/**`, …). So funktioniert §9 serverseitig: **T0/T1 berührt keine CODEOWNER-Pfade → kein Review nötig → Auto-Merge; T2/T3 berührt CODEOWNER-Pfade → required Review.** `verify-review` failt **nicht** auf „noch nicht diff --git a/dist/cli/derive-tier.js b/dist/cli/derive-tier.js index 80265be..6db1232 100644 --- a/dist/cli/derive-tier.js +++ b/dist/cli/derive-tier.js @@ -3,10 +3,14 @@ // - { touched, tierMap } — caller supplies the map content (no path resolution) // - { touched, repo } — devloop LOCATES the repo's tier-map robustly (absolute // path: .devloop/ -> tools/ -> root) and reads it itself. +// - { touched, repo, baseRef } — wie oben, aber die Suche laeuft in der BASIS (`git show`): +// ein PR waehlt seine tier-map nicht selbst (Issue #13). Hat die +// Basis keinen Kandidaten, gilt der erste Kandidat im Arbeitsbaum. // Always plain node (sandbox-clean) — never a repo's tsx-based `pnpm run tier`. import { readFileSync } from "node:fs"; import { deriveTier } from "../core/tier.js"; -import { resolveTierMapPath } from "../core/tier-map.js"; +import { resolveTierMapPath, TIER_MAP_CANDIDATES } from "../core/tier-map.js"; +import { readTreeEntry } from "../core/tree-entry.js"; import { readStdin } from "./_stdin.js"; const req = JSON.parse(await readStdin()); let tierMap = req.tierMap; @@ -16,12 +20,34 @@ if (!tierMap) { process.stderr.write("derive-tier: provide either `tierMap` or `repo` on stdin\n"); process.exit(2); } - const found = resolveTierMapPath(req.repo); - if (!found) { - process.stderr.write(`derive-tier: no tier-map found under ${req.repo} (.devloop/ , tools/ , or root)\n`); - process.exit(2); + let fromBase = false; + if (req.baseRef) { + try { + for (const cand of TIER_MAP_CANDIDATES) { + const entry = readTreeEntry(req.repo, req.baseRef, cand); + if (entry.kind === "missing") + continue; + if (entry.kind !== "file") + throw new Error(`${cand} ist in der Basis kein regulaeres Blob (${entry.kind})`); + tierMap = JSON.parse(entry.content); + tierMapPath = `${req.baseRef}:${cand}`; + fromBase = true; + break; + } + } + catch (e) { + process.stderr.write(`derive-tier: tier-map der Basis ${req.baseRef} unlesbar: ${e.message}\n`); + process.exit(1); + } + } + if (!fromBase) { + const found = resolveTierMapPath(req.repo); + if (!found) { + process.stderr.write(`derive-tier: no tier-map found under ${req.repo} (.devloop/ , tools/ , or root)\n`); + process.exit(2); + } + tierMapPath = found; + tierMap = JSON.parse(readFileSync(found, "utf8")); } - tierMapPath = found; - tierMap = JSON.parse(readFileSync(found, "utf8")); } process.stdout.write(JSON.stringify({ tier: deriveTier(req.touched, tierMap), tierMapPath }) + "\n"); diff --git a/dist/cli/verify-review.js b/dist/cli/verify-review.js index 00d6e23..c41d2fc 100644 --- a/dist/cli/verify-review.js +++ b/dist/cli/verify-review.js @@ -5,10 +5,14 @@ // stdin JSON: { reviews, prAuthor, headSha, botLogins?, humanReviewers?, diffPaths?, protectedGlobs?, // tier?, headRef?, baseRef?, repo? } // Spec-Aenderungen (REQ-SPECGATE-*) umgehen die T0/T1-Abkuerzung nicht und verlangen Basis-CODEOWNERS-Deckung. +// Mit baseRef kommen protectedGlobs und botLogins aus der Basis (Rueckfall: Arbeitsbaum, dann stdin; +// REQ-CFGBASE-2..4), und Config-Aenderungen (.devloop/**, tier-map) verhalten sich wie Spec-Aenderungen +// (REQ-CFGBASE-5/6), ausser bei Erstaufnahme. // reviews come from `gh api repos/{owner}/{repo}/pulls/{n}/reviews`. import { evaluateApproval } from "../core/review.js"; import { touchesProtectedSet } from "../core/protected-set.js"; import { isSpecChange, readBaseCodeowners, specGlobs, specPaths, uncoveredByCodeowners, SPEC_GLOBS_PATH, } from "../core/spec-change.js"; +import { BOT_LOGINS_PATH, PROTECTED_GLOBS_PATH, configPaths, isInitialAdoption, readConfigList, } from "../core/config-change.js"; import { readStdin } from "./_stdin.js"; function fail(reason) { process.stdout.write(JSON.stringify({ ok: false, reason }) + "\n"); @@ -16,14 +20,35 @@ function fail(reason) { } const req = JSON.parse(await readStdin()); const reviews = req.reviews ?? []; +const repo = req.repo ?? "."; +// 0. Config-Listen aus der Basis (REQ-CFGBASE-2/3/4). Unlesbar = config-invalid (kein Rueckfall), +// nirgends vorhanden = config-missing. Ohne baseRef gilt nur der stdin-Wert wie bisher. +let protectedGlobs = req.protectedGlobs; +let botLogins = req.botLogins; +if (req.baseRef) { + try { + const pg = readConfigList(repo, req.baseRef, PROTECTED_GLOBS_PATH); + const bl = readConfigList(repo, req.baseRef, BOT_LOGINS_PATH); + protectedGlobs = pg?.list ?? req.protectedGlobs; + botLogins = bl?.list ?? req.botLogins; + } + catch (e) { + fail(`config-invalid: ${e.message}`); + } + const missing = [ + ...(protectedGlobs === undefined ? [PROTECTED_GLOBS_PATH] : []), + ...(botLogins === undefined ? [BOT_LOGINS_PATH] : []), + ]; + if (missing.length > 0) { + fail(`config-missing: weder in der Basis ${req.baseRef}, im Arbeitsbaum noch auf stdin: ${missing.join(", ")}`); + } +} +const approvalCtx = { ...req, botLogins }; // 1. Gate-tamper fails ALWAYS, independent of approval state (reward-hacking alarm). -if (req.diffPaths && - req.protectedGlobs && - touchesProtectedSet(req.diffPaths, req.protectedGlobs)) { +if (req.diffPaths && protectedGlobs && touchesProtectedSet(req.diffPaths, protectedGlobs)) { fail("protected-set-touched: the diff edits a guardian/gate config (reward-hacking alarm)"); } // 1b. Spec-Aenderung (REQ-SPECGATE-1..7). Config gilt immer (REQ-5): ungueltig = fail-closed. -const repo = req.repo ?? "."; let globs; try { globs = specGlobs(repo, req.baseRef); @@ -56,16 +81,46 @@ if (specChange) { `${owners === null ? " (keine CODEOWNERS gefunden)" : ""}: ${uncovered.join(", ")}`); } } +// 1c. Config-Aenderung (REQ-CFGBASE-5/6): kein Abkuerzen, Basis-CODEOWNERS muessen die Pfade decken. +// Erstaufnahme (Basis ohne jeden Config-Pfad) ist ausgenommen: es gibt nichts zu schuetzen. +let configChange = false; +if (req.baseRef) { + const cfgPaths = configPaths(diffPaths); + if (cfgPaths.length > 0) { + let adoption; + try { + adoption = isInitialAdoption(repo, req.baseRef); + } + catch (e) { + fail(`config-invalid: ${e.message}`); + } + if (!adoption) { + configChange = true; + let owners; + try { + owners = readBaseCodeowners(repo, req.baseRef); + } + catch (e) { + fail(`config-unguarded: ${e.message} (Config-Pfade: ${cfgPaths.join(", ")})`); + } + const uncovered = uncoveredByCodeowners(cfgPaths, owners); + if (uncovered.length > 0) { + fail(`config-unguarded: Config-Pfade ohne CODEOWNERS-Deckung in der Basis ${req.baseRef}` + + `${owners === null ? " (keine CODEOWNERS gefunden)" : ""}: ${uncovered.join(", ")}`); + } + } + } +} // 2. Tier gate (§9): T0/T1 auto-merge — no approval required. (Gate-tamper above still applied.) // Unknown/absent tier defaults to conservative "T3" (approval required). The authoritative // T2/T3 merge block is branch protection's required CODEOWNER review on the high-tier paths; // this check additionally validates a present approval (human, on HEAD) and the protected set. const tier = req.tier ?? "T3"; -if (!specChange && (tier === "T0" || tier === "T1")) { +if (!specChange && !configChange && (tier === "T0" || tier === "T1")) { process.stdout.write(JSON.stringify({ ok: true, tier, note: "tier T0/T1: no approval required (§9)" }) + "\n"); process.exit(0); } -const status = evaluateApproval(reviews, req); +const status = evaluateApproval(reviews, approvalCtx); if (status === "ok") { process.stdout.write(JSON.stringify({ ok: true }) + "\n"); process.exit(0); diff --git a/dist/cli/verify-unskip.js b/dist/cli/verify-unskip.js index fbb2516..0266c87 100644 --- a/dist/cli/verify-unskip.js +++ b/dist/cli/verify-unskip.js @@ -5,8 +5,9 @@ // // SCOPE: the seam applies to the tests devloop MANAGES (those `spec-to-tests` derives from a // reviewed spec), not to every test file in the repo. The target repo declares them in -// `.devloop/managed-tests.json` (glob list) — a file inside the protected set, so an agent -// cannot widen it. No such file => every test file is managed (today's behaviour, fail-closed). +// `.devloop/managed-tests.json` (glob list) — read from the BASE; changing it is a config change +// that needs a CODEOWNERS review (verify-review, #13), so an agent cannot widen it on its own. +// No such file => every test file is managed (today's behaviour, fail-closed). // Deliberately NOT branch-name-driven: an agent chooses its own branch name. // // Usage: verify-unskip [headBranch] (baseRef e.g. origin/main) @@ -33,7 +34,7 @@ const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/; // The glob list is read from the BASE ref first: the scope that is already on the protected // branch decides, so a PR cannot loosen the seam for itself. Only if the file does not exist on // base do we fall back to the checkout (a repo adopting the file — that PR necessarily touches -// `.devloop/**` = the protected set and is already flagged by verify-review). +// `.devloop/**`, a config change that verify-review handles: review required unless initial adoption). const readWorktree = (rel) => { try { return readFileSync(join(repo, rel), "utf8"); diff --git a/dist/core/config-change.js b/dist/core/config-change.js new file mode 100644 index 0000000..07e8686 --- /dev/null +++ b/dist/core/config-change.js @@ -0,0 +1,88 @@ +// `.devloop/`-Config aus der Basis (Issue #13, docs/2026-11-27-devloop-config-aus-basis-design.md). +// Die Precondition-Action darf die Regeln, nach denen ein PR geprueft wird, nicht aus dem PR-HEAD +// lesen. Dieses Modul liest Config-Listen aus der Basis (`git show`) und erkennt Config-Aenderungen; +// die CODEOWNERS-Deckung der Basis (wie bei Spec-Pfaden, #4) erzwingt das Review. +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { matchesAnyGlob } from "./glob.js"; +import { readTreeEntry } from "./tree-entry.js"; +export const PROTECTED_GLOBS_PATH = ".devloop/protected-globs.json"; +export const BOT_LOGINS_PATH = ".devloop/bot-logins.json"; +/** Config-Pfade: alles unter `.devloop/` plus die tier-map-Kandidaten ausserhalb davon. */ +export const CONFIG_GLOBS = [".devloop/**", "tools/tier-map.json", "tier-map.json"]; +export class ConfigInvalidError extends Error { +} +export const configPaths = (diffPaths) => diffPaths.filter((p) => matchesAnyGlob(p, [...CONFIG_GLOBS])); +export const isConfigChange = (diffPaths) => configPaths(diffPaths).length > 0; +function assertRefResolvable(repo, baseRef) { + if (baseRef.startsWith("-")) + throw new ConfigInvalidError(`ungueltiger baseRef: ${baseRef}`); + try { + execFileSync("git", ["-C", repo, "rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`], { + stdio: ["ignore", "pipe", "ignore"], + }); + } + catch { + throw new ConfigInvalidError(`baseRef nicht aufloesbar: ${baseRef}`); + } +} +/** + * Erstaufnahme: die Basis enthaelt keinen einzigen Config-Pfad (der PR, der devloop einrichtet). + * Ein unaufloesbarer baseRef wirft (fail-closed), er gilt nie als "leere Basis". + */ +export function isInitialAdoption(repo, baseRef) { + assertRefResolvable(repo, baseRef); + let out; + try { + out = execFileSync("git", ["-C", repo, "--literal-pathspecs", "ls-tree", "-r", "-z", "--name-only", baseRef, "--", ".devloop", "tools/tier-map.json", "tier-map.json"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); + } + catch (e) { + throw new ConfigInvalidError(`Basis ${baseRef} nicht lesbar: ${e.message}`); + } + return !out.split("\0").some((p) => p !== "" && matchesAnyGlob(p, [...CONFIG_GLOBS])); +} +/** Parst ein JSON-Array von Strings (leeres Array ist gueltig). Sonst ConfigInvalidError. */ +export function parseStringArray(raw, label) { + let parsed; + try { + parsed = JSON.parse(raw); + } + catch { + throw new ConfigInvalidError(`${label} ist kein gueltiges JSON`); + } + if (!Array.isArray(parsed) || !parsed.every((x) => typeof x === "string")) { + throw new ConfigInvalidError(`${label} ist kein JSON-Array von Strings`); + } + return parsed; +} +/** + * Liest eine String-Listen-Config. Rangfolge: (1) Basis, (2) Arbeitsbaum, (3) null (Aufrufer + * entscheidet, z. B. stdin-Wert). Existiert die Basis-Datei, aber ist unlesbar (kein JSON, falsche + * Form, kein reguelaeres Blob), wirft sie ConfigInvalidError: kein Rueckfall auf HEAD. + */ +export function readConfigList(repo, baseRef, path) { + assertRefResolvable(repo, baseRef); + let entry; + try { + entry = readTreeEntry(repo, baseRef, path); + } + catch (e) { + throw new ConfigInvalidError(`${path} in der Basis ${baseRef} nicht lesbar: ${e.message}`); + } + if (entry.kind === "file") + return { list: parseStringArray(entry.content, `${path} (Basis)`), source: "base" }; + if (entry.kind !== "missing") { + throw new ConfigInvalidError(`${path} in der Basis ${baseRef} ist kein regulaeres Blob (${entry.kind})`); + } + let raw; + try { + raw = readFileSync(join(repo, path), "utf8"); + } + catch (e) { + if (e.code === "ENOENT") + return null; + throw new ConfigInvalidError(`${path} im Arbeitsbaum nicht lesbar: ${e.message}`); + } + return { list: parseStringArray(raw, `${path} (Arbeitsbaum)`), source: "worktree" }; +} diff --git a/dist/core/init.js b/dist/core/init.js index 23e7201..b7a159c 100644 --- a/dist/core/init.js +++ b/dist/core/init.js @@ -4,10 +4,11 @@ // Upgrade-aware: it will NOT shadow an existing tier-map, and it warns LOUDLY (notes) when an // existing workflow is left stale — `force` overwrites the workflow for a real migration. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { dirname, join, relative } from "node:path"; import { resolveTierMapPath } from "./tier-map.js"; import { tierGlobs } from "./tier.js"; -import { parseCodeowners, findUncoveredTierGlobs } from "./codeowners.js"; +import { parseCodeowners, findUncoveredTierGlobs, codeownersCovers } from "./codeowners.js"; +import { uncoveredSpecPaths } from "./spec-change.js"; // Convert a tier glob to a CODEOWNERS path: `services/**` -> `/services/` (anchored dir), // `**/auth/**` -> `auth/` (matches anywhere). A skeleton line for the human to assign owners. function tierGlobToCodeownersPath(glob) { @@ -16,13 +17,19 @@ function tierGlobToCodeownersPath(glob) { } return "/" + glob.replace(/\/\*\*$/, "/").replace(/\*\*$/, "").replace(/\*$/, ""); } +// tier-map outside `.devloop/` (tools/ or root) as CODEOWNERS paths, else null. +function tierMapOutsideDevloop(repo, tierMapPath) { + const rel = relative(repo, tierMapPath); + return rel.startsWith(".devloop/") ? null : ["/" + rel]; +} // Project-agnostic skeletons — the adopter tunes them in their constitution/CI. const PROTECTED_GLOBS_SKELETON = JSON.stringify(["**/stryker.conf.*", "**/.semgrep/**", "**/constitution.md", "**/CODEOWNERS", "**/*.eslintrc*"], null, 2); // Which test paths the unskip seam (§11) binds. The skeleton is the FAIL-CLOSED default — // `**` = every test file, i.e. exactly the pre-v0.8.1 behaviour. Narrow it to the paths // spec-to-tests actually authors (the caged services / twin areas), otherwise a plain PR that -// adds an ordinary active test file cannot pass the guard. Lives in `.devloop/` = the protected -// set, so an agent cannot widen it to smuggle its own tests past the seam. +// adds an ordinary active test file cannot pass the guard. verify-unskip reads it from the BASE; +// a PR that changes `.devloop/**` is a config change and needs a CODEOWNERS review (#13), so an +// agent cannot widen it to smuggle its own tests past the seam. const MANAGED_TESTS_SKELETON = JSON.stringify({ _comment: "Globs of the DEVLOOP-MANAGED test files (written by spec-to-tests, only un-skippable by implement). " + "Narrow these to your caged areas; ordinary tests outside them are not bound by the unskip seam. " + @@ -83,7 +90,7 @@ export function initRepo(targetRepo, ciTemplate, opts = {}) { const existingTierMap = resolveTierMapPath(targetRepo); if (existingTierMap) { result.skipped.push(".devloop/tier-map.json"); - result.notes.push(`tier-map already present (${existingTierMap.replace(targetRepo + "/", "")}) — not writing ` + + result.notes.push(`tier-map already present (${relative(targetRepo, existingTierMap)}) — not writing ` + `.devloop/tier-map.json (it would shadow yours). Reconcile your map with the devloop tier rules.`); } else { @@ -109,14 +116,28 @@ export function initRepo(targetRepo, ciTemplate, opts = {}) { const coRel = ["CODEOWNERS", ".github/CODEOWNERS", "docs/CODEOWNERS"].find((r) => existsSync(join(targetRepo, r))); if (!coRel) { const owners = [...new Set(t2t3.map(tierGlobToCodeownersPath))].map((p) => `${p} @OWNER`); + // Config-Pfade (#13): /.devloop/ plus a tier-map outside it, so a config change needs a review. + const cfg = ["/.devloop/", ...(tierMapOutsideDevloop(targetRepo, tierMapPath) ?? [])].map((p) => `${p} @OWNER`); write(".github/CODEOWNERS", "# devloop: T2/T3 tier paths require a human CODEOWNER review (the §9 merge gate).\n" + - "# Replace @OWNER with the real owner(s). Keep your protected set (gate configs) covered too.\n" + - owners.join("\n") + + "# Replace @OWNER with the real owner(s). /.devloop/ must stay covered: verify-review requires\n" + + "# a review for config changes, read against the BASE CODEOWNERS (else `config-unguarded`).\n" + + [...cfg, ...owners].join("\n") + "\n"); } else { result.skipped.push(coRel); - const uncovered = findUncoveredTierGlobs(t2t3, parseCodeowners(readFileSync(join(targetRepo, coRel), "utf8"))); + const patterns = parseCodeowners(readFileSync(join(targetRepo, coRel), "utf8")); + const outside = (tierMapOutsideDevloop(targetRepo, tierMapPath) ?? []).map((p) => p.slice(1)); + const uncoveredCfg = [ + ...(patterns.some((pat) => codeownersCovers(".devloop/config.json", pat)) ? [] : [".devloop/"]), + ...uncoveredSpecPaths(outside, patterns), + ]; + if (uncoveredCfg.length > 0) { + result.notes.push(`CODEOWNERS (${coRel}) does not cover these devloop config paths: ${uncoveredCfg.join(", ")} — add ` + + `owner lines (e.g. "/.devloop/ @OWNER"). Without them, every change to .devloop/** or the ` + + `tier-map fails verify-review with config-unguarded.`); + } + const uncovered = findUncoveredTierGlobs(t2t3, patterns); if (uncovered.length > 0) { result.notes.push(`CODEOWNERS (${coRel}) does not cover these T2/T3 tier paths — add owner lines, else such ` + `a PR could auto-merge unreviewed: ${uncovered.join(", ")}`); diff --git a/dist/core/managed-tests.js b/dist/core/managed-tests.js index 05a4c8e..953f66b 100644 --- a/dist/core/managed-tests.js +++ b/dist/core/managed-tests.js @@ -8,10 +8,11 @@ // // The distinction comes from a CONFIG FILE IN THE TARGET REPO — `.devloop/managed-tests.json`, // a glob list — deliberately NOT from the branch name: an agent picks its own branch name, so a -// branch-coupled exemption is self-serve. `.devloop/**` is part of the protected set -// (protected-globs.json), so an agent cannot widen the exemption list to smuggle its own tests -// past the seam — `verify-review` fails a diff that touches the protected set, unconditionally -// and independent of tier, BEFORE the unskip step ever runs. +// branch-coupled exemption is self-serve. verify-unskip reads the file from the BASE first, and a +// PR that changes `.devloop/**` is a config change: `verify-review` skips the T0/T1 shortcut and +// requires that the BASE CODEOWNERS cover `.devloop/` (else `config-unguarded`), so GitHub demands a +// human review (#13). An agent therefore cannot widen the exemption list on its own to smuggle +// its own tests past the seam. // // Fail-closed & backwards compatible: NO config file (or an unreadable/malformed one) means // EVERY test file is managed — exactly today's behaviour. No existing adopter gets looser by diff --git a/docs/2026-11-27-devloop-config-aus-basis-design.md b/docs/2026-11-27-devloop-config-aus-basis-design.md new file mode 100644 index 0000000..e04a992 --- /dev/null +++ b/docs/2026-11-27-devloop-config-aus-basis-design.md @@ -0,0 +1,148 @@ +# `.devloop/`-Config: Die Basis entscheidet, Änderungen brauchen ein Review — Design + +> devloop, Issue #13. Die Precondition-Action liest `tier-map.json`, `protected-globs.json` und +> `bot-logins.json` aus dem PR-HEAD. Ein Bot-PR kann sich damit die Regeln, nach denen er geprüft +> wird, selbst setzen. `init.ts` behauptet im Kommentar, `.devloop/` sei geschützt; das stimmt nicht. +> Status: **abgenommen** (2026-11-27), inklusive Review-Pflicht für Config-Änderungen über reines (b) hinaus. + +## Ist-Zustand (main, d251efb) + +Wer liest welche Config in der Precondition-Action (`.github/actions/precondition-check/action.yml`): + +| Datei | gelesen aus | Stelle | +|---|---|---| +| `tier-map.json` (`.devloop/` → `tools/` → Root) | PR-HEAD | `derive-tier` mit `repo:"."` (Schritt „Compute the AUTHORITATIVE tier“) | +| `.devloop/protected-globs.json` | PR-HEAD | `cat` im Schritt „Verify HUMAN approval“ | +| `.devloop/bot-logins.json` | PR-HEAD | `cat` im selben Schritt | +| `.devloop/spec-globs.json` | Basis | `specGlobs` (REQ-SPECGATE-8, #4) | +| `.devloop/managed-tests.json` | Basis, nur bei Fehlen in der Basis aus dem Arbeitsbaum | `verify-unskip` | +| `tier-map.json` + CODEOWNERS im Drift-Wächter | PR-HEAD | `check-codeowners` (#14, nicht hier) | + +Realer Pfad in jedem per `/devloop:init` eingerichteten Repo (Skeletons aus `src/core/init.ts`): + +1. Ein Bot-PR leert `.devloop/protected-globs.json` und ändert `stryker.conf.json`. +2. Der Gate-Tamper-Check sieht die leere HEAD-Liste und schlägt nicht an. +3. `stryker.conf.json` fällt in der Skeleton-tier-map nur unter `**` → T1. `verify-review` gibt T1 + ohne Approval frei. +4. Die von `init` angelegte CODEOWNERS deckt nur T2/T3-Pfade. GitHub verlangt kein Review. +5. Der PR mergt per Auto-Merge. Der Mutations-Gate ist ohne Mensch abgeschwächt. + +Gleiches Muster: tier-map im PR herabstufen (eigener PR wird T1); Bot-Login aus `bot-logins.json` +entfernen (Bot-Approval zählt als menschlich). + +## Entscheidung zu den Varianten aus dem Issue + +- **(a) `.devloop/**` ins Protected-Skeleton:** Jede Config-Änderung scheitert am Gate-Tamper-Check + und braucht einen Admin-Override. Nicht bedienbar. +- **(b) alles aus der Basis lesen:** schließt die Selbstanwendung im **eigenen** Lauf. Reicht allein + aber nicht: Ein T1-PR, der nur `.devloop/protected-globs.json` leert, mergt ohne Review, und **der + nächste** PR läuft schon mit der leeren Liste. + +**Vorschlag: (b) plus Review-Pflicht für Config-Änderungen**, nach dem Muster der Spec-Änderungen aus +#4. Eine Config-Änderung umgeht die T0/T1-Abkürzung, und die CODEOWNERS der Basis müssen jeden +geänderten Config-Pfad decken. Dann verlangt GitHub serverseitig das Review eines Menschen. Kein +Admin-Override, kein harter Fail ohne Approval (kein v0.2.4-Effekt, siehe #4). + +## Begriffe + +- **Config-Pfad:** ein Pfad unter `.devloop/` oder einer der tier-map-Kandidaten außerhalb davon + (`tools/tier-map.json`, `tier-map.json`). +- **Config-Änderung:** ein PR, dessen Diff mindestens einen Config-Pfad enthält (hinzugefügt, + geändert, gelöscht, Rename-Quelle oder -Ziel; Diff wie in REQ-SPECGATE-9). +- **Erstaufnahme:** Die Basis enthält keinen einzigen Config-Pfad. Das ist der PR, der devloop + einrichtet; in der Basis gibt es dann nichts, was geschützt werden könnte. +- **Basis-Config:** der Inhalt einer Config-Datei im Basis-Ref (`origin/`), gelesen per + `git show`, nie aus dem Arbeitsbaum. +- **Basis-CODEOWNERS:** wie in #4 (`.github/CODEOWNERS`, `CODEOWNERS`, `docs/CODEOWNERS` der Basis, + erste gefundene gilt). + +## Anforderungen (EARS) + +- **REQ-CFGBASE-1** *(ubiquitous)* — Die Precondition-Action soll das Tier mit der tier-map der + Basis berechnen (Suchreihenfolge `.devloop/` → `tools/` → Root, angewandt auf die Basis). Ein PR, + der die tier-map ändert, soll mit der tier-map der Basis eingestuft werden. +- **REQ-CFGBASE-2** *(ubiquitous)* — `verify-review` soll in der Action die Protected-Globs und die + Bot-Logins der Basis verwenden. Ein PR, der `protected-globs.json` leert oder `bot-logins.json` + ändert, soll in seinem eigenen Lauf nach den Basis-Listen geprüft werden. +- **REQ-CFGBASE-3** *(unwanted)* — Wenn eine Basis-Config-Datei existiert, aber unlesbar ist (kein + gültiges JSON, falsche Form, kein reguläres Blob), soll der Check fehlschlagen (fail-closed). Es + gibt keinen Rückfall auf den PR-HEAD. +- **REQ-CFGBASE-4** *(state-driven)* — Solange die Basis eine einzelne Config-Datei nicht enthält, + soll die Action sie aus dem PR-HEAD lesen (wie heute; bei der tier-map: Kandidat aus dem HEAD, + wenn die Basis keinen hat). Ein solcher PR fügt die Datei hinzu und ist damit eine + Config-Änderung (REQ-CFGBASE-5), außer bei Erstaufnahme. +- **REQ-CFGBASE-5** *(event-driven)* — Wenn ein PR eine Config-Änderung ist und keine Erstaufnahme, + soll `verify-review` die T0/T1-Abkürzung nicht anwenden und die Approval wie ab T2 bewerten + (gültige menschliche Approval auf HEAD → `ok:true`; keine → `ok:true, pending:true`; ungültige → + `ok:false`). +- **REQ-CFGBASE-6** *(unwanted)* — Wenn bei einer Config-Änderung (keine Erstaufnahme) ein + Config-Pfad von keinem Eintrag der Basis-CODEOWNERS gedeckt ist oder die Basis keine CODEOWNERS + hat, soll `verify-review` mit `ok:false` und `reason` beginnend mit `config-unguarded` + fehlschlagen und die ungedeckten Pfade nennen. +- **REQ-CFGBASE-7** *(ubiquitous)* — Ein PR ohne Config-Änderung soll sich bis auf REQ-CFGBASE-1/2 + (Quelle der Config) genau wie bisher verhalten. +- **REQ-CFGBASE-8** *(event-driven)* — Wenn `/devloop:init` eine CODEOWNERS anlegt, soll sie + `/.devloop/` (und einen tier-map-Pfad außerhalb von `.devloop/`, falls die tier-map dort liegt) + mit dem Platzhalter-Owner enthalten. Existiert eine CODEOWNERS, die diese Pfade nicht deckt, soll + `init` das in `notes` melden. +- **REQ-CFGBASE-9** *(ubiquitous)* — Kommentare, die `.devloop/` als geschützt bezeichnen + (`src/core/init.ts`, `src/core/managed-tests.ts`, `src/cli/verify-unskip.ts`), sollen den + tatsächlichen Mechanismus beschreiben (Basis liest, CODEOWNERS-Review). + +## Umsetzung (Skizze, nicht bindend) + +- Kern: `src/core/config-change.ts` mit `CONFIG_GLOBS`, `isConfigChange(diffPaths)`, + `isInitialAdoption(repo, baseRef)`; Basis-Lesen über `readBaseFile` aus `spec-change.ts`. +- `derive-tier` bekommt optional `baseRef` und sucht die tier-map in der Basis. +- `verify-review` liest `protectedGlobs`/`botLogins` selbst aus der Basis, wenn `baseRef` gesetzt + ist; die stdin-Werte bleiben für den lokalen Aufruf ohne `baseRef`. +- `action.yml`: die beiden `cat` entfallen; `derive-tier` bekommt `baseRef`. +- Versionssprung **v0.11.0** (verschärft: Config-Änderungen brauchen Basis-CODEOWNERS-Deckung). +- Doku: `USAGE.md` und `skills/init/SKILL.md` — `/.devloop/` in CODEOWNERS eintragen. + +## Detektoren (Wirkung) und Mutationsproben + +CLI-Tests gegen `dist/` in temporären Git-Repos mit echter Basis (`git show`, keine Attrappe). Die +Action-Tests bauen den Clone **wie `actions/checkout`**: detached auf HEAD, kein lokaler `main`, nur +`origin/` (vgl. #17), damit ein `baseRef` ohne `origin/` rot wird. + +| Fall | Erwartung | tötet Mutation | +|---|---|---| +| Action: Basis-tier-map `src/** → T3`, PR stuft in HEAD auf T1 und ändert `src/a.ts` | Tier T3 | tier-map aus HEAD | +| Action: Basis-tier-map nur unter `tools/`, HEAD legt `.devloop/tier-map.json` mit T1 an | Tier aus `tools/` der Basis | Suchreihenfolge im HEAD statt in der Basis | +| Action: Basis-protected-globs enthält `**/stryker.conf.*`, PR leert die Liste und ändert `stryker.conf.json` | rot, `protected-set-touched` | protected-globs aus HEAD | +| Action: Basis-bot-logins `["bot"]`, PR leert die Liste, Approval von `bot` auf HEAD, Tier T2 | rot | bot-logins aus HEAD | +| Basis-`protected-globs.json` = `{` | rot | Parse-Fehler still auf HEAD/leer | +| T1, PR ändert nur `.devloop/protected-globs.json`, Basis-CODEOWNERS ohne `/.devloop/` | `config-unguarded` | Config-Erkennung entfernt | +| dto. mit Deckung, keine Reviews | `ok:true, pending:true` | — (Gegenprobe gegen harten Fail) | +| dto. mit Deckung, Approval auf altem SHA | `ok:false` | T0/T1-Abkürzung vor der Approval-Bewertung belassen | +| T1, PR legt `tools/tier-map.json` an, Basis hat `.devloop/tier-map.json` | Config-Änderung | Config-Pfade nur unter `.devloop/` | +| T1, PR legt `.devloop/spec-globs.json` neu an, Basis hat andere `.devloop/`-Dateien | Config-Änderung (`config-unguarded` ohne Deckung) | nur geänderte, nicht hinzugefügte Dateien zählen | +| Erstaufnahme: Basis ohne jeden Config-Pfad, PR legt Skeletons an | kein `config-unguarded`, Tier aus HEAD-tier-map | Erstaufnahme nicht erkannt | +| Basis hat `.devloop/`, aber keine `bot-logins.json`; PR fügt sie hinzu | Liste aus HEAD, Config-Änderung | — | +| T1, `src/a.ts`, keine Config-Pfade | `ok:true` wie bisher | Config-Bedingung immer wahr | +| Basis-CODEOWNERS ohne `/.devloop/`, HEAD-CODEOWNERS mit | `config-unguarded` | CODEOWNERS aus HEAD | +| `init` ohne CODEOWNERS | angelegte Datei enthält `/.devloop/` | — | +| `init` mit CODEOWNERS ohne `/.devloop/` | Hinweis in `notes` | — | + +Mutationen werden im Implementierungs-PR gefahren und mit Ergebnis in der PR-Beschreibung dokumentiert. + +## Bekannte Grenzen (dokumentiert, keine eigene Runde) + +- **Lokale Leser bleiben beim Arbeitsbaum:** `smoke-tiers`, der PreToolUse-Hook und `/devloop:loop` + lesen `.devloop/config.json` lokal. Das ist der Orchestrator selbst, kein Prüfpunkt gegen ihn; + die CI-Kette entscheidet. +- **`check-codeowners`** liest tier-map und CODEOWNERS weiter aus dem HEAD (#14). +- **Nach dem Update auf v0.11.0 ist die erste Config-Änderung rot**, bis `/.devloop/` in der + CODEOWNERS der Basis steht. Fail-closed und dokumentiert, `init` meldet die Lücke. +- **`managed-tests.json` fehlt in der Basis:** Der Rückfall auf den Arbeitsbaum in `verify-unskip` + bleibt. Der PR, der sie hinzufügt, ist jetzt eine Config-Änderung und braucht ein Review. +- **Owner ohne Schreibrecht, `@OWNER`-Platzhalter, großzügiges CODEOWNERS-Matching und + Branch-Protection** gelten wie in #4 dokumentiert. +- **`.devloop` als Symlink in der Basis:** Ersetzt ein PR `.devloop/` durch einen Symlink, ist das + eine Config-Änderung und braucht ein CODEOWNER-Review. Ist er gemergt, gibt es in der Basis keinen + Config-Pfad mehr als Blob unter `.devloop/`. Jeder spätere PR gilt dann als Erstaufnahme + (REQ-CFGBASE-4), und der Config-Gate greift nicht mehr. Voraussetzung ist ein menschlich + approvter Merge. Es ist also kein Umgehungspfad ohne Review, sondern ein Rückbau, den der Owner + mitträgt. Ein eigenes REQ dafür (`.devloop` in der Basis kein Verzeichnis → `config-invalid`) + wäre möglich, ist aber bewusst zurückgestellt. diff --git a/package.json b/package.json index fa9fe94..ae404ab 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.10.3", + "version": "0.11.0", "private": true, "type": "module", "license": "MIT", diff --git a/skills/init/SKILL.md b/skills/init/SKILL.md index 2b9abad..3c9515a 100644 --- a/skills/init/SKILL.md +++ b/skills/init/SKILL.md @@ -37,6 +37,6 @@ Danach (Anker b — die Autorität sitzt serverseitig auf GitHub): 2. **Branch Protection** für die zwei harten Stopps: - **Require a review from CODEOWNERS** (das ist der Spec-Review/T3-Merge-Mensch) + **dismiss stale approvals on push** (Content-Bindung). - Die **Agent-Identität von Approve/Merge ausschließen** (sie darf nur vorschlagen) und in `.devloop/bot-logins.json` eintragen → `verify-review` zählt ihre Reviews nie als Mensch-Approval. -3. **CODEOWNERS** ist das §9-Merge-Tor: `init` **scaffoldet** eine `.github/CODEOWNERS` für die T2/T3-tier-map-Pfade (mit `@OWNER`-Platzhalter — **ersetzen!**), wenn keine existiert; existiert eine, lässt `init` sie unberührt und **meldet** ungedeckte T2/T3-Pfade (`notes`). **Spec-Pfade (`/.specify/specs/` o.ä.) eintragen ist Pflicht und wird erzwungen:** `verify-review` prüft bei jeder Spec-Änderung (Branch `devloop/spec/*` oder Spec-Pfad im Diff), dass die CODEOWNERS der **Basis** (nicht des PR-HEAD) jeden geänderten Spec-Pfad decken, sonst `spec-unguarded`. Was als Spec-Pfad gilt, steht in `.devloop/spec-globs.json` (JSON-Array nicht-leerer Globs, gelesen aus der Basis (Änderung wirkt erst nach dem Merge), Default `["**/spec.md"]`; ungültig oder leeres Array = fail-closed). Der Drift-Wächter `check-codeowners` erzwingt die Deckung nur für die T2/T3-tier-map-Pfade, **nicht** für Spec-Pfade; die Spec-Deckung erzwingt `verify-review` bei Spec-Änderungen. +3. **CODEOWNERS** ist das §9-Merge-Tor: `init` **scaffoldet** eine `.github/CODEOWNERS` für die T2/T3-tier-map-Pfade (mit `@OWNER`-Platzhalter — **ersetzen!**), wenn keine existiert; existiert eine, lässt `init` sie unberührt und **meldet** ungedeckte T2/T3-Pfade (`notes`). **`/.devloop/` muss von der CODEOWNERS gedeckt sein** (`init` scaffoldet `/.devloop/ @OWNER`, bei bestehender CODEOWNERS meldet es die Lücke in `notes`): Die Precondition-Action liest `tier-map`, `protected-globs` und `bot-logins` aus der **Basis**, und jede Config-Änderung (`.devloop/**`, tier-map) braucht ein Review, sonst `config-unguarded`. **Spec-Pfade (`/.specify/specs/` o.ä.) eintragen ist Pflicht und wird erzwungen:** `verify-review` prüft bei jeder Spec-Änderung (Branch `devloop/spec/*` oder Spec-Pfad im Diff), dass die CODEOWNERS der **Basis** (nicht des PR-HEAD) jeden geänderten Spec-Pfad decken, sonst `spec-unguarded`. Was als Spec-Pfad gilt, steht in `.devloop/spec-globs.json` (JSON-Array nicht-leerer Globs, gelesen aus der Basis (Änderung wirkt erst nach dem Merge), Default `["**/spec.md"]`; ungültig oder leeres Array = fail-closed). Der Drift-Wächter `check-codeowners` erzwingt die Deckung nur für die T2/T3-tier-map-Pfade, **nicht** für Spec-Pfade; die Spec-Deckung erzwingt `verify-review` bei Spec-Änderungen. 4. `tier-map.json` und `protected-globs.json` ans Repo anpassen (Wirkung→Tier, geschützter Satz). 5. Sicherstellen, dass die übrigen Wächter stehen (Mutation-Ratchet, Semgrep-Fluchttür, geschützter Satz) — sonst verweigert `/devloop:loop` zu Recht den Auto-Loop. diff --git a/src/cli/derive-tier.ts b/src/cli/derive-tier.ts index 28cc5f8..043ca41 100644 --- a/src/cli/derive-tier.ts +++ b/src/cli/derive-tier.ts @@ -3,16 +3,21 @@ // - { touched, tierMap } — caller supplies the map content (no path resolution) // - { touched, repo } — devloop LOCATES the repo's tier-map robustly (absolute // path: .devloop/ -> tools/ -> root) and reads it itself. +// - { touched, repo, baseRef } — wie oben, aber die Suche laeuft in der BASIS (`git show`): +// ein PR waehlt seine tier-map nicht selbst (Issue #13). Hat die +// Basis keinen Kandidaten, gilt der erste Kandidat im Arbeitsbaum. // Always plain node (sandbox-clean) — never a repo's tsx-based `pnpm run tier`. import { readFileSync } from "node:fs"; import { deriveTier, type TierMapInput } from "../core/tier.js"; -import { resolveTierMapPath } from "../core/tier-map.js"; +import { resolveTierMapPath, TIER_MAP_CANDIDATES } from "../core/tier-map.js"; +import { readTreeEntry } from "../core/tree-entry.js"; import { readStdin } from "./_stdin.js"; interface Request { touched: string[]; repo?: string; + baseRef?: string; tierMap?: TierMapInput; } @@ -26,17 +31,36 @@ if (!tierMap) { process.stderr.write("derive-tier: provide either `tierMap` or `repo` on stdin\n"); process.exit(2); } - const found = resolveTierMapPath(req.repo); - if (!found) { - process.stderr.write( - `derive-tier: no tier-map found under ${req.repo} (.devloop/ , tools/ , or root)\n`, - ); - process.exit(2); + let fromBase = false; + if (req.baseRef) { + try { + for (const cand of TIER_MAP_CANDIDATES) { + const entry = readTreeEntry(req.repo, req.baseRef, cand); + if (entry.kind === "missing") continue; + if (entry.kind !== "file") throw new Error(`${cand} ist in der Basis kein regulaeres Blob (${entry.kind})`); + tierMap = JSON.parse(entry.content) as TierMapInput; + tierMapPath = `${req.baseRef}:${cand}`; + fromBase = true; + break; + } + } catch (e) { + process.stderr.write(`derive-tier: tier-map der Basis ${req.baseRef} unlesbar: ${(e as Error).message}\n`); + process.exit(1); + } + } + if (!fromBase) { + const found = resolveTierMapPath(req.repo); + if (!found) { + process.stderr.write( + `derive-tier: no tier-map found under ${req.repo} (.devloop/ , tools/ , or root)\n`, + ); + process.exit(2); + } + tierMapPath = found; + tierMap = JSON.parse(readFileSync(found, "utf8")) as TierMapInput; } - tierMapPath = found; - tierMap = JSON.parse(readFileSync(found, "utf8")) as TierMapInput; } process.stdout.write( - JSON.stringify({ tier: deriveTier(req.touched, tierMap), tierMapPath }) + "\n", + JSON.stringify({ tier: deriveTier(req.touched, tierMap as TierMapInput), tierMapPath }) + "\n", ); diff --git a/src/cli/verify-review.ts b/src/cli/verify-review.ts index 001f6b3..208bc1d 100644 --- a/src/cli/verify-review.ts +++ b/src/cli/verify-review.ts @@ -5,6 +5,9 @@ // stdin JSON: { reviews, prAuthor, headSha, botLogins?, humanReviewers?, diffPaths?, protectedGlobs?, // tier?, headRef?, baseRef?, repo? } // Spec-Aenderungen (REQ-SPECGATE-*) umgehen die T0/T1-Abkuerzung nicht und verlangen Basis-CODEOWNERS-Deckung. +// Mit baseRef kommen protectedGlobs und botLogins aus der Basis (Rueckfall: Arbeitsbaum, dann stdin; +// REQ-CFGBASE-2..4), und Config-Aenderungen (.devloop/**, tier-map) verhalten sich wie Spec-Aenderungen +// (REQ-CFGBASE-5/6), ausser bei Erstaufnahme. // reviews come from `gh api repos/{owner}/{repo}/pulls/{n}/reviews`. import { evaluateApproval, type Review, type ApprovalContext } from "../core/review.js"; @@ -17,6 +20,13 @@ import { uncoveredByCodeowners, SPEC_GLOBS_PATH, } from "../core/spec-change.js"; +import { + BOT_LOGINS_PATH, + PROTECTED_GLOBS_PATH, + configPaths, + isInitialAdoption, + readConfigList, +} from "../core/config-change.js"; import { readStdin } from "./_stdin.js"; interface Request extends ApprovalContext { @@ -37,18 +47,37 @@ function fail(reason: string): never { const req = JSON.parse(await readStdin()) as Request; const reviews = req.reviews ?? []; +const repo = req.repo ?? "."; + +// 0. Config-Listen aus der Basis (REQ-CFGBASE-2/3/4). Unlesbar = config-invalid (kein Rueckfall), +// nirgends vorhanden = config-missing. Ohne baseRef gilt nur der stdin-Wert wie bisher. +let protectedGlobs = req.protectedGlobs; +let botLogins = req.botLogins; +if (req.baseRef) { + try { + const pg = readConfigList(repo, req.baseRef, PROTECTED_GLOBS_PATH); + const bl = readConfigList(repo, req.baseRef, BOT_LOGINS_PATH); + protectedGlobs = pg?.list ?? req.protectedGlobs; + botLogins = bl?.list ?? req.botLogins; + } catch (e) { + fail(`config-invalid: ${(e as Error).message}`); + } + const missing = [ + ...(protectedGlobs === undefined ? [PROTECTED_GLOBS_PATH] : []), + ...(botLogins === undefined ? [BOT_LOGINS_PATH] : []), + ]; + if (missing.length > 0) { + fail(`config-missing: weder in der Basis ${req.baseRef}, im Arbeitsbaum noch auf stdin: ${missing.join(", ")}`); + } +} +const approvalCtx: ApprovalContext = { ...req, botLogins }; // 1. Gate-tamper fails ALWAYS, independent of approval state (reward-hacking alarm). -if ( - req.diffPaths && - req.protectedGlobs && - touchesProtectedSet(req.diffPaths, req.protectedGlobs) -) { +if (req.diffPaths && protectedGlobs && touchesProtectedSet(req.diffPaths, protectedGlobs)) { fail("protected-set-touched: the diff edits a guardian/gate config (reward-hacking alarm)"); } // 1b. Spec-Aenderung (REQ-SPECGATE-1..7). Config gilt immer (REQ-5): ungueltig = fail-closed. -const repo = req.repo ?? "."; let globs: string[]; try { globs = specGlobs(repo, req.baseRef); @@ -84,17 +113,48 @@ if (specChange) { } } +// 1c. Config-Aenderung (REQ-CFGBASE-5/6): kein Abkuerzen, Basis-CODEOWNERS muessen die Pfade decken. +// Erstaufnahme (Basis ohne jeden Config-Pfad) ist ausgenommen: es gibt nichts zu schuetzen. +let configChange = false; +if (req.baseRef) { + const cfgPaths = configPaths(diffPaths); + if (cfgPaths.length > 0) { + let adoption: boolean; + try { + adoption = isInitialAdoption(repo, req.baseRef); + } catch (e) { + fail(`config-invalid: ${(e as Error).message}`); + } + if (!adoption) { + configChange = true; + let owners: string | null; + try { + owners = readBaseCodeowners(repo, req.baseRef); + } catch (e) { + fail(`config-unguarded: ${(e as Error).message} (Config-Pfade: ${cfgPaths.join(", ")})`); + } + const uncovered = uncoveredByCodeowners(cfgPaths, owners); + if (uncovered.length > 0) { + fail( + `config-unguarded: Config-Pfade ohne CODEOWNERS-Deckung in der Basis ${req.baseRef}` + + `${owners === null ? " (keine CODEOWNERS gefunden)" : ""}: ${uncovered.join(", ")}`, + ); + } + } + } +} + // 2. Tier gate (§9): T0/T1 auto-merge — no approval required. (Gate-tamper above still applied.) // Unknown/absent tier defaults to conservative "T3" (approval required). The authoritative // T2/T3 merge block is branch protection's required CODEOWNER review on the high-tier paths; // this check additionally validates a present approval (human, on HEAD) and the protected set. const tier = req.tier ?? "T3"; -if (!specChange && (tier === "T0" || tier === "T1")) { +if (!specChange && !configChange && (tier === "T0" || tier === "T1")) { process.stdout.write(JSON.stringify({ ok: true, tier, note: "tier T0/T1: no approval required (§9)" }) + "\n"); process.exit(0); } -const status = evaluateApproval(reviews, req); +const status = evaluateApproval(reviews, approvalCtx); if (status === "ok") { process.stdout.write(JSON.stringify({ ok: true }) + "\n"); process.exit(0); diff --git a/src/cli/verify-unskip.ts b/src/cli/verify-unskip.ts index fd6afbb..9fdc1b9 100644 --- a/src/cli/verify-unskip.ts +++ b/src/cli/verify-unskip.ts @@ -5,8 +5,9 @@ // // SCOPE: the seam applies to the tests devloop MANAGES (those `spec-to-tests` derives from a // reviewed spec), not to every test file in the repo. The target repo declares them in -// `.devloop/managed-tests.json` (glob list) — a file inside the protected set, so an agent -// cannot widen it. No such file => every test file is managed (today's behaviour, fail-closed). +// `.devloop/managed-tests.json` (glob list) — read from the BASE; changing it is a config change +// that needs a CODEOWNERS review (verify-review, #13), so an agent cannot widen it on its own. +// No such file => every test file is managed (today's behaviour, fail-closed). // Deliberately NOT branch-name-driven: an agent chooses its own branch name. // // Usage: verify-unskip [headBranch] (baseRef e.g. origin/main) @@ -42,7 +43,7 @@ const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/; // The glob list is read from the BASE ref first: the scope that is already on the protected // branch decides, so a PR cannot loosen the seam for itself. Only if the file does not exist on // base do we fall back to the checkout (a repo adopting the file — that PR necessarily touches -// `.devloop/**` = the protected set and is already flagged by verify-review). +// `.devloop/**`, a config change that verify-review handles: review required unless initial adoption). const readWorktree = (rel: string): string => { try { return readFileSync(join(repo, rel), "utf8"); diff --git a/src/core/config-change.ts b/src/core/config-change.ts new file mode 100644 index 0000000..6ca0daf --- /dev/null +++ b/src/core/config-change.ts @@ -0,0 +1,98 @@ +// `.devloop/`-Config aus der Basis (Issue #13, docs/2026-11-27-devloop-config-aus-basis-design.md). +// Die Precondition-Action darf die Regeln, nach denen ein PR geprueft wird, nicht aus dem PR-HEAD +// lesen. Dieses Modul liest Config-Listen aus der Basis (`git show`) und erkennt Config-Aenderungen; +// die CODEOWNERS-Deckung der Basis (wie bei Spec-Pfaden, #4) erzwingt das Review. + +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { matchesAnyGlob } from "./glob.js"; +import { readTreeEntry } from "./tree-entry.js"; + +export const PROTECTED_GLOBS_PATH = ".devloop/protected-globs.json"; +export const BOT_LOGINS_PATH = ".devloop/bot-logins.json"; + +/** Config-Pfade: alles unter `.devloop/` plus die tier-map-Kandidaten ausserhalb davon. */ +export const CONFIG_GLOBS: readonly string[] = [".devloop/**", "tools/tier-map.json", "tier-map.json"]; + +export class ConfigInvalidError extends Error {} + +export const configPaths = (diffPaths: string[]): string[] => + diffPaths.filter((p) => matchesAnyGlob(p, [...CONFIG_GLOBS])); + +export const isConfigChange = (diffPaths: string[]): boolean => configPaths(diffPaths).length > 0; + +function assertRefResolvable(repo: string, baseRef: string): void { + if (baseRef.startsWith("-")) throw new ConfigInvalidError(`ungueltiger baseRef: ${baseRef}`); + try { + execFileSync("git", ["-C", repo, "rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`], { + stdio: ["ignore", "pipe", "ignore"], + }); + } catch { + throw new ConfigInvalidError(`baseRef nicht aufloesbar: ${baseRef}`); + } +} + +/** + * Erstaufnahme: die Basis enthaelt keinen einzigen Config-Pfad (der PR, der devloop einrichtet). + * Ein unaufloesbarer baseRef wirft (fail-closed), er gilt nie als "leere Basis". + */ +export function isInitialAdoption(repo: string, baseRef: string): boolean { + assertRefResolvable(repo, baseRef); + let out: string; + try { + out = execFileSync( + "git", + ["-C", repo, "--literal-pathspecs", "ls-tree", "-r", "-z", "--name-only", baseRef, "--", ".devloop", "tools/tier-map.json", "tier-map.json"], + { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }, + ); + } catch (e) { + throw new ConfigInvalidError(`Basis ${baseRef} nicht lesbar: ${(e as Error).message}`); + } + return !out.split("\0").some((p) => p !== "" && matchesAnyGlob(p, [...CONFIG_GLOBS])); +} + +/** Parst ein JSON-Array von Strings (leeres Array ist gueltig). Sonst ConfigInvalidError. */ +export function parseStringArray(raw: string, label: string): string[] { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new ConfigInvalidError(`${label} ist kein gueltiges JSON`); + } + if (!Array.isArray(parsed) || !parsed.every((x) => typeof x === "string")) { + throw new ConfigInvalidError(`${label} ist kein JSON-Array von Strings`); + } + return parsed as string[]; +} + +/** + * Liest eine String-Listen-Config. Rangfolge: (1) Basis, (2) Arbeitsbaum, (3) null (Aufrufer + * entscheidet, z. B. stdin-Wert). Existiert die Basis-Datei, aber ist unlesbar (kein JSON, falsche + * Form, kein reguelaeres Blob), wirft sie ConfigInvalidError: kein Rueckfall auf HEAD. + */ +export function readConfigList( + repo: string, + baseRef: string, + path: string, +): { list: string[]; source: "base" | "worktree" } | null { + assertRefResolvable(repo, baseRef); + let entry; + try { + entry = readTreeEntry(repo, baseRef, path); + } catch (e) { + throw new ConfigInvalidError(`${path} in der Basis ${baseRef} nicht lesbar: ${(e as Error).message}`); + } + if (entry.kind === "file") return { list: parseStringArray(entry.content, `${path} (Basis)`), source: "base" }; + if (entry.kind !== "missing") { + throw new ConfigInvalidError(`${path} in der Basis ${baseRef} ist kein regulaeres Blob (${entry.kind})`); + } + let raw: string; + try { + raw = readFileSync(join(repo, path), "utf8"); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "ENOENT") return null; + throw new ConfigInvalidError(`${path} im Arbeitsbaum nicht lesbar: ${(e as Error).message}`); + } + return { list: parseStringArray(raw, `${path} (Arbeitsbaum)`), source: "worktree" }; +} diff --git a/src/core/init.ts b/src/core/init.ts index 8e3d1d9..fd0f305 100644 --- a/src/core/init.ts +++ b/src/core/init.ts @@ -5,10 +5,11 @@ // existing workflow is left stale — `force` overwrites the workflow for a real migration. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { dirname, join, relative } from "node:path"; import { resolveTierMapPath } from "./tier-map.js"; import { tierGlobs, type TierMapInput } from "./tier.js"; -import { parseCodeowners, findUncoveredTierGlobs } from "./codeowners.js"; +import { parseCodeowners, findUncoveredTierGlobs, codeownersCovers } from "./codeowners.js"; +import { uncoveredSpecPaths } from "./spec-change.js"; // Convert a tier glob to a CODEOWNERS path: `services/**` -> `/services/` (anchored dir), // `**/auth/**` -> `auth/` (matches anywhere). A skeleton line for the human to assign owners. @@ -19,6 +20,12 @@ function tierGlobToCodeownersPath(glob: string): string { return "/" + glob.replace(/\/\*\*$/, "/").replace(/\*\*$/, "").replace(/\*$/, ""); } +// tier-map outside `.devloop/` (tools/ or root) as CODEOWNERS paths, else null. +function tierMapOutsideDevloop(repo: string, tierMapPath: string): string[] | null { + const rel = relative(repo, tierMapPath); + return rel.startsWith(".devloop/") ? null : ["/" + rel]; +} + export interface InitResult { created: string[]; skipped: string[]; @@ -40,8 +47,9 @@ const PROTECTED_GLOBS_SKELETON = JSON.stringify( // Which test paths the unskip seam (§11) binds. The skeleton is the FAIL-CLOSED default — // `**` = every test file, i.e. exactly the pre-v0.8.1 behaviour. Narrow it to the paths // spec-to-tests actually authors (the caged services / twin areas), otherwise a plain PR that -// adds an ordinary active test file cannot pass the guard. Lives in `.devloop/` = the protected -// set, so an agent cannot widen it to smuggle its own tests past the seam. +// adds an ordinary active test file cannot pass the guard. verify-unskip reads it from the BASE; +// a PR that changes `.devloop/**` is a config change and needs a CODEOWNERS review (#13), so an +// agent cannot widen it to smuggle its own tests past the seam. const MANAGED_TESTS_SKELETON = JSON.stringify( { _comment: @@ -127,7 +135,7 @@ export function initRepo( if (existingTierMap) { result.skipped.push(".devloop/tier-map.json"); result.notes.push( - `tier-map already present (${existingTierMap.replace(targetRepo + "/", "")}) — not writing ` + + `tier-map already present (${relative(targetRepo, existingTierMap)}) — not writing ` + `.devloop/tier-map.json (it would shadow yours). Reconcile your map with the devloop tier rules.`, ); } else { @@ -161,19 +169,32 @@ export function initRepo( ); if (!coRel) { const owners = [...new Set(t2t3.map(tierGlobToCodeownersPath))].map((p) => `${p} @OWNER`); + // Config-Pfade (#13): /.devloop/ plus a tier-map outside it, so a config change needs a review. + const cfg = ["/.devloop/", ...(tierMapOutsideDevloop(targetRepo, tierMapPath) ?? [])].map((p) => `${p} @OWNER`); write( ".github/CODEOWNERS", "# devloop: T2/T3 tier paths require a human CODEOWNER review (the §9 merge gate).\n" + - "# Replace @OWNER with the real owner(s). Keep your protected set (gate configs) covered too.\n" + - owners.join("\n") + + "# Replace @OWNER with the real owner(s). /.devloop/ must stay covered: verify-review requires\n" + + "# a review for config changes, read against the BASE CODEOWNERS (else `config-unguarded`).\n" + + [...cfg, ...owners].join("\n") + "\n", ); } else { result.skipped.push(coRel); - const uncovered = findUncoveredTierGlobs( - t2t3, - parseCodeowners(readFileSync(join(targetRepo, coRel), "utf8")), - ); + const patterns = parseCodeowners(readFileSync(join(targetRepo, coRel), "utf8")); + const outside = (tierMapOutsideDevloop(targetRepo, tierMapPath) ?? []).map((p) => p.slice(1)); + const uncoveredCfg = [ + ...(patterns.some((pat) => codeownersCovers(".devloop/config.json", pat)) ? [] : [".devloop/"]), + ...uncoveredSpecPaths(outside, patterns), + ]; + if (uncoveredCfg.length > 0) { + result.notes.push( + `CODEOWNERS (${coRel}) does not cover these devloop config paths: ${uncoveredCfg.join(", ")} — add ` + + `owner lines (e.g. "/.devloop/ @OWNER"). Without them, every change to .devloop/** or the ` + + `tier-map fails verify-review with config-unguarded.`, + ); + } + const uncovered = findUncoveredTierGlobs(t2t3, patterns); if (uncovered.length > 0) { result.notes.push( `CODEOWNERS (${coRel}) does not cover these T2/T3 tier paths — add owner lines, else such ` + diff --git a/src/core/managed-tests.ts b/src/core/managed-tests.ts index b3b00cf..75e1f0f 100644 --- a/src/core/managed-tests.ts +++ b/src/core/managed-tests.ts @@ -8,10 +8,11 @@ // // The distinction comes from a CONFIG FILE IN THE TARGET REPO — `.devloop/managed-tests.json`, // a glob list — deliberately NOT from the branch name: an agent picks its own branch name, so a -// branch-coupled exemption is self-serve. `.devloop/**` is part of the protected set -// (protected-globs.json), so an agent cannot widen the exemption list to smuggle its own tests -// past the seam — `verify-review` fails a diff that touches the protected set, unconditionally -// and independent of tier, BEFORE the unskip step ever runs. +// branch-coupled exemption is self-serve. verify-unskip reads the file from the BASE first, and a +// PR that changes `.devloop/**` is a config change: `verify-review` skips the T0/T1 shortcut and +// requires that the BASE CODEOWNERS cover `.devloop/` (else `config-unguarded`), so GitHub demands a +// human review (#13). An agent therefore cannot widen the exemption list on its own to smuggle +// its own tests past the seam. // // Fail-closed & backwards compatible: NO config file (or an unreadable/malformed one) means // EVERY test file is managed — exactly today's behaviour. No existing adopter gets looser by diff --git a/test/cli/config-aus-basis.test.ts b/test/cli/config-aus-basis.test.ts new file mode 100644 index 0000000..e746f49 --- /dev/null +++ b/test/cli/config-aus-basis.test.ts @@ -0,0 +1,599 @@ +// [REQ-CFGBASE-*] .devloop-Config aus der Basis (#13). CLI-Tests gegen dist/ in temporaeren Git-Repos +// mit echter Basis (Branch "base", echtes `git show`). Keine Attrappen. +import { test, expect, afterEach } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { dirname, resolve, join } from "node:path"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const verifyCli = join(root, "dist/cli/verify-review.js"); +const deriveCli = join(root, "dist/cli/derive-tier.js"); + +const dirs: string[] = []; +afterEach(() => { + while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); +}); + +function git(repo: string, ...args: string[]): void { + const r = spawnSync("git", ["-c", "commit.gpgsign=false", ...args], { cwd: repo, encoding: "utf8" }); + if (r.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${r.stderr}`); +} + +function write(repo: string, rel: string, content: string): void { + const p = join(repo, rel); + mkdirSync(dirname(p), { recursive: true }); + writeFileSync(p, content); +} + +const DEFAULT_CONFIG: Record = { + ".devloop/tier-map.json": JSON.stringify({ T1: ["**"] }), + ".devloop/bot-logins.json": '["agent-bot"]', + ".devloop/protected-globs.json": '["**/stryker.conf.*"]', +}; + +// Basis-Commit auf Branch "base". Standard: komplette Config (kein Erstaufnahme-Fall). +// files: Pfad -> Inhalt; null entfernt einen Standard-Eintrag. +function makeRepo(files: Record = {}, withDefaults = true): string { + const repo = mkdtempSync(join(tmpdir(), "config-aus-basis-")); + dirs.push(repo); + git(repo, "init", "-q", "-b", "base"); + git(repo, "config", "user.name", "Test"); + git(repo, "config", "user.email", "test@example.invalid"); + write(repo, "README.md", "x\n"); + const all = { ...(withDefaults ? DEFAULT_CONFIG : {}), ...files }; + for (const [p, c] of Object.entries(all)) if (c !== null) write(repo, p, c); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "base"); + return repo; +} + +// Branch "feature" mit PR-Aenderungen (null = loeschen), Commit + Arbeitsbaum. +function branchWith(repo: string, files: Record): void { + git(repo, "checkout", "-q", "-b", "feature"); + for (const [p, c] of Object.entries(files)) { + if (c === null) git(repo, "rm", "-q", p); + else write(repo, p, c); + } + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "pr"); +} + +const baseReq = { prAuthor: "agent-bot", headSha: "abc123", tier: "T1", baseRef: "base", headRef: "feature/y", reviews: [] }; + +function run(repo: string, req: object) { + const r = spawnSync("node", [verifyCli], { + encoding: "utf8", + input: JSON.stringify({ ...baseReq, repo, ...req }), + cwd: root, + }); + let out: any = {}; + try { + out = JSON.parse(r.stdout); + } catch { + /* leer lassen: Assertions auf ok scheitern mit klarem Diff */ + } + return { status: r.status, out, stdout: r.stdout }; +} + +function derive(repo: string, req: object) { + const r = spawnSync("node", [deriveCli], { encoding: "utf8", input: JSON.stringify({ repo, ...req }), cwd: root }); + let out: any = {}; + try { + out = JSON.parse(r.stdout); + } catch { + /* leer */ + } + return { status: r.status, out, stderr: r.stderr }; +} + +const COVER_CFG = "/.devloop/ @alice\n"; +const aliceOk = { user: "alice", state: "APPROVED", commit_id: "abc123" }; +const cfgDiff = [".devloop/protected-globs.json"]; + +// ---------- REQ-CFGBASE-1: derive-tier liest die tier-map aus der Basis ---------- + +test("[REQ-CFGBASE-1] Basis-tier-map src/** -> T3, PR stuft in HEAD auf T1 herab -> Tier T3", () => { + const repo = makeRepo({ ".devloop/tier-map.json": JSON.stringify({ T3: ["src/**"], T1: ["**"] }) }); + branchWith(repo, { ".devloop/tier-map.json": JSON.stringify({ T1: ["**"] }), "src/a.ts": "x\n" }); + const r = derive(repo, { touched: ["src/a.ts", ".devloop/tier-map.json"], baseRef: "base" }); + expect(r.status).toBe(0); + expect(r.out.tier).toBe("T3"); +}); + +test("[REQ-CFGBASE-1] Basis-tier-map nur unter tools/, HEAD legt .devloop/tier-map.json (T1) an -> Tier aus tools/ der Basis", () => { + const repo = makeRepo( + { ".devloop/tier-map.json": null, "tools/tier-map.json": JSON.stringify({ T3: ["src/**"], T1: ["**"] }) }, + ); + branchWith(repo, { ".devloop/tier-map.json": JSON.stringify({ T1: ["**"] }), "src/a.ts": "x\n" }); + const r = derive(repo, { touched: ["src/a.ts", ".devloop/tier-map.json"], baseRef: "base" }); + expect(r.status).toBe(0); + expect(r.out.tier).toBe("T3"); +}); + +test("[REQ-CFGBASE-1] Suchreihenfolge in der Basis: .devloop/ vor tools/ vor Root", () => { + const repo = makeRepo({ + ".devloop/tier-map.json": null, + "tools/tier-map.json": JSON.stringify({ T2: ["src/**"], T1: ["**"] }), + "tier-map.json": JSON.stringify({ T3: ["src/**"], T1: ["**"] }), + }); + branchWith(repo, { "src/a.ts": "x\n" }); + const r = derive(repo, { touched: ["src/a.ts"], baseRef: "base" }); + expect(r.status).toBe(0); + expect(r.out.tier).toBe("T2"); +}); + +test("[REQ-CFGBASE-1][REQ-CFGBASE-4] Gegenprobe: Basis ohne tier-map-Kandidat -> Arbeitsbaum gilt (wie heute)", () => { + const repo = makeRepo({ ".devloop/tier-map.json": null }); + branchWith(repo, { ".devloop/tier-map.json": JSON.stringify({ T2: ["src/**"], T1: ["**"] }), "src/a.ts": "x\n" }); + const r = derive(repo, { touched: ["src/a.ts"], baseRef: "base" }); + expect(r.status).toBe(0); + expect(r.out.tier).toBe("T2"); +}); + +test("[REQ-CFGBASE-1] Gegenprobe: ohne baseRef wie bisher aus dem Arbeitsbaum", () => { + const repo = makeRepo({ ".devloop/tier-map.json": JSON.stringify({ T3: ["src/**"], T1: ["**"] }) }); + branchWith(repo, { ".devloop/tier-map.json": JSON.stringify({ T2: ["src/**"], T1: ["**"] }) }); + const r = derive(repo, { touched: ["src/a.ts"] }); + expect(r.status).toBe(0); + expect(r.out.tier).toBe("T2"); +}); + +// ---------- REQ-CFGBASE-3: unlesbare Basis-Datei, fail-closed ---------- + +test("[REQ-CFGBASE-3] Basis-tier-map = `{`, Arbeitsbaum gueltig -> derive-tier Exit != 0 (kein Rueckfall auf HEAD)", () => { + const repo = makeRepo({ ".devloop/tier-map.json": "{" }); + branchWith(repo, { ".devloop/tier-map.json": JSON.stringify({ T1: ["**"] }) }); + const r = derive(repo, { touched: ["src/a.ts"], baseRef: "base" }); + expect(r.status).not.toBe(0); + expect(r.status).not.toBeNull(); +}); + +test("[REQ-CFGBASE-3] Basis-tier-map ist ein Verzeichnis (kein reguelaeres Blob) -> derive-tier Exit != 0", () => { + const repo = makeRepo({ ".devloop/tier-map.json": null, ".devloop/tier-map.json/x": "a\n" }); + branchWith(repo, { "src/a.ts": "x\n" }); + const r = derive(repo, { touched: ["src/a.ts"], baseRef: "base" }); + expect(r.status).not.toBe(0); +}); + +test("[REQ-CFGBASE-3] Basis-protected-globs = `{` -> config-invalid (kein Rueckfall auf stdin/HEAD/leer)", () => { + const repo = makeRepo({ ".devloop/protected-globs.json": "{" }); + branchWith(repo, { ".devloop/protected-globs.json": "[]", "src/a.ts": "x\n" }); + const r = run(repo, { diffPaths: ["src/a.ts"], protectedGlobs: [] }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).toMatch(/^config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-protected-globs falsche Form ({}, [1], [\"a\",null], Objekt) -> config-invalid", () => { + for (const content of ["{}", "[1]", '["a", null]', '{"globs":["a"]}', "null", ""]) { + const repo = makeRepo({ ".devloop/protected-globs.json": content }); + const r = run(repo, { diffPaths: ["src/a.ts"], protectedGlobs: [] }); + expect(r.out.reason, JSON.stringify(content)).toMatch(/^config-invalid/); + expect(r.status, JSON.stringify(content)).toBe(1); + } +}); + +test("[REQ-CFGBASE-3] Basis-protected-globs ist ein Verzeichnis (kein reguelaeres Blob) -> config-invalid", () => { + const repo = makeRepo({ ".devloop/protected-globs.json": null, ".devloop/protected-globs.json/x": "a\n" }); + const r = run(repo, { diffPaths: ["src/a.ts"], protectedGlobs: [] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-bot-logins = `{` -> config-invalid, auch wenn stdin und Arbeitsbaum gueltig sind", () => { + const repo = makeRepo({ ".devloop/bot-logins.json": "{" }); + branchWith(repo, { ".devloop/bot-logins.json": '["agent-bot"]' }); + const r = run(repo, { diffPaths: ["src/a.ts"], botLogins: ["agent-bot"] }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).toMatch(/^config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-bot-logins falsche Form ({}, [1], \"x\") und Verzeichnis -> config-invalid", () => { + for (const content of ["{}", "[1]", '"x"']) { + const repo = makeRepo({ ".devloop/bot-logins.json": content }); + const r = run(repo, { diffPaths: ["src/a.ts"], botLogins: ["agent-bot"] }); + expect(r.out.reason, content).toMatch(/^config-invalid/); + } + const repo = makeRepo({ ".devloop/bot-logins.json": null, ".devloop/bot-logins.json/x": "a\n" }); + const r = run(repo, { diffPaths: ["src/a.ts"], botLogins: ["agent-bot"] }); + expect(r.out.reason).toMatch(/^config-invalid/); +}); + +// ---------- REQ-CFGBASE-2: verify-review nimmt Protected-Globs und Bot-Logins aus der Basis ---------- + +test("[REQ-CFGBASE-2] Basis-protected-globs mit stryker-Glob, PR leert die Liste und aendert stryker.conf.json -> protected-set-touched", () => { + const repo = makeRepo(); + branchWith(repo, { ".devloop/protected-globs.json": "[]", "stryker.conf.json": "{}" }); + // stdin traegt die (geleerte) HEAD-Liste wie die alte Action + const r = run(repo, { diffPaths: ["stryker.conf.json", ".devloop/protected-globs.json"], protectedGlobs: [] }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-2] Basis-bot-logins [\"bot\"], PR leert die Liste, Approval von bot auf HEAD, T2 -> ok:false", () => { + const repo = makeRepo({ ".devloop/bot-logins.json": '["bot"]' }, true); + git(repo, "checkout", "-q", "-b", "feature"); + write(repo, ".devloop/bot-logins.json", "[]"); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "pr"); + const r = run(repo, { + tier: "T2", + prAuthor: "someone", + diffPaths: ["src/a.ts"], + botLogins: [], + reviews: [{ user: "bot", state: "APPROVED", commit_id: "abc123" }], + }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).toMatch(/human-approval/); +}); + +test("[REQ-CFGBASE-2] Gegenprobe: dieselbe Lage mit menschlicher Approval -> ok:true", () => { + const repo = makeRepo({ ".devloop/bot-logins.json": '["bot"]' }); + const r = run(repo, { tier: "T2", prAuthor: "someone", diffPaths: ["src/a.ts"], reviews: [aliceOk] }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); +}); + +// ---------- REQ-CFGBASE-4: Rangfolge Basis -> Arbeitsbaum -> stdin -> config-missing ---------- + +const stryker = { diffPaths: ["stryker.conf.json"] }; + +test("[REQ-CFGBASE-4] Rangfolge: Basis (stryker-Glob) schlaegt Arbeitsbaum ([]) und stdin ([])", () => { + const repo = makeRepo(); + write(repo, ".devloop/protected-globs.json", "[]"); // nur Arbeitsbaum, nicht committet + const r = run(repo, { ...stryker, protectedGlobs: [] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-4] Rangfolge: Basis ohne protected-globs, Arbeitsbaum mit stryker-Glob schlaegt stdin ([])", () => { + const repo = makeRepo({ ".devloop/protected-globs.json": null }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/stryker.conf.*"]' }); + const r = run(repo, { ...stryker, protectedGlobs: [] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-4] Rangfolge: weder Basis noch Arbeitsbaum -> stdin-Wert gilt (stryker-Glob greift)", () => { + const repo = makeRepo({ ".devloop/protected-globs.json": null }); + const r = run(repo, { ...stryker, protectedGlobs: ["**/stryker.conf.*"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-4] protected-globs fehlt ueberall (Basis, Arbeitsbaum, stdin) -> config-missing", () => { + const repo = makeRepo({ ".devloop/protected-globs.json": null }); + const r = run(repo, { diffPaths: ["src/a.ts"] }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).toMatch(/^config-missing/); +}); + +test("[REQ-CFGBASE-4] bot-logins fehlt ueberall -> config-missing", () => { + const repo = makeRepo({ ".devloop/bot-logins.json": null }); + const r = run(repo, { diffPaths: ["src/a.ts"] }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).toMatch(/^config-missing/); +}); + +test("[REQ-CFGBASE-4] Rangfolge bot-logins: Basis ohne Datei, Arbeitsbaum [\"bot\"] schlaegt stdin ([]) -> Bot-Approval zaehlt nicht", () => { + const repo = makeRepo({ ".devloop/bot-logins.json": null }); + branchWith(repo, { ".devloop/bot-logins.json": '["bot"]' }); + const r = run(repo, { + tier: "T2", + prAuthor: "someone", + diffPaths: ["src/a.ts"], + botLogins: [], + reviews: [{ user: "bot", state: "APPROVED", commit_id: "abc123" }], + }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); +}); + +test("[REQ-CFGBASE-4] Rangfolge bot-logins: weder Basis noch Arbeitsbaum -> stdin gilt (Bot-Approval zaehlt nicht)", () => { + const repo = makeRepo({ ".devloop/bot-logins.json": null }); + const r = run(repo, { + tier: "T2", + prAuthor: "someone", + diffPaths: ["src/a.ts"], + botLogins: ["bot"], + reviews: [{ user: "bot", state: "APPROVED", commit_id: "abc123" }], + }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); +}); + +test("[REQ-CFGBASE-4][REQ-CFGBASE-7] Gegenprobe: ohne baseRef gilt nur stdin wie bisher (kein config-missing)", () => { + const repo = makeRepo({}, false); + const ok = run(repo, { baseRef: undefined, diffPaths: ["src/a.ts"] }); + expect(ok.status).toBe(0); + expect(ok.out.ok).toBe(true); + const tamper = run(repo, { baseRef: undefined, diffPaths: ["stryker.conf.json"], protectedGlobs: ["**/stryker.conf.*"] }); + expect(tamper.status).toBe(1); + expect(tamper.out.reason).toMatch(/protected-set-touched/); +}); + +// ---------- REQ-CFGBASE-5/6: Config-Aenderung ---------- + +test("[REQ-CFGBASE-6] T1, PR aendert nur .devloop/protected-globs.json, Basis-CODEOWNERS ohne /.devloop/ -> config-unguarded mit Pfad", () => { + const repo = makeRepo({ CODEOWNERS: "/src/ @alice\n" }); + branchWith(repo, { ".devloop/protected-globs.json": "[]" }); + const r = run(repo, { diffPaths: cfgDiff }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).toMatch(/^config-unguarded/); + expect(r.stdout).toContain(".devloop/protected-globs.json"); +}); + +test("[REQ-CFGBASE-6] Basis ganz ohne CODEOWNERS (Basis hat Config) -> config-unguarded", () => { + const repo = makeRepo(); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { diffPaths: cfgDiff }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-unguarded/); +}); + +test("[REQ-CFGBASE-6] ungedeckter Config-Pfad: auch menschliche Approval auf HEAD rettet nicht (Deckung vor Approval)", () => { + const repo = makeRepo({ CODEOWNERS: "/src/ @alice\n" }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { diffPaths: cfgDiff, reviews: [aliceOk] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-unguarded/); +}); + +test("[REQ-CFGBASE-6] mehrere Config-Pfade: nur der ungedeckte wird genannt", () => { + const repo = makeRepo({ CODEOWNERS: "/.devloop/protected-globs.json @alice\n" }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]', ".devloop/bot-logins.json": '["agent-bot","y"]' }); + const r = run(repo, { diffPaths: [".devloop/protected-globs.json", ".devloop/bot-logins.json"] }); + expect(r.out.reason).toMatch(/^config-unguarded/); + expect(r.stdout).toContain(".devloop/bot-logins.json"); + expect(r.stdout).not.toContain(".devloop/protected-globs.json"); +}); + +test("[REQ-CFGBASE-5] Config-Aenderung mit Deckung, keine Reviews -> ok:true, pending:true (kein harter Fail)", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { diffPaths: cfgDiff }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); + expect(r.out.pending).toBe(true); +}); + +test("[REQ-CFGBASE-5] Config-Aenderung mit Deckung, T0 -> ebenfalls pending (keine T0/T1-Abkuerzung)", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { tier: "T0", diffPaths: cfgDiff }); + expect(r.status).toBe(0); + expect(r.out.pending).toBe(true); +}); + +test("[REQ-CFGBASE-5] Config-Aenderung mit Deckung, Approval auf altem SHA -> ok:false", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { diffPaths: cfgDiff, reviews: [{ user: "alice", state: "APPROVED", commit_id: "old" }] }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); +}); + +test("[REQ-CFGBASE-5] Config-Aenderung mit Deckung, Bot-Approval auf HEAD -> ok:false", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { diffPaths: cfgDiff, reviews: [{ user: "agent-bot", state: "APPROVED", commit_id: "abc123" }] }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); +}); + +test("[REQ-CFGBASE-5] Gegenprobe: Config-Aenderung mit Deckung, menschliche Approval auf HEAD -> ok:true, nicht pending", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { diffPaths: cfgDiff, reviews: [aliceOk] }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); + expect(r.out.pending).toBeFalsy(); +}); + +test("[REQ-CFGBASE-5] Config-Pfad geloescht (Datei im Diff, im HEAD weg) zaehlt als Config-Aenderung -> config-unguarded", () => { + const repo = makeRepo({ CODEOWNERS: "/src/ @alice\n" }); + branchWith(repo, { ".devloop/bot-logins.json": null }); + const r = run(repo, { diffPaths: [".devloop/bot-logins.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-unguarded/); +}); + +test("[REQ-CFGBASE-5] T1, PR legt tools/tier-map.json an, Basis hat .devloop/tier-map.json -> Config-Aenderung (config-unguarded)", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { "tools/tier-map.json": JSON.stringify({ T1: ["**"] }) }); + const r = run(repo, { diffPaths: ["tools/tier-map.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-unguarded/); + expect(r.stdout).toContain("tools/tier-map.json"); +}); + +test("[REQ-CFGBASE-5] T1, PR legt tier-map.json im Root an -> Config-Aenderung (config-unguarded)", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { "tier-map.json": JSON.stringify({ T1: ["**"] }) }); + const r = run(repo, { diffPaths: ["tier-map.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-unguarded/); + expect(r.stdout).toContain("tier-map.json"); +}); + +test("[REQ-CFGBASE-5] T1, PR legt .devloop/spec-globs.json NEU an, Basis hat andere .devloop-Dateien -> config-unguarded ohne Deckung", () => { + const repo = makeRepo({ CODEOWNERS: "/src/ @alice\n" }); + branchWith(repo, { ".devloop/spec-globs.json": '["specs/**"]' }); + const r = run(repo, { diffPaths: [".devloop/spec-globs.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-unguarded/); + expect(r.stdout).toContain(".devloop/spec-globs.json"); +}); + +test("[REQ-CFGBASE-5] T1, PR legt .devloop/spec-globs.json NEU an, mit Deckung -> pending", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { ".devloop/spec-globs.json": '["specs/**"]' }); + const r = run(repo, { diffPaths: [".devloop/spec-globs.json"] }); + expect(r.status).toBe(0); + expect(r.out.pending).toBe(true); +}); + +test("[REQ-CFGBASE-6] Basis-CODEOWNERS ohne /.devloop/, HEAD-CODEOWNERS mit -> config-unguarded (CODEOWNERS aus der Basis)", () => { + const repo = makeRepo({ CODEOWNERS: "/src/ @alice\n" }); + branchWith(repo, { CODEOWNERS: "/src/ @alice\n/.devloop/ @mallory\n", ".devloop/protected-globs.json": "[]" }); + const r = run(repo, { diffPaths: ["CODEOWNERS", ".devloop/protected-globs.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-unguarded/); +}); + +test("[REQ-CFGBASE-6] Gegenprobe: Basis deckt /.devloop/, HEAD streicht die Deckung -> pending (Basis zaehlt)", () => { + const repo = makeRepo({ CODEOWNERS: COVER_CFG }); + branchWith(repo, { CODEOWNERS: "/src/ @alice\n", ".devloop/protected-globs.json": '["**/x"]' }); + const r = run(repo, { diffPaths: ["CODEOWNERS", ".devloop/protected-globs.json"] }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); + expect(r.out.pending).toBe(true); +}); + +// ---------- REQ-CFGBASE-4/5/6: Erstaufnahme und Hinzufuegen einzelner Dateien ---------- + +test("[REQ-CFGBASE-5][REQ-CFGBASE-6] Erstaufnahme: Basis ohne jeden Config-Pfad, PR legt Skeletons an -> kein config-unguarded, T1 ok", () => { + const repo = makeRepo({}, false); + branchWith(repo, { + ".devloop/tier-map.json": JSON.stringify({ T1: ["**"] }), + ".devloop/bot-logins.json": '["agent-bot"]', + ".devloop/protected-globs.json": "[]", + "src/a.ts": "x\n", + }); + const r = run(repo, { + diffPaths: [".devloop/tier-map.json", ".devloop/bot-logins.json", ".devloop/protected-globs.json", "src/a.ts"], + }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); + expect(r.stdout).not.toMatch(/config-unguarded/); +}); + +test("[REQ-CFGBASE-4] Erstaufnahme: Listen kommen aus dem HEAD-Arbeitsbaum (stryker-Glob im HEAD greift)", () => { + const repo = makeRepo({}, false); + branchWith(repo, { + ".devloop/bot-logins.json": '["agent-bot"]', + ".devloop/protected-globs.json": '["**/stryker.conf.*"]', + "stryker.conf.json": "{}", + }); + const r = run(repo, { diffPaths: [".devloop/protected-globs.json", ".devloop/bot-logins.json", "stryker.conf.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-4] Basis hat .devloop/, aber keine bot-logins.json; PR fuegt sie hinzu -> Liste aus HEAD, Config-Aenderung", () => { + const repo = makeRepo({ ".devloop/bot-logins.json": null, CODEOWNERS: "/src/ @alice\n" }); + branchWith(repo, { ".devloop/bot-logins.json": '["bot"]' }); + // ohne Deckung: Config-Aenderung + const unguarded = run(repo, { diffPaths: [".devloop/bot-logins.json"] }); + expect(unguarded.status).toBe(1); + expect(unguarded.out.reason).toMatch(/^config-unguarded/); + // mit Deckung (neuer Basis-Stand): HEAD-Liste ["bot"] gilt, Bot-Approval zaehlt nicht + const repo2 = makeRepo({ ".devloop/bot-logins.json": null, CODEOWNERS: COVER_CFG }); + branchWith(repo2, { ".devloop/bot-logins.json": '["bot"]' }); + const r = run(repo2, { + prAuthor: "someone", + diffPaths: [".devloop/bot-logins.json"], + reviews: [{ user: "bot", state: "APPROVED", commit_id: "abc123" }], + }); + expect(r.status).toBe(1); + expect(r.out.ok).toBe(false); + expect(r.out.reason).not.toMatch(/config-/); +}); + +// ---------- REQ-CFGBASE-7: ohne Config-Aenderung wie bisher ---------- + +test("[REQ-CFGBASE-7] T1, nur src/a.ts, keine Config-Pfade -> ok:true wie bisher (Bot-Approval egal)", () => { + const repo = makeRepo({ CODEOWNERS: "/src/ @alice\n" }); + const r = run(repo, { diffPaths: ["src/a.ts"], reviews: [{ user: "agent-bot", state: "APPROVED", commit_id: "abc123" }] }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); + expect(r.out.pending).toBeFalsy(); +}); + +test("[REQ-CFGBASE-7] T0, nur src/a.ts, ohne CODEOWNERS und ohne Reviews -> ok:true (kein config-unguarded)", () => { + const repo = makeRepo(); + const r = run(repo, { tier: "T0", diffPaths: ["src/a.ts"] }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); +}); + +test("[REQ-CFGBASE-7] aehnliche, aber keine Config-Pfade (src/tier-map.json, docs/.devloop-notes.md, tools/tier-map.json.bak) -> ok:true", () => { + const repo = makeRepo(); + const r = run(repo, { diffPaths: ["src/tier-map.json", "docs/.devloop-notes.md", "tools/tier-map.json.bak", "x.devloop/a"] }); + expect(r.status).toBe(0); + expect(r.out.ok).toBe(true); + expect(r.stdout).not.toMatch(/config-unguarded/); +}); + +test("[REQ-CFGBASE-7] T2 ohne Review bleibt pending, Gate-Tamper bleibt hart (mit Basis-Globs)", () => { + const repo = makeRepo(); + const pend = run(repo, { tier: "T2", diffPaths: ["src/a.ts"] }); + expect(pend.status).toBe(0); + expect(pend.out.pending).toBe(true); + const tamper = run(repo, { diffPaths: ["stryker.conf.json"] }); + expect(tamper.status).toBe(1); + expect(tamper.out.reason).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-7] Reihenfolge: Gate-Tamper vor Config-Gate", () => { + const repo = makeRepo(); + const r = run(repo, { diffPaths: ["stryker.conf.json", ".devloop/protected-globs.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-7] Reihenfolge: Spec-Gate (spec-unguarded) vor Config-Gate", () => { + const repo = makeRepo(); + const r = run(repo, { headRef: "devloop/spec/x", diffPaths: ["specs/x/spec.md", ".devloop/protected-globs.json"] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^spec-unguarded/); +}); + +// ---------- REQ-CFGBASE-3: Symlink in der Basis ist kein reguelaeres Blob ---------- + +function symlinkRepo(link: string, target: string, targetContent: string, extra: Record = {}): string { + const repo = makeRepo({ [link]: null, [target.replace("../", "")]: targetContent, ...extra }); + mkdirSync(dirname(join(repo, link)), { recursive: true }); + symlinkSync(target, join(repo, link)); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "symlink"); + return repo; +} + +test("[REQ-CFGBASE-3] Basis-protected-globs ist Symlink auf cfg/pg.json, PR leert das Ziel und aendert stryker.conf.json -> config-invalid", () => { + const repo = symlinkRepo(".devloop/protected-globs.json", "../cfg/pg.json", '["**/stryker.conf.*"]'); + branchWith(repo, { "cfg/pg.json": "[]", "stryker.conf.json": "{}" }); + const r = run(repo, { diffPaths: ["stryker.conf.json", "cfg/pg.json"], protectedGlobs: [] }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-bot-logins ist Symlink auf cfg/bl.json, PR leert das Ziel -> config-invalid", () => { + const repo = symlinkRepo(".devloop/bot-logins.json", "../cfg/bl.json", '["bot"]'); + branchWith(repo, { "cfg/bl.json": "[]" }); + const r = run(repo, { + tier: "T2", + prAuthor: "someone", + diffPaths: ["src/a.ts"], + botLogins: [], + reviews: [{ user: "bot", state: "APPROVED", commit_id: "abc123" }], + }); + expect(r.status).toBe(1); + expect(r.out.reason).toMatch(/^config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-tier-map ist ein Symlink -> derive-tier Exit != 0, kein Rueckfall auf den Arbeitsbaum", () => { + const repo = symlinkRepo(".devloop/tier-map.json", "../cfg/tm.json", JSON.stringify({ T3: ["src/**"] })); + branchWith(repo, { "cfg/tm.json": JSON.stringify({ T1: ["**"] }) }); + const r = derive(repo, { touched: ["src/a.ts"], baseRef: "base" }); + expect(r.status).not.toBe(0); + expect(r.status).not.toBeNull(); +}); diff --git a/test/cli/precondition-action-config.test.ts b/test/cli/precondition-action-config.test.ts new file mode 100644 index 0000000..682bd28 --- /dev/null +++ b/test/cli/precondition-action-config.test.ts @@ -0,0 +1,380 @@ +// [REQ-CFGBASE-*] Fuehrt die echten run:-Skripte der Precondition-Action aus (gh gestubbt), Setup bash + jq. +// Der Clone wird wie `actions/checkout` gebaut: detached auf der HEAD-SHA, KEIN lokaler `main`, +// nur `origin/main` (per "Fetch base"). Ein baseRef ohne `origin/` laeuft hier ins Leere (vgl. #17). +import { test, expect, afterEach } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, chmodSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { dirname, resolve, join } from "node:path"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const actionDir = join(root, ".github/actions/precondition-check"); +const actionYml = readFileSync(join(actionDir, "action.yml"), "utf8"); + +function stepRun(namePrefix: string): string { + const lines = actionYml.split("\n"); + const i = lines.findIndex((l) => l.trim().startsWith("- name: " + namePrefix)); + if (i < 0) throw new Error("step not found: " + namePrefix); + const r = lines.findIndex((l, k) => k > i && /^\s+run: \|\s*$/.test(l)); + if (r < 0) throw new Error("no block run: for step " + namePrefix); + const runIndent = lines[r].length - lines[r].trimStart().length; + const out: string[] = []; + for (let k = r + 1; k < lines.length; k++) { + const l = lines[k]; + const ind = l.length - l.trimStart().length; + if (l.trim() !== "" && ind <= runIndent) break; + out.push(l.slice(runIndent + 2)); + } + return out.join("\n"); +} + +const dirs: string[] = []; +afterEach(() => { + while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); +}); + +function sh(cwd: string, cmd: string, args: string[]): string { + const r = spawnSync(cmd, args, { cwd, encoding: "utf8" }); + if (r.status !== 0) throw new Error(`${cmd} ${args.join(" ")}: ${r.stderr}`); + return r.stdout; +} +const git = (cwd: string, ...a: string[]) => + sh(cwd, "git", ["-c", "commit.gpgsign=false", "-c", "core.quotepath=true", ...a]); + +function write(repo: string, rel: string, content: string): void { + const p = join(repo, rel); + mkdirSync(dirname(p), { recursive: true }); + writeFileSync(p, content); +} + +const T1_MAP = JSON.stringify({ T1: ["**"] }); +const CONFIG = { + ".devloop/tier-map.json": T1_MAP, + ".devloop/bot-logins.json": '["agent-bot"]', + ".devloop/protected-globs.json": "[]", +}; +const COVER = "/.devloop/ @alice\n"; + +// Basis auf origin/main; PR-Commit in einem Autoren-Clone, als refs/pull/1/head nach origin geschoben; +// CI-Clone: frisch, detached auf der HEAD-SHA, kein lokaler Branch. +function setup(opts: { + baseFiles: Record; // null = Standard-Eintrag aus CONFIG weglassen + withDefaults?: boolean; + change: (repo: string) => void; + author?: string; + baseHook?: (repo: string) => void; // z. B. Symlinks, vor dem Basis-Commit +}) { + const tmp = mkdtempSync(join(tmpdir(), "precond-action-cfg-")); + dirs.push(tmp); + const origin = join(tmp, "origin.git"); + const author = join(tmp, "author"); + const ci = join(tmp, "ci"); + mkdirSync(author); + mkdirSync(ci); + sh(tmp, "git", ["init", "-q", "--bare", "-b", "main", origin]); + git(author, "init", "-q", "-b", "main"); + git(author, "config", "user.name", "Test"); + git(author, "config", "user.email", "t@example.invalid"); + git(author, "remote", "add", "origin", origin); + write(author, "README.md", "x\n"); + const files = { ...(opts.withDefaults === false ? {} : CONFIG), ...opts.baseFiles }; + for (const [p, c] of Object.entries(files)) if (c !== null) write(author, p, c); + opts.baseHook?.(author); + git(author, "add", "-A"); + git(author, "commit", "-q", "-m", "base"); + git(author, "push", "-q", "origin", "main"); + git(author, "checkout", "-q", "-b", "feature/y"); + opts.change(author); + git(author, "add", "-A"); + git(author, "commit", "-q", "-m", "pr"); + const sha = git(author, "rev-parse", "HEAD").trim(); + git(author, "push", "-q", "origin", "HEAD:refs/pull/1/head"); + + // CI-Clone wie actions/checkout: fetch der PR-Ref, detached checkout, kein lokaler Branch. + git(ci, "init", "-q"); + git(ci, "config", "user.name", "Test"); + git(ci, "config", "user.email", "t@example.invalid"); + git(ci, "remote", "add", "origin", origin); + git(ci, "fetch", "-q", "--no-tags", "origin", "+refs/pull/1/head:refs/remotes/pull/1/head"); + git(ci, "checkout", "-q", "--detach", sha); + if (git(ci, "for-each-ref", "refs/heads").trim() !== "") throw new Error("setup: CI-Clone hat lokale Branches"); + if (git(ci, "rev-parse", "--abbrev-ref", "HEAD").trim() !== "HEAD") throw new Error("setup: HEAD nicht detached"); + + const bin = join(tmp, "bin"); + mkdirSync(bin); + const reviewsFile = join(tmp, "reviews.json"); + writeFileSync(reviewsFile, "[]"); + writeFileSync(join(bin, "gh"), `#!/bin/sh\ncat "${reviewsFile}"\n`); + chmodSync(join(bin, "gh"), 0o755); + return { work: ci, bin, sha, reviewsFile, author: opts.author ?? "agent-bot" }; +} + +type Setup = ReturnType; + +function runSteps(s: Setup, shellFlags: string[] = ["-eo", "pipefail"]) { + const env = { + PATH: `${s.bin}:${process.env.PATH}`, + HOME: process.env.HOME ?? "/tmp", + GITHUB_ACTION_PATH: actionDir, + BASE: "main", + HEAD_REF: "feature/y", + HEAD_SHA: s.sha, + AUTHOR: s.author, + PR: "1", + REPO: "o/r", + GH_TOKEN: "stub", + }; + const run = (script: string) => spawnSync("bash", ["--noprofile", "--norc", ...shellFlags, "-c", script], { cwd: s.work, env, encoding: "utf8" }); + const fetch = run(`git fetch origin "+refs/heads/$BASE:refs/remotes/origin/$BASE"`); + if (fetch.status !== 0) throw new Error("fetch: " + fetch.stderr); + const tier = run(stepRun("Compute the AUTHORITATIVE tier")); + let tierJson: any = {}; + try { + tierJson = JSON.parse(readFileSync(join(s.work, "tier.json"), "utf8")); + } catch { + /* Schritt fehlgeschlagen */ + } + const verify = tier.status === 0 ? run(stepRun("Verify HUMAN approval")) : undefined; + return { tier, tierJson, verify }; +} + +const lastJson = (out: string) => JSON.parse(out.trim().split("\n").pop()!); + +test("[REQ-CFGBASE-1] Clone wie actions/checkout: Basis-tier-map src/** -> T3, PR stuft in HEAD auf T1 herab und aendert src/a.ts -> Tier T3", () => { + const s = setup({ + baseFiles: { ".devloop/tier-map.json": JSON.stringify({ T3: ["src/**"], T1: ["**"] }), CODEOWNERS: COVER }, + change: (w) => { + write(w, ".devloop/tier-map.json", T1_MAP); + write(w, "src/a.ts", "x\n"); + }, + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.tierJson.tier).toBe("T3"); +}); + +test("[REQ-CFGBASE-1] Basis-tier-map nur unter tools/, HEAD legt .devloop/tier-map.json (T1) an -> Tier aus tools/ der Basis", () => { + const s = setup({ + baseFiles: { + ".devloop/tier-map.json": null, + "tools/tier-map.json": JSON.stringify({ T3: ["src/**"], T1: ["**"] }), + CODEOWNERS: COVER, + }, + change: (w) => { + write(w, ".devloop/tier-map.json", T1_MAP); + write(w, "src/a.ts", "x\n"); + }, + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.tierJson.tier).toBe("T3"); +}); + +test("[REQ-CFGBASE-3] Basis-tier-map = `{`, HEAD repariert sie -> Tier-Schritt rot (kein Rueckfall auf HEAD)", () => { + const s = setup({ + baseFiles: { ".devloop/tier-map.json": "{", CODEOWNERS: COVER }, + change: (w) => write(w, ".devloop/tier-map.json", T1_MAP), + }); + const r = runSteps(s); + expect(r.tier.status).not.toBe(0); +}); + +test("[REQ-CFGBASE-2] Basis-protected-globs mit stryker-Glob, PR leert die Liste und aendert stryker.conf.json -> Schritt rot, protected-set-touched", () => { + const s = setup({ + baseFiles: { ".devloop/protected-globs.json": '["**/stryker.conf.*"]', CODEOWNERS: COVER }, + change: (w) => { + write(w, ".devloop/protected-globs.json", "[]"); + write(w, "stryker.conf.json", "{}"); + }, + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/protected-set-touched/); +}); + +test("[REQ-CFGBASE-2] Basis-bot-logins [\"bot\"], PR leert die Liste, Approval von bot auf HEAD, T2 -> Schritt rot", () => { + const s = setup({ + baseFiles: { + ".devloop/bot-logins.json": '["bot"]', + ".devloop/tier-map.json": JSON.stringify({ T2: ["src/**"], T1: ["**"] }), + CODEOWNERS: COVER, + }, + author: "someone", + change: (w) => { + write(w, ".devloop/bot-logins.json", "[]"); + write(w, "src/a.ts", "x\n"); + }, + }); + writeFileSync(s.reviewsFile, JSON.stringify([{ user: "bot", state: "APPROVED", commit_id: s.sha }])); + const r = runSteps(s); + expect(r.tierJson.tier).toBe("T2"); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/human-approval/); +}); + +test("[REQ-CFGBASE-3] Basis-protected-globs = `{`, HEAD repariert sie -> Schritt rot, config-invalid (kein Rueckfall auf HEAD)", () => { + const s = setup({ + baseFiles: { ".devloop/protected-globs.json": "{", CODEOWNERS: COVER }, + change: (w) => write(w, ".devloop/protected-globs.json", "[]"), + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-bot-logins = `{`, HEAD repariert sie -> Schritt rot, config-invalid", () => { + const s = setup({ + baseFiles: { ".devloop/bot-logins.json": "{", CODEOWNERS: COVER }, + change: (w) => write(w, ".devloop/bot-logins.json", '["agent-bot"]'), + }); + const r = runSteps(s); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/config-invalid/); +}); + +test("[REQ-CFGBASE-4] protected-globs fehlt in Basis und HEAD -> Schritt rot, config-missing (kein cat mehr, kein stiller Default)", () => { + const s = setup({ + baseFiles: { ".devloop/protected-globs.json": null, CODEOWNERS: COVER }, + change: (w) => write(w, "src/a.ts", "x\n"), + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/config-missing/); +}); + +test("[REQ-CFGBASE-4] Basis hat .devloop/, aber keine bot-logins.json; PR fuegt [\"bot\"] hinzu -> Liste aus HEAD (Bot-Approval zaehlt nicht), kein config-missing", () => { + const s = setup({ + baseFiles: { + ".devloop/bot-logins.json": null, + ".devloop/tier-map.json": JSON.stringify({ T2: ["src/**"], T1: ["**"] }), + CODEOWNERS: COVER, + }, + author: "someone", + change: (w) => { + write(w, ".devloop/bot-logins.json", '["bot"]'); + write(w, "src/a.ts", "x\n"); + }, + }); + writeFileSync(s.reviewsFile, JSON.stringify([{ user: "bot", state: "APPROVED", commit_id: s.sha }])); + const r = runSteps(s); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/human-approval/); + expect(r.verify!.stdout).not.toMatch(/config-missing/); +}); + +test("[REQ-CFGBASE-5][REQ-CFGBASE-6] T1, PR aendert nur .devloop/protected-globs.json, Basis-CODEOWNERS ohne /.devloop/ -> Schritt rot, config-unguarded", () => { + const s = setup({ + baseFiles: { CODEOWNERS: "/src/ @alice\n" }, + change: (w) => write(w, ".devloop/protected-globs.json", '["**/x"]'), + }); + const r = runSteps(s); + expect(r.tierJson.tier).toBe("T1"); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/config-unguarded/); +}); + +test("[REQ-CFGBASE-5] dto. mit Deckung in der Basis, keine Reviews -> Schritt gruen, pending:true", () => { + const s = setup({ + baseFiles: { CODEOWNERS: COVER }, + change: (w) => write(w, ".devloop/protected-globs.json", '["**/x"]'), + }); + const r = runSteps(s); + expect(r.verify!.status).toBe(0); + expect(lastJson(r.verify!.stdout).pending).toBe(true); +}); + +test("[REQ-CFGBASE-5][REQ-CFGBASE-6] Erstaufnahme: Basis ohne jeden Config-Pfad, PR legt Skeletons an -> Tier aus HEAD-tier-map, Schritt gruen, kein config-unguarded", () => { + const s = setup({ + baseFiles: {}, + withDefaults: false, + change: (w) => { + for (const [p, c] of Object.entries(CONFIG)) write(w, p, c); + write(w, "src/a.ts", "x\n"); + }, + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.tierJson.tier).toBe("T1"); + expect(r.verify!.status).toBe(0); + expect(r.verify!.stdout).not.toMatch(/config-unguarded/); + expect(lastJson(r.verify!.stdout).ok).toBe(true); +}); + +test("[REQ-CFGBASE-7] Gegenprobe: normaler PR (nur src/a.ts, T1, Basis mit Config) -> Schritt gruen, ok:true", () => { + const s = setup({ + baseFiles: { CODEOWNERS: "/src/ @alice\n" }, + change: (w) => write(w, "src/a.ts", "x\n"), + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.tierJson.tier).toBe("T1"); + expect(r.verify!.status).toBe(0); + expect(lastJson(r.verify!.stdout).ok).toBe(true); +}); + +// Symlink in der Basis: ls-tree-Modus 120000 ist kein reguelaeres Blob. Der PR repariert/leert das Ziel im HEAD. +function linkInBase(link: string, target: string) { + return (repo: string) => { + mkdirSync(dirname(join(repo, link)), { recursive: true }); + symlinkSync(target, join(repo, link)); + }; +} + +test("[REQ-CFGBASE-3] Basis-protected-globs ist ein Symlink auf cfg/pg.json, PR leert cfg/pg.json und aendert stryker.conf.json -> Schritt rot, config-invalid", () => { + const s = setup({ + baseFiles: { ".devloop/protected-globs.json": null, "cfg/pg.json": '["**/stryker.conf.*"]', CODEOWNERS: COVER }, + baseHook: linkInBase(".devloop/protected-globs.json", "../cfg/pg.json"), + change: (w) => { + write(w, "cfg/pg.json", "[]"); + write(w, "stryker.conf.json", "{}"); + }, + }); + const r = runSteps(s); + expect(r.tier.status).toBe(0); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-bot-logins ist ein Symlink, PR leert das Ziel, Bot-Approval auf HEAD -> Schritt rot, config-invalid", () => { + const s = setup({ + baseFiles: { + ".devloop/bot-logins.json": null, + "cfg/bl.json": '["bot"]', + ".devloop/tier-map.json": JSON.stringify({ T2: ["src/**"], T1: ["**"] }), + CODEOWNERS: COVER, + }, + baseHook: linkInBase(".devloop/bot-logins.json", "../cfg/bl.json"), + author: "someone", + change: (w) => { + write(w, "cfg/bl.json", "[]"); + write(w, "src/a.ts", "x\n"); + }, + }); + writeFileSync(s.reviewsFile, JSON.stringify([{ user: "bot", state: "APPROVED", commit_id: s.sha }])); + const r = runSteps(s); + expect(r.verify!.status).toBe(1); + expect(r.verify!.stdout).toMatch(/config-invalid/); +}); + +test("[REQ-CFGBASE-3] Basis-tier-map ist ein Symlink, HEAD hat gueltige Datei am Ziel -> Tier-Schritt rot", () => { + const s = setup({ + baseFiles: { ".devloop/tier-map.json": null, "cfg/tm.json": "{", CODEOWNERS: COVER }, + baseHook: linkInBase(".devloop/tier-map.json", "../cfg/tm.json"), + change: (w) => write(w, "cfg/tm.json", T1_MAP), + }); + const r = runSteps(s); + expect(r.tier.status).not.toBe(0); +}); + +test("[REQ-CFGBASE-3] Tier-Schritt ohne -e (nur -o pipefail) mit kaputter Basis-tier-map -> rc != 0 (|| exit 1 im Block)", () => { + const s = setup({ + baseFiles: { ".devloop/tier-map.json": "{", CODEOWNERS: COVER }, + change: (w) => write(w, ".devloop/tier-map.json", T1_MAP), + }); + const r = runSteps(s, ["-o", "pipefail"]); + expect(r.tier.status).not.toBe(0); +}); diff --git a/test/cli/precondition-action.test.ts b/test/cli/precondition-action.test.ts index 9c958be..8e7811f 100644 --- a/test/cli/precondition-action.test.ts +++ b/test/cli/precondition-action.test.ts @@ -93,7 +93,7 @@ function runSteps(s: ReturnType) { REPO: "o/r", GH_TOKEN: "stub", }; - const run = (script: string) => spawnSync("bash", ["-c", script], { cwd: s.work, env, encoding: "utf8" }); + const run = (script: string) => spawnSync("bash", ["--noprofile", "--norc", "-eo", "pipefail", "-c", script], { cwd: s.work, env, encoding: "utf8" }); const fetch = run(`git fetch origin "+refs/heads/$BASE:refs/remotes/origin/$BASE"`); if (fetch.status !== 0) throw new Error("fetch: " + fetch.stderr); const tier = run(stepRun("Compute the AUTHORITATIVE tier")); diff --git a/test/cli/verify-review-spec.test.ts b/test/cli/verify-review-spec.test.ts index 969dc0c..3425412 100644 --- a/test/cli/verify-review-spec.test.ts +++ b/test/cli/verify-review-spec.test.ts @@ -40,7 +40,8 @@ function makeRepo(files: Record = {}): string { const COVER_SPECS = "/specs/ @alice\n"; -const baseReq = { prAuthor: "agent-bot", headSha: "abc123", botLogins: ["agent-bot"], tier: "T0", baseRef: "base" }; +// protectedGlobs: ab #13 verlangt verify-review mit baseRef eine Quelle (Basis, Arbeitsbaum oder stdin), sonst config-missing. +const baseReq = { prAuthor: "agent-bot", headSha: "abc123", botLogins: ["agent-bot"], protectedGlobs: [] as string[], tier: "T0", baseRef: "base" }; function run(repo: string, req: object) { const r = spawnSync("node", [cli], { diff --git a/test/core/init-config-codeowners.test.ts b/test/core/init-config-codeowners.test.ts new file mode 100644 index 0000000..8b3451c --- /dev/null +++ b/test/core/init-config-codeowners.test.ts @@ -0,0 +1,75 @@ +// [REQ-CFGBASE-8] init deckt /.devloop/ in der CODEOWNERS ab bzw. meldet die Luecke. +import { test, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, rmSync, readFileSync, mkdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { initRepo } from "../../src/core/init.js"; + +const TEMPLATE = "name: devloop-precondition-check\n# ...\n"; + +let repo: string; +beforeEach(() => { + repo = mkdtempSync(join(tmpdir(), "devloop-init-cfg-")); +}); +afterEach(() => rmSync(repo, { recursive: true, force: true })); + +const lines = (s: string) => s.split("\n").map((l) => l.trim()); + +test("[REQ-CFGBASE-8] init ohne CODEOWNERS: angelegte Datei enthaelt /.devloop/ mit Platzhalter-Owner", () => { + initRepo(repo, TEMPLATE); + const co = readFileSync(join(repo, ".github/CODEOWNERS"), "utf8"); + expect(lines(co)).toContain("/.devloop/ @OWNER"); +}); + +test("[REQ-CFGBASE-8] init ohne CODEOWNERS, tier-map unter tools/: /tools/tier-map.json und /.devloop/ eingetragen", () => { + mkdirSync(join(repo, "tools"), { recursive: true }); + writeFileSync(join(repo, "tools/tier-map.json"), JSON.stringify({ T3: ["services/**"], T1: ["**"] })); + initRepo(repo, TEMPLATE); + const co = lines(readFileSync(join(repo, ".github/CODEOWNERS"), "utf8")); + expect(co).toContain("/.devloop/ @OWNER"); + expect(co).toContain("/tools/tier-map.json @OWNER"); +}); + +test("[REQ-CFGBASE-8] init mit CODEOWNERS ohne /.devloop/: Datei unveraendert, Hinweis in notes nennt .devloop", () => { + mkdirSync(join(repo, ".github"), { recursive: true }); + writeFileSync(join(repo, ".github/CODEOWNERS"), "/docs/ @writer\n"); + const r = initRepo(repo, TEMPLATE); + expect(readFileSync(join(repo, ".github/CODEOWNERS"), "utf8")).toBe("/docs/ @writer\n"); + expect(r.notes.some((n) => /CODEOWNERS/.test(n) && /\.devloop\//.test(n) && /not cover|deck|uncovered/i.test(n))).toBe(true); +}); + +test("[REQ-CFGBASE-8] Gegenprobe: CODEOWNERS deckt /.devloop/ bereits -> kein Hinweis zu .devloop in den CODEOWNERS-notes", () => { + mkdirSync(join(repo, ".github"), { recursive: true }); + writeFileSync(join(repo, ".github/CODEOWNERS"), "/.devloop/ @writer\n"); + const r = initRepo(repo, TEMPLATE); + expect(r.notes.some((n) => /CODEOWNERS/.test(n) && /\.devloop\/?(\s|,|\)|$)/.test(n) && !/managed-tests/.test(n))).toBe(false); +}); + +test("[REQ-CFGBASE-8] init mit CODEOWNERS ohne Deckung der tier-map unter tools/: Hinweis nennt tools/tier-map.json", () => { + mkdirSync(join(repo, "tools"), { recursive: true }); + writeFileSync(join(repo, "tools/tier-map.json"), JSON.stringify({ T1: ["**"] })); + mkdirSync(join(repo, ".github"), { recursive: true }); + writeFileSync(join(repo, ".github/CODEOWNERS"), "/.devloop/ @writer\n"); + const r = initRepo(repo, TEMPLATE); + expect(r.notes.some((n) => /CODEOWNERS/.test(n) && /tools\/tier-map\.json/.test(n))).toBe(true); +}); + +// Schraegstrich am Ende (Tab-Vervollstaendigung): kein absoluter Pfad in der CODEOWNERS. +test("[REQ-CFGBASE-8] init mit Schraegstrich am Ende, ohne tier-map: keine Zeile mit absolutem Pfad", () => { + initRepo(repo + "/", TEMPLATE); + const text = readFileSync(join(repo, ".github/CODEOWNERS"), "utf8"); + expect(text).not.toContain(repo); + expect(text).not.toMatch(/^\/\//m); + expect(lines(text)).toContain("/.devloop/ @OWNER"); +}); + +test("[REQ-CFGBASE-8] init mit Schraegstrich am Ende, tier-map unter tools/: /tools/tier-map.json @OWNER, kein absoluter Pfad", () => { + mkdirSync(join(repo, "tools"), { recursive: true }); + writeFileSync(join(repo, "tools/tier-map.json"), JSON.stringify({ T3: ["services/**"], T1: ["**"] })); + const r = initRepo(repo + "/", TEMPLATE); + const text = readFileSync(join(repo, ".github/CODEOWNERS"), "utf8"); + expect(text).not.toContain(repo); + expect(text).not.toMatch(/^\/\//m); + expect(lines(text)).toContain("/tools/tier-map.json @OWNER"); + expect(r.notes.join("\n")).not.toContain(repo); +});