diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index be5b75f..706f389 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.16.0", + "version": "0.17.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/USAGE.md b/USAGE.md index 6bbdfff..0e1fc5c 100644 --- a/USAGE.md +++ b/USAGE.md @@ -110,7 +110,11 @@ Danach **von Hand** (das ist der Anker, der Selbst-Freigabe verhindert): > ohne REQ-Tag und `.only`/`.todo`/`xit` bleiben verboten. So ist der grüne Pfad Wächter-Wissen, > nicht Folklore (`describe.skip` um aktive `it` trifft **beide** Wächter und ist tabu). 8. **`verify-unskip`** als Required Check auf dem Implementierungs-PR wiren (im CI-Template enthalten) — - erzwingt, dass `implement` an Tests nur `.skip` entfernt. + erzwingt, dass `implement` an Tests nur `.skip` entfernt. **Neue verwaltete Testdateien** kommen nur + über den Spec-PR (`devloop/spec/*`); im Impl-PR sind sie eine Verletzung, unabhängig vom Inhalt. + **Symlinks** (jeder geänderte Pfad, nicht nur Testnamen) müssen auf eine **reguläre Datei im + Repo** zeigen — Verzeichnis-Links, fehlende oder externe Ziele, Wurzel und Link-Ketten sind + Verletzungen (vitest folgt Verzeichnis-Links in Bäume, die nie committet oder geprüft wurden). > **Umfang setzen (sonst Fehlalarm):** Die Naht gilt für die Pfade in > `.devloop/managed-tests.json`. Steht dort das Skeleton `["**"]`, gilt sie für **jede** > Testdatei im Repo — dann kann auch ein PR, der mit devloop nichts zu tun hat (ein diff --git a/agents/devloop-implement.md b/agents/devloop-implement.md index e6a7961..d4a6331 100644 --- a/agents/devloop-implement.md +++ b/agents/devloop-implement.md @@ -11,7 +11,7 @@ Du implementierst gegen **vorgegebene** `spec.md` + Tests. Du bist der Produzent ## Vorgabe (nicht verhandelbar) - `spec.md` + die Tests liegen schon **auf `main`** (über den gereviewten Spec-PR). Du baust darauf auf. -- **Die einzige erlaubte Änderung an `*.test.*`-Dateien ist das Entfernen von `.skip`.** Niemals Assertions, Testtitel, Test-Struktur ändern, Tests hinzufügen/löschen, oder irgendwo ein `.skip` *hinzufügen* (ein Test heimlich stilllegen). Das ist die Naht der Test↔Code-Gewaltenteilung (§11 #3) und wird **maschinell geprüft** (`verify-unskip` als CI-Required-Check) — ein Diff, der mehr als `.skip` entfernt, ist rot. +- **Die einzige erlaubte Änderung an `*.test.*`-Dateien ist das Entfernen von `.skip`.** Niemals Assertions, Testtitel, Test-Struktur ändern, Tests hinzufügen/löschen, oder irgendwo ein `.skip` *hinzufügen* (ein Test heimlich stilllegen). Das ist die Naht der Test↔Code-Gewaltenteilung (§11 #3) und wird **maschinell geprüft** (`verify-unskip` als CI-Required-Check) — ein Diff, der mehr als `.skip` entfernt, ist rot. **Lege keine neue Testdatei an** (neue verwaltete Tests gibt es nur über den Spec-PR; im Impl-PR ist schon die Existenz eine Verletzung, egal wie der Test aussieht) und **keine Symlinks** außer auf reguläre Dateien im Repo (nie auf Verzeichnisse, nie nach außen). - Den **geschützten Satz** (CI-Config, Thresholds, Semgrep-Regeln, `constitution.md`) änderst du **nie**. Ein „Fix", der das Gate statt den Code anfasst, ist Reward-Hacking-Alarm (§5#3), kein Fortschritt. ## Auftrag (innere Schleife — Sandbox, Tempo) diff --git a/agents/devloop-spec-to-tests.md b/agents/devloop-spec-to-tests.md index d5feaaa..8ced5dc 100644 --- a/agents/devloop-spec-to-tests.md +++ b/agents/devloop-spec-to-tests.md @@ -35,7 +35,7 @@ node "${CLAUDE_PLUGIN_ROOT}"/dist/cli/req-delta.js # { - **added** → neuen Test, `.skip`'t (wie oben). - **changed** → den bestehenden Test (gleiche `REQ-`-ID) ändern **und `.skip` wieder setzen**. Sonst rötet der jetzt-aktive Test gegen den (noch alten) Code `main` beim Spec-PR-Merge. `implement` entskippt ihn später, nachdem der Code nachgezogen ist. - **removed** → den Test entfernen (sonst rote verwaiste `REQ-`-Referenz im Trace-Gate). -Unveränderte Tests **nicht** anfassen (sie bleiben aktiv und grün). Das läuft alles auf dem **Spec-PR** (`devloop/spec/`); dort darfst du Tests autoren/ändern/re-skippen — `verify-unskip` greift dort nicht. +Unveränderte Tests **nicht** anfassen (sie bleiben aktiv und grün). Das läuft alles auf dem **Spec-PR** (`devloop/spec/`); dort darfst du Tests autoren/ändern/re-skippen — `verify-unskip` greift dort nicht. Neue Testdateien entstehen **nur hier**: im Impl-PR sind neue verwaltete Tests eine Verletzung. Lege keine Symlinks auf Verzeichnisse an (Symlinks nur auf reguläre Dateien im Repo). ## Grenzen diff --git a/dist/cli/verify-unskip.js b/dist/cli/verify-unskip.js index 0266c87..a8a5baa 100644 --- a/dist/cli/verify-unskip.js +++ b/dist/cli/verify-unskip.js @@ -1,7 +1,10 @@ // CLI: the unskip CI guard (Obol pilot §3.2/§4). Runs on EVERY PR (spec PR + implement PR): -// - a NEW test file may be authored only if every test in it is `.skip`'d (spec PR); -// - an EXISTING test file may change ONLY by removing `.skip` (implement PR). -// implement can thus neither author active tests nor edit existing ones. Fail-closed (exit 1). +// - a NEW managed test file is a violation outside `devloop/spec/*` (#21: new tests come only +// through a spec PR; the content is never judged); +// - an EXISTING test file may change ONLY by removing `.skip` (implement PR); +// - every changed symlink must resolve to a regular file inside the repo (#25). +// implement can thus neither add test files nor edit existing ones. Not covered: test() calls in a +// non-test module that a test imports (limit, issue #41). Fail-closed (exit 1). // // 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 @@ -11,11 +14,10 @@ // Deliberately NOT branch-name-driven: an agent chooses its own branch name. // // Usage: verify-unskip [headBranch] (baseRef e.g. origin/main) -import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { isAllowedTestEdit, isSpecBranch } from "../core/unskip.js"; -import { parseNulPaths } from "../core/diff-paths.js"; +import { checkSymlinks, rawDiff, SymlinkReadError } from "../core/symlinks.js"; import { readTreeEntry, TreeEntryReadError } from "../core/tree-entry.js"; import { MANAGED_TESTS_PATH, isManagedTestPath, parseManagedTestGlobs, } from "../core/managed-tests.js"; const repo = process.argv[2] ?? "."; @@ -65,22 +67,19 @@ const fromWorktree = cfg.kind === "missing" ? readWorktree(MANAGED_TESTS_PATH) : const managedRaw = cfg.kind === "file" ? fromBase : fromWorktree; const managedSource = cfg.kind === "file" ? "base" : fromWorktree !== "" ? "worktree" : "default"; const managedGlobs = parseManagedTestGlobs(managedRaw); -// The changed paths: NUL-separated (-z: no quoting of non-ASCII/special characters) and without -// rename detection (a rename shows BOTH the old and the new path, so the old one is judged as a -// deletion). Unlike `git show` of an absent file, a failing diff (unresolvable base, ...) is NOT -// "no test files": it fails closed with exit 1. -const changedPaths = () => { +// The changed entries: NUL-separated (-z: no quoting) and without rename detection (a rename shows +// BOTH the old and the new path, so the old one is judged as a deletion). A failing diff +// (unresolvable base, ...) is NOT "no test files": it fails closed with exit 1. +const diffEntries = () => { try { - const raw = execFileSync("git", ["-C", repo, "diff", "--no-renames", "-z", "--name-only", `${base}...HEAD`], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 }); - return parseNulPaths(raw); + return rawDiff(repo, base); } catch (e) { - const detail = String(e.stderr ?? e.message ?? e).trim(); - process.stderr.write(`verify-unskip: cannot compute the changed paths against base "${base}" (git diff failed): ${detail}\n`); - process.exit(1); + return fail(`cannot compute the changed paths against base "${base}" (git diff failed): ${e.message}`); } }; -const testFiles = changedPaths().filter((f) => TEST_FILE.test(f)); +const entries = diffEntries(); +const testFiles = entries.map((e) => e.path).filter((f) => TEST_FILE.test(f)); const changed = testFiles.filter((f) => isManagedTestPath(f, managedGlobs)); const unmanaged = testFiles.filter((f) => !isManagedTestPath(f, managedGlobs)); const violations = []; @@ -112,19 +111,40 @@ for (const file of changed) { }); continue; } + if (oldEntry.kind === "missing") { + // REQ-NEWTEST-1: a new managed test file is judged by its existence, never its content. + violations.push({ + file, + reason: "new managed test file outside a spec PR; new managed tests come only through a spec PR (devloop/spec/*)", + }); + continue; + } const oldContent = contentOf(oldEntry); // "" if the file is new const newContent = contentOf(newEntry); if (!isAllowedTestEdit(oldContent, newContent)) { violations.push({ file, - reason: oldContent === "" - ? "new test file contains an active (non-.skip) test (spec-PR tests must be skipped)" - : newContent === "" - ? "existing test file deleted or emptied (also when renamed away; implement must not remove tests)" - : "existing test file changed beyond removing `.skip` (implement must not edit tests)", + reason: newContent === "" + ? "existing test file deleted or emptied (also when renamed away; implement must not remove tests)" + : "existing test file changed beyond removing `.skip` (implement must not edit tests)", }); } } +// REQ-SYMLINK-*: every changed path whose HEAD entry is a symlink, independent of name and scope. +let symlinks = []; +try { + const r = checkSymlinks(repo, entries); + symlinks = r.symlinks; + // One violation per file: type (UNSKIPCONTENT-4) > NEWTEST-1 > SYMLINK-1. + const seen = new Set(violations.map((v) => v.file)); + violations.push(...r.violations.filter((v) => !seen.has(v.file))); +} +catch (e) { + if (!(e instanceof SymlinkReadError)) + throw e; + const links = entries.filter((x) => x.newMode === "120000").map((x) => x.path); + fail(`cannot read symlink entries/targets @ ${base}...HEAD (symlinks: ${links.join(", ")}): ${e.message}`); +} const ok = violations.length === 0; process.stdout.write(JSON.stringify({ ok, @@ -134,6 +154,7 @@ process.stdout.write(JSON.stringify({ managedSource, checked: changed, unmanaged, + symlinks, violations, }, null, 2) + "\n"); process.exit(ok ? 0 : 1); diff --git a/dist/core/symlinks.js b/dist/core/symlinks.js new file mode 100644 index 0000000..327f528 --- /dev/null +++ b/dist/core/symlinks.js @@ -0,0 +1,121 @@ +// Symlink rule of the unskip seam (#25): every symlink a PR creates or re-points must resolve to a +// REGULAR FILE inside the repo (in HEAD). vitest follows directory links into trees that are never +// committed (node_modules) or never run by default (cypress), so the link path alone decides nothing. +import { execFileSync } from "node:child_process"; +import { posix } from "node:path"; +export class SymlinkReadError extends Error { +} +const run = (repo, args, input, maxBuffer = 256 * 1024 * 1024) => { + try { + return execFileSync("git", ["-C", repo, "--literal-pathspecs", ...args], { + stdio: ["pipe", "pipe", "pipe"], + input, + maxBuffer, + }); + } + catch (e) { + const err = e; + throw new SymlinkReadError(String(err.stderr ?? "").trim() || err.message || String(e)); + } +}; +/** `git diff --raw -z --no-renames --no-abbrev`: ":om nm oo no S\0path\0" records. */ +export function parseRawDiff(raw) { + const parts = raw.split("\0"); + const out = []; + for (let i = 0; i + 1 < parts.length; i += 2) { + const m = /^:(\d+) (\d+) ([0-9a-f]+) ([0-9a-f]+) (\w)$/.exec(parts[i]); + if (!m) { + if (parts[i] === "") + break; + throw new SymlinkReadError(`unparsable diff record ${JSON.stringify(parts[i])}`); + } + out.push({ path: parts[i + 1], newMode: m[2], newOid: m[4] }); + } + return out; +} +export const rawDiff = (repo, base) => parseRawDiff(run(repo, ["diff", "--raw", "-z", "--no-renames", "--no-abbrev", `${base}...HEAD`]).toString("utf8")); +/** Link target -> repo-relative resolved path, or null if absolute / escaping / root / empty. */ +export function resolveLinkTarget(linkPath, target) { + if (target === "" || target.startsWith("/") || target.endsWith("/") || target.includes("\0")) + return null; + const resolved = posix.normalize(posix.join(posix.dirname(linkPath), target)); + if (resolved === "." || resolved === ".." || resolved.startsWith("../") || resolved.startsWith("/")) { + return null; + } + return resolved; +} +/** Contents of the given blobs (one `cat-file --batch` call). */ +export function readBlobs(repo, oids) { + const res = new Map(); + if (oids.length === 0) + return res; + const buf = run(repo, ["cat-file", "--batch"], oids.join("\n") + "\n", 1024 * 1024 * 1024); + let pos = 0; + for (const oid of oids) { + const nl = buf.indexOf(10, pos); + const header = nl < 0 ? "" : buf.subarray(pos, nl).toString("utf8"); + const m = /^([0-9a-f]+) (\w+) (\d+)$/.exec(header); + if (!m || m[2] !== "blob") + throw new SymlinkReadError(`cannot read blob ${oid} (${header || "no output"})`); + const size = Number(m[3]); + res.set(oid, buf.subarray(nl + 1, nl + 1 + size).toString("utf8")); + pos = nl + 1 + size + 1; + } + return res; +} +/** HEAD entries (mode) of the given exact paths; absent paths are not in the map. One call per chunk. */ +export function headModes(repo, paths) { + const res = new Map(); + for (let i = 0; i < paths.length; i += 500) { + const chunk = paths.slice(i, i + 500); + const raw = run(repo, ["ls-tree", "-z", "HEAD", "--", ...chunk]).toString("utf8"); + for (const rec of raw.split("\0").filter((r) => r !== "")) { + const m = /^(\d+) (\w+) ([0-9a-f]+)\t([\s\S]*)$/.exec(rec); + if (!m) + throw new SymlinkReadError("unparsable ls-tree record"); + res.set(m[4], { mode: m[1], oid: m[3] }); + } + } + return res; +} +export function checkSymlinks(repo, entries) { + const links = entries.filter((e) => e.newMode === "120000"); + const blobs = readBlobs(repo, [...new Set(links.map((l) => l.newOid))]); + const infos = links.map((l) => { + const target = blobs.get(l.newOid); + return { file: l.path, target, resolved: resolveLinkTarget(l.path, target) }; + }); + const modes = headModes(repo, [...new Set(infos.flatMap((i) => (i.resolved === null ? [] : [i.resolved])))]); + // A regular-file target whose blob cannot be read is a read error, never "fine". + const targetOids = [...new Set([...modes.values()].filter((e) => e.mode === "100644" || e.mode === "100755").map((e) => e.oid))]; + if (targetOids.length > 0) { + const out = run(repo, ["cat-file", "--batch-check"], targetOids.join("\n") + "\n").toString("utf8"); + const lines = out.split("\n").filter((l) => l !== ""); + if (lines.length !== targetOids.length || lines.some((l) => !/^[0-9a-f]+ blob \d+$/.test(l))) { + throw new SymlinkReadError(`a symlink target blob cannot be read (${lines.find((l) => !/^[0-9a-f]+ blob \d+$/.test(l)) ?? "short output"})`); + } + } + const violations = []; + for (const i of infos) { + const t = i.target; + let why = null; + if (i.resolved === null) { + why = `outside the repo, absolute, the repo root or empty`; + } + else { + const e = modes.get(i.resolved); + if (!e) + why = `missing in HEAD (${i.resolved})`; + else if (e.mode !== "100644" && e.mode !== "100755") { + why = `not a regular file in HEAD (${i.resolved}: ${e.mode === "040000" ? "directory" : e.mode === "120000" ? "symlink" : e.mode === "160000" ? "submodule" : e.mode})`; + } + } + if (why !== null) { + violations.push({ + file: i.file, + reason: `symlink ${i.file} -> ${t}: target ${why}; a symlink must resolve to a regular file inside the repo`, + }); + } + } + return { symlinks: infos.map((i) => ({ file: i.file, target: i.target })), violations }; +} diff --git a/dist/core/unskip.js b/dist/core/unskip.js index f143b79..1115949 100644 --- a/dist/core/unskip.js +++ b/dist/core/unskip.js @@ -12,26 +12,10 @@ const SKIP = ".skip"; const isWordChar = (c) => c !== undefined && /\w/.test(c); // A `.skip` token only counts at a word boundary (so `.skipped` is not treated as `.skip`). const skipAt = (s, i) => s.startsWith(SKIP, i) && !isWordChar(s[i + SKIP.length]); -// Does the source contain an ACTIVE (non-skipped) test call? Matches `it`/`test` with any -// chained props (e.g. .only/.each/.skip) before the call paren; active unless the chain has -// `.skip`. `describe(` is a container, not a test, so it is ignored. -const TEST_CALL = /\b(?:it|test)((?:\.\w+)*)\s*\(/g; -export function hasActiveTest(content) { - for (const m of content.matchAll(TEST_CALL)) { - if (!/\.skip\b/.test(m[1])) - return true; - } - return false; -} -// Unified rule for the precondition-check (runs on BOTH the spec PR and the implement PR): -// - NEW test file (old empty): authoring is allowed — but every test must be `.skip`'d, so -// nothing secretly-active lands on a green main (spec-PR authoring by spec-to-tests). -// - EXISTING test file: only `.skip` removal is allowed (implement PR). -// Safe on both: implement cannot smuggle an active test via a new file (would have to be all -// `.skip`'d = inert), nor edit assertions of existing files. +// Unified rule for the precondition-check on the implement PR: an EXISTING test file may change +// only by removing `.skip`. NEW managed test files are not judged by content at all — the CLI +// rejects them outright (they come only through a spec PR, #21). export function isAllowedTestEdit(oldContent, newContent) { - if (oldContent === "") - return !hasActiveTest(newContent); return isUnskipOnly(oldContent, newContent); } export function isUnskipOnly(oldContent, newContent) { diff --git a/docs/2026-11-28-verify-unskip-neue-tests-symlinks-design.md b/docs/2026-11-28-verify-unskip-neue-tests-symlinks-design.md new file mode 100644 index 0000000..d54dbdc --- /dev/null +++ b/docs/2026-11-28-verify-unskip-neue-tests-symlinks-design.md @@ -0,0 +1,186 @@ +# verify-unskip: keine neuen verwalteten Tests im Impl-PR, keine Symlinks auf Verzeichnisse — Design + +> devloop, Issues #21 und #25. Die Unskip-Naht prüft neue Testdateien an der Form ihres Inhalts +> (Regex) und sieht nur Pfade mit Testnamen. Beides lässt aktive Tests durch, die vitest ausführt. +> Status: **abgenommen** (2026-11-28). + +## Ist-Zustand (main, f1f5e84 — v0.16.0) + +- `src/core/unskip.ts`: `isAllowedTestEdit(old, new)`. Für eine **neue** Datei (`old === ""`) ist + sie erlaubt, wenn `hasActiveTest(new)` falsch ist. `hasActiveTest` sucht per Regex + `\b(?:it|test)((?:\.\w+)*)\s*\(` nach einem Aufruf ohne `.skip`. Für eine **bestehende** Datei + gilt `isUnskipOnly`, ein zeichengenauer Abgleich, der nur gelöschte `.skip` zulässt. +- `src/cli/verify-unskip.ts`: prüft nur geänderte Pfade, die auf `TEST_FILE` passen und im + verwalteten Scope liegen. No-op auf `devloop/spec/*`. + +Gemessene Lücken: + +1. **#21, Alias:** neue Datei mit `import { test as t } from "vitest"; t("evil", …)` → Naht + `ok: true`, vitest führt den Test aus. Ebenso `test["only"](…)`, `(test)(…)`. +2. **#25, Verzeichnis-Symlink:** PR fügt `t/cy -> ../cypress` und `t/dep -> ../node_modules/evilpkg` + hinzu. Die Link-Pfade tragen keinen Testnamen und werden nicht betrachtet. vitest folgt den + Links und führt `t/cy/old.spec.js` (Basis, sonst per Default-Exclude nie gelaufen) und + `t/dep/x.test.js` (erst in CI installiert, nie committet) aus. + +## Entscheidung + +**#21:** Statt den Inhalt neuer Dateien zu deuten, verbietet die Naht sie. Ein PR außerhalb von +`devloop/spec/*` darf keine verwaltete Testdatei anlegen. Das entspricht dem, was +`agents/devloop-implement.md` schon heute vorschreibt („Tests hinzufügen/löschen“ ist verboten). +Neue verwaltete Tests entstehen nur im Spec-PR, und den gibt das Spec-Gate (#4) nur mit +menschlichem Review frei. Damit ist die Schreibweise des Tests gleichgültig; es gibt keine +Regex mehr, die man umgehen kann. + +Der Vorschlag aus dem Issue (Tests über `vitest list` einsammeln) ist verworfen. Die Action müsste +die Abhängigkeiten des Ziel-Repos installieren und dessen vitest-Config aus dem PR-HEAD ausführen. +Die Config ist Code, den der PR selbst ändern kann, etwa um die eigene Datei aus der Liste zu +nehmen. Fail-closed ist das nur mit großem Aufwand, und es bindet devloop an vitest. + +**#25:** Jeder Symlink, den der PR anlegt oder umbiegt, muss innerhalb des Repos auf eine reguläre +Datei im HEAD zeigen. Ein Ziel, das ein Verzeichnis ist, fehlt (z. B. ein erst in CI installierter +Ordner), außerhalb des Repos liegt oder selbst ein Symlink ist, ist eine Verletzung. Das gilt für +jeden geänderten Pfad, nicht nur für Testnamen und unabhängig vom verwalteten Scope: Ob unter einem +Verzeichnis verwaltete Tests landen, lässt sich am Link-Pfad nicht ablesen. + +**Gemessene Kosten auf echten PRs** (bsk, 280 gemergte PRs, Stand 2026-11-28): + +- Neue verwaltete Testdatei außerhalb von `devloop/spec/*`: 6 PRs (#45, #46, #61, #64, #156 nur + geändert, #192). In allen neuen Dateien findet schon `hasActiveTest` einen aktiven Test + (28 Dateien, 28 aktiv). Die neue Regel ändert das Urteil für **0** PRs. +- Symlinks: 10 Commits auf `main` legen Symlinks an, alle vor der devloop-Einführung (letzter + 2026-05-23). 9 davon sind versehentlich committete `node_modules`-Links (Verzeichnisse → künftig + Verletzung, erwünscht), einer legt 4 Bild-Platzhalter als Links auf eine Datei im selben + Ordner an (→ erlaubt). Im heutigen Baum: 0 Symlinks. obol und carrera-planer: nie ein Symlink. + +## Begriffe + +- **Verwaltete Testdatei:** wie bisher, ein Pfad, der auf `TEST_FILE` passt und im Scope aus + `.devloop/managed-tests.json` liegt (fehlt die Datei: jeder Testpfad). +- **Neu angelegt:** Der Pfad fehlt in der Basis und ist im HEAD vorhanden. +- **Geänderter Symlink:** ein Pfad aus dem Diff, dessen Eintrag im HEAD ein Symlink (`120000`) ist. + Das umfasst neue Links, umgebogene Links und Dateien, die zu Links werden. +- **Link-Ziel:** der Inhalt des Symlink-Blobs im HEAD, unverändert (kein Trimmen). +- **Aufgelöstes Ziel:** das Link-Ziel relativ zum Ordner des Links, normalisiert (`.` und `..` + aufgelöst). Es liegt **im Repo**, wenn es weder absolut ist noch über die Wurzel hinausführt + noch die Wurzel selbst ist. + +## Anforderungen (EARS) + +- **REQ-NEWTEST-1** *(unwanted)* — Wenn ein PR außerhalb von `devloop/spec/*` eine verwaltete + Testdatei neu anlegt, soll `verify-unskip` das als Verletzung werten, unabhängig vom Inhalt der + Datei. Die Meldung nennt, dass neue verwaltete Tests nur über einen Spec-PR (`devloop/spec/*`) + kommen. +- **REQ-NEWTEST-2** *(ubiquitous)* — Für bestehende verwaltete Testdateien bleibt die Regel + unverändert: Erlaubt ist nur das Entfernen von `.skip`; Löschen oder Leeren ist eine + Verletzung. Unverwaltete Testdateien werden weiter nicht bewertet. +- **REQ-SYMLINK-1** *(unwanted)* — Wenn ein geänderter Symlink kein aufgelöstes Ziel im Repo hat + oder sein aufgelöstes Ziel im HEAD keine reguläre Datei ist (fehlt, Verzeichnis, Symlink, + Submodul), soll `verify-unskip` das als Verletzung werten. Das gilt für jeden Pfad im Diff, + unabhängig von Dateiname und verwaltetem Scope. Die Meldung nennt Link-Pfad und Link-Ziel. +- **REQ-SYMLINK-2** *(ubiquitous)* — Ein geänderter Symlink, dessen aufgelöstes Ziel im HEAD eine + reguläre Datei ist, bleibt erlaubt, sofern er nicht selbst eine verwaltete Testdatei ist (dann + gilt REQ-UNSKIPCONTENT-4 unverändert). Gelöschte Symlinks sind erlaubt. +- **REQ-SYMLINK-3** *(unwanted)* — Wenn Eintrag oder Ziel eines geänderten Pfads nicht gelesen + werden kann, soll `verify-unskip` mit Exit 1 fehlschlagen und Pfad und Ref nennen (wie + REQ-UNSKIPCONTENT-3). +- **REQ-UNSKIPNEU-4** *(ubiquitous)* — Unverändert bleiben: No-op auf `devloop/spec/*`, + Pfadermittlung, Lesen des Scopes aus der Basis, Aufruf und Exit-Codes. Das Ausgabeformat + bekommt ein Feld `symlinks` mit den geprüften geänderten Symlinks; die übrigen Felder bleiben. + Je Pfad steht höchstens eine Verletzung in `violations`, Rangfolge: Typ (REQ-UNSKIPCONTENT-4) vor + REQ-NEWTEST-1 vor REQ-SYMLINK-1. Der Exit-Code bleibt 1, sobald eine greift. +- **REQ-UNSKIPNEU-5** *(ubiquitous)* — `USAGE.md`, `agents/devloop-implement.md` und + `agents/devloop-spec-to-tests.md` sollen nennen: Neue verwaltete Tests nur im Spec-PR; + Symlinks nur auf reguläre Dateien im Repo. + +## Geänderte Erwartungen bestehender Tests + +Diese Tests prüfen bisher, dass eine neue, vollständig geskippte Datei außerhalb eines Spec-Branches +durchgeht. Nach REQ-NEWTEST-1 ist sie eine Verletzung; die Erwartung kehrt sich um: + +- `test/cli/verify-unskip-inhalte.test.ts`: „counter-probe: new 1.2 MB file with all tests skipped + passes“ (REQ-UNSKIPCONTENT-1) und „a plainly absent path (new file …) is NOT a read error: exit 0 + for a new skipped file“ (REQ-UNSKIPCONTENT-2). Neue Gegenprobe für beide: dieselbe Konstruktion + als **bestehende** geskippte Datei, PR entfernt nur `.skip` → Exit 0. Damit bleibt geprüft, dass + Größe und „fehlt in der Basis“ kein Lesefehler sind (Exit 1 mit Lesefehler-Meldung vs. Exit 1 mit + REQ-NEWTEST-1-Meldung unterscheiden). +- `test/core/unskip.test.ts`: die Fälle zu `hasActiveTest` und „a NEW test file … is allowed iff + every test is skipped“ entfallen bzw. werden auf die neue Regel umgestellt. +- `test/cli/verify-unskip.test.ts` „spec PR: a NEW all-skipped test file is allowed (exit 0)“: läuft + auf Branch `spec` ohne Head-Branch-Argument, also als Impl-PR, und wird nach REQ-NEWTEST-1 rot. + Der Titel meint den Spec-PR; der Test bekommt deshalb `devloop/spec/b` als Head-Branch und bleibt + bei Exit 0 (No-op). (Nachgetragen nach der Teststation, 2026-11-28.) +- Alle übrigen bestehenden Tests bleiben unverändert grün. + +## Detektoren (Wirkung) und Mutationsproben + +CLI-Tests gegen `dist/cli/verify-unskip.js` in echten temporären Git-Repos: + +| Fall | Erwartung | tötet Mutation | +|---|---|---| +| neue verwaltete Datei mit `import { test as t }`, `t("evil")`; vitest führt sie aus (im Test gegengeprüft) | Exit 1, REQ-NEWTEST-1-Meldung | Inhalt statt Existenz bewertet | +| neue verwaltete Datei, alle Tests geskippt | Exit 1 | dto. | +| neue verwaltete leere Datei | Exit 1 | „leer = nicht neu“ | +| dieselben drei auf `devloop/spec/x` | Exit 0 (No-op) | Spec-Branch nicht ausgenommen | +| neue **unverwaltete** Datei mit aktivem Test (Scope gesetzt) | Exit 0, in `unmanaged` | Scope bei neuen Dateien ignoriert | +| bestehende geskippte Datei, nur `.skip` entfernt | Exit 0 | — (Gegenprobe) | +| Datei im PR umbenannt (alter Pfad gelöscht, neuer angelegt) | Exit 1 | — (wie bisher, jetzt mit beiden Gründen) | +| `t/cy -> ../cypress` (Verzeichnis in HEAD); vitest führt `t/cy/old.spec.js` aus | Exit 1, Meldung nennt `t/cy` und `../cypress` | Symlinks ohne Testnamen übergangen | +| `t/dep -> ../node_modules/evilpkg` (fehlt in HEAD) | Exit 1 | „fehlt“ als erlaubt | +| Link mit absolutem Ziel `/tmp/x` bzw. `../../außerhalb` | Exit 1 | Ziel außerhalb nicht geprüft | +| Link auf `.` bzw. auf die Wurzel (`t/r -> ..`) | Exit 1 | Wurzel als Ziel erlaubt | +| Link auf einen Link, der auf eine Datei zeigt | Exit 1 | Ketten verfolgt statt abgelehnt | +| Link `img/a.jpg -> b.jpg` (reguläre Datei im selben Ordner) | Exit 0, in `symlinks` | jeder Symlink verboten | +| Link `x -> sub/../y.txt` (reguläre Datei nach Normalisierung) | Exit 0 | Normalisierung fehlt | +| bestehende Datei wird zum Verzeichnis-Link (Typwechsel) | Exit 1 | nur neue Pfade geprüft | +| bestehender Datei-Link wird auf ein Verzeichnis umgebogen | Exit 1 | nur neue Pfade geprüft | +| Verzeichnis-Link im Scope **außerhalb** (Scope gesetzt, Link-Pfad unverwaltet) | Exit 1 | Scope auf Symlinks angewandt | +| gelöschter Verzeichnis-Link | Exit 0 | Löschung als Änderung gewertet | +| Ziel-Blob des Links nicht lesbar (Objekt entfernt) | Exit 1, nennt Pfad und Ref | Lesefehler als „fehlt“ | +| Spec-Branch mit Verzeichnis-Link | Exit 0 (No-op) | — | + +Mutationen werden im Implementierungs-PR gefahren und mit Ergebnis in der PR-Beschreibung +dokumentiert. + +## Umsetzung (Skizze, nicht bindend) + +- `hasActiveTest` und der Zweig „neu“ in `isAllowedTestEdit` entfallen. +- Einträge aller geänderten Pfade im HEAD möglichst in einem Aufruf lesen (z. B. + `git diff --raw -z`), nicht ein `ls-tree` pro Pfad. +- Versionssprung **v0.17.0**. + +## Kritiker-Abbruchbedingung (vor dem Start festgelegt) + +Höchstens zwei Kritikerrunden. Blockierend ist nur eine falsche Zahl auf einem realen Pfad: ein +gemergter PR aus bsk, obol, carrera-planer oder devloop, dessen Urteil der neue Stand falsch fällt, +oder eine Konstruktion, bei der vitest einen Test ausführt, den die Naht durchlässt. Alles andere +wird unter „Bekannte Grenzen“ dokumentiert. + +## Bekannte Grenzen (dokumentiert, keine eigene Runde) + +- **Testdatei-Erkennung bleibt `TEST_FILE`:** Ein eigenes `include` in der vitest-Config, ein + anderer Runner oder ein Pfad mit Zeilenende am Ende (`x.test.ts`, Grenze aus #15) wird nicht + als Testdatei erkannt. Eine neue solche Datei ist damit weiter nicht verwaltet. Folge-Issue #39. +- **Symlinks, die schon in der Basis liegen,** prüft die Naht nicht. Ein bestehender + Verzeichnis-Link bringt neue Dateien in seinem Ziel mit; die erscheinen im Diff aber unter ihrem + echten Pfad und werden dort wie jede Datei geprüft. Lücke nur, wenn der echte Pfad unverwaltet + und der Link-Pfad verwaltet ist. +- **Zwischen-Symlinks im Ziel:** Führt das Ziel durch einen Ordner, der selbst ein Symlink ist, + findet Git dort keinen Eintrag; das Ziel gilt als fehlend (Verletzung, fail-closed). +- **Spec-PRs** bleiben No-op, auch für Symlinks. Sie laufen über das Spec-Gate mit menschlichem + Review. +- **Scope-unabhängige Symlink-Regel:** Repos mit engem Scope bekommen auch für Links außerhalb + ihrer verwalteten Tests eine Verletzung. Gemessen ohne Treffer seit der devloop-Einführung. +- **Tests in Nicht-Testdateien:** Ein Impl-PR, der nur `.skip` entfernt und in einem von der + Testdatei importierten Modul (`src/helper.ts`) ein `test(…)` ergänzt, besteht die Naht; vitest + führt den zusätzlichen Test aus (gemessen: 2 statt 1 Test). Bestand schon auf `main` (v0.16.0). + Schließen ließe es sich erst über einen Vergleich der Testmenge; Folge-Issue #41. +- **Lexikalische statt physischer Auflösung:** Das Link-Ziel wird rein textlich normalisiert. Liegt + in der Basis schon ein Verzeichnis-Link (`sup -> cypress/support`), löst `t/cy -> ../sup/../e2e` + textlich auf die reguläre Datei `e2e` auf, das Betriebssystem aber auf `cypress/e2e`. Kein + gemessenes Repo hat einen solchen Verzeichnis-Link. +- **Submodule** (gitlinks) mit Testdateien prüft die Naht nicht. Wirkung nur, wenn die CI + Submodule auscheckt; keine gemessene CI tut das. +- **Andere Urteile in obol:** Die Kostenmessung oben stammt aus bsk. In obol wechseln 2 von 51 + gemergten PRs von bestanden auf Verletzung (#19 `devloop/account-detail-spec`, #28 + `devloop/wallet-topup-spec`): Spec-PRs von vor der Branch-Konvention `devloop/spec/` + (2026-06-21). Nach heutigem Vertrag ist das das gewollte Urteil. diff --git a/package.json b/package.json index b9001f1..4904c0e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.16.0", + "version": "0.17.0", "private": true, "type": "module", "license": "MIT", diff --git a/src/cli/verify-unskip.ts b/src/cli/verify-unskip.ts index 9fdc1b9..b001097 100644 --- a/src/cli/verify-unskip.ts +++ b/src/cli/verify-unskip.ts @@ -1,7 +1,10 @@ // CLI: the unskip CI guard (Obol pilot §3.2/§4). Runs on EVERY PR (spec PR + implement PR): -// - a NEW test file may be authored only if every test in it is `.skip`'d (spec PR); -// - an EXISTING test file may change ONLY by removing `.skip` (implement PR). -// implement can thus neither author active tests nor edit existing ones. Fail-closed (exit 1). +// - a NEW managed test file is a violation outside `devloop/spec/*` (#21: new tests come only +// through a spec PR; the content is never judged); +// - an EXISTING test file may change ONLY by removing `.skip` (implement PR); +// - every changed symlink must resolve to a regular file inside the repo (#25). +// implement can thus neither add test files nor edit existing ones. Not covered: test() calls in a +// non-test module that a test imports (limit, issue #41). Fail-closed (exit 1). // // 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 @@ -16,7 +19,7 @@ import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { isAllowedTestEdit, isSpecBranch } from "../core/unskip.js"; -import { parseNulPaths } from "../core/diff-paths.js"; +import { checkSymlinks, rawDiff, SymlinkReadError, type DiffEntry } from "../core/symlinks.js"; import { readTreeEntry, TreeEntryReadError, type TreeEntry } from "../core/tree-entry.js"; import { MANAGED_TESTS_PATH, @@ -74,28 +77,19 @@ const managedRaw = cfg.kind === "file" ? fromBase : fromWorktree; const managedSource = cfg.kind === "file" ? "base" : fromWorktree !== "" ? "worktree" : "default"; const managedGlobs = parseManagedTestGlobs(managedRaw); -// The changed paths: NUL-separated (-z: no quoting of non-ASCII/special characters) and without -// rename detection (a rename shows BOTH the old and the new path, so the old one is judged as a -// deletion). Unlike `git show` of an absent file, a failing diff (unresolvable base, ...) is NOT -// "no test files": it fails closed with exit 1. -const changedPaths = (): string[] => { +// The changed entries: NUL-separated (-z: no quoting) and without rename detection (a rename shows +// BOTH the old and the new path, so the old one is judged as a deletion). A failing diff +// (unresolvable base, ...) is NOT "no test files": it fails closed with exit 1. +const diffEntries = (): DiffEntry[] => { try { - const raw = execFileSync( - "git", - ["-C", repo, "diff", "--no-renames", "-z", "--name-only", `${base}...HEAD`], - { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 }, - ); - return parseNulPaths(raw); + return rawDiff(repo, base); } catch (e) { - const detail = String((e as { stderr?: unknown }).stderr ?? (e as Error).message ?? e).trim(); - process.stderr.write( - `verify-unskip: cannot compute the changed paths against base "${base}" (git diff failed): ${detail}\n`, - ); - process.exit(1); + return fail(`cannot compute the changed paths against base "${base}" (git diff failed): ${(e as Error).message}`); } }; -const testFiles = changedPaths().filter((f) => TEST_FILE.test(f)); +const entries = diffEntries(); +const testFiles = entries.map((e) => e.path).filter((f) => TEST_FILE.test(f)); const changed = testFiles.filter((f) => isManagedTestPath(f, managedGlobs)); const unmanaged = testFiles.filter((f) => !isManagedTestPath(f, managedGlobs)); @@ -131,21 +125,42 @@ for (const file of changed) { }); continue; } + if (oldEntry.kind === "missing") { + // REQ-NEWTEST-1: a new managed test file is judged by its existence, never its content. + violations.push({ + file, + reason: + "new managed test file outside a spec PR; new managed tests come only through a spec PR (devloop/spec/*)", + }); + continue; + } const oldContent = contentOf(oldEntry); // "" if the file is new const newContent = contentOf(newEntry); if (!isAllowedTestEdit(oldContent, newContent)) { violations.push({ file, reason: - oldContent === "" - ? "new test file contains an active (non-.skip) test (spec-PR tests must be skipped)" - : newContent === "" + newContent === "" ? "existing test file deleted or emptied (also when renamed away; implement must not remove tests)" : "existing test file changed beyond removing `.skip` (implement must not edit tests)", }); } } +// REQ-SYMLINK-*: every changed path whose HEAD entry is a symlink, independent of name and scope. +let symlinks: { file: string; target: string }[] = []; +try { + const r = checkSymlinks(repo, entries); + symlinks = r.symlinks; + // One violation per file: type (UNSKIPCONTENT-4) > NEWTEST-1 > SYMLINK-1. + const seen = new Set(violations.map((v) => v.file)); + violations.push(...r.violations.filter((v) => !seen.has(v.file))); +} catch (e) { + if (!(e instanceof SymlinkReadError)) throw e; + const links = entries.filter((x) => x.newMode === "120000").map((x) => x.path); + fail(`cannot read symlink entries/targets @ ${base}...HEAD (symlinks: ${links.join(", ")}): ${e.message}`); +} + const ok = violations.length === 0; process.stdout.write( JSON.stringify( @@ -157,6 +172,7 @@ process.stdout.write( managedSource, checked: changed, unmanaged, + symlinks, violations, }, null, diff --git a/src/core/symlinks.ts b/src/core/symlinks.ts new file mode 100644 index 0000000..6e36f7a --- /dev/null +++ b/src/core/symlinks.ts @@ -0,0 +1,135 @@ +// Symlink rule of the unskip seam (#25): every symlink a PR creates or re-points must resolve to a +// REGULAR FILE inside the repo (in HEAD). vitest follows directory links into trees that are never +// committed (node_modules) or never run by default (cypress), so the link path alone decides nothing. +import { execFileSync } from "node:child_process"; +import { posix } from "node:path"; + +export interface DiffEntry { + path: string; + /** Mode in HEAD ("000000" = deleted). */ + newMode: string; + newOid: string; +} + +export class SymlinkReadError extends Error {} + +const run = (repo: string, args: string[], input?: string, maxBuffer = 256 * 1024 * 1024): Buffer => { + try { + return execFileSync("git", ["-C", repo, "--literal-pathspecs", ...args], { + stdio: ["pipe", "pipe", "pipe"], + input, + maxBuffer, + }); + } catch (e) { + const err = e as { stderr?: unknown; message?: string }; + throw new SymlinkReadError(String(err.stderr ?? "").trim() || err.message || String(e)); + } +}; + +/** `git diff --raw -z --no-renames --no-abbrev`: ":om nm oo no S\0path\0" records. */ +export function parseRawDiff(raw: string): DiffEntry[] { + const parts = raw.split("\0"); + const out: DiffEntry[] = []; + for (let i = 0; i + 1 < parts.length; i += 2) { + const m = /^:(\d+) (\d+) ([0-9a-f]+) ([0-9a-f]+) (\w)$/.exec(parts[i]); + if (!m) { + if (parts[i] === "") break; + throw new SymlinkReadError(`unparsable diff record ${JSON.stringify(parts[i])}`); + } + out.push({ path: parts[i + 1], newMode: m[2], newOid: m[4] }); + } + return out; +} + +export const rawDiff = (repo: string, base: string): DiffEntry[] => + parseRawDiff( + run(repo, ["diff", "--raw", "-z", "--no-renames", "--no-abbrev", `${base}...HEAD`]).toString("utf8"), + ); + +/** Link target -> repo-relative resolved path, or null if absolute / escaping / root / empty. */ +export function resolveLinkTarget(linkPath: string, target: string): string | null { + if (target === "" || target.startsWith("/") || target.endsWith("/") || target.includes("\0")) return null; + const resolved = posix.normalize(posix.join(posix.dirname(linkPath), target)); + if (resolved === "." || resolved === ".." || resolved.startsWith("../") || resolved.startsWith("/")) { + return null; + } + return resolved; +} + +/** Contents of the given blobs (one `cat-file --batch` call). */ +export function readBlobs(repo: string, oids: string[]): Map { + const res = new Map(); + if (oids.length === 0) return res; + const buf = run(repo, ["cat-file", "--batch"], oids.join("\n") + "\n", 1024 * 1024 * 1024); + let pos = 0; + for (const oid of oids) { + const nl = buf.indexOf(10, pos); + const header = nl < 0 ? "" : buf.subarray(pos, nl).toString("utf8"); + const m = /^([0-9a-f]+) (\w+) (\d+)$/.exec(header); + if (!m || m[2] !== "blob") throw new SymlinkReadError(`cannot read blob ${oid} (${header || "no output"})`); + const size = Number(m[3]); + res.set(oid, buf.subarray(nl + 1, nl + 1 + size).toString("utf8")); + pos = nl + 1 + size + 1; + } + return res; +} + +/** HEAD entries (mode) of the given exact paths; absent paths are not in the map. One call per chunk. */ +export function headModes(repo: string, paths: string[]): Map { + const res = new Map(); + for (let i = 0; i < paths.length; i += 500) { + const chunk = paths.slice(i, i + 500); + const raw = run(repo, ["ls-tree", "-z", "HEAD", "--", ...chunk]).toString("utf8"); + for (const rec of raw.split("\0").filter((r) => r !== "")) { + const m = /^(\d+) (\w+) ([0-9a-f]+)\t([\s\S]*)$/.exec(rec); + if (!m) throw new SymlinkReadError("unparsable ls-tree record"); + res.set(m[4], { mode: m[1], oid: m[3] }); + } + } + return res; +} + +export interface SymlinkResult { + symlinks: { file: string; target: string }[]; + violations: { file: string; reason: string }[]; +} + +export function checkSymlinks(repo: string, entries: DiffEntry[]): SymlinkResult { + const links = entries.filter((e) => e.newMode === "120000"); + const blobs = readBlobs(repo, [...new Set(links.map((l) => l.newOid))]); + const infos = links.map((l) => { + const target = blobs.get(l.newOid) as string; + return { file: l.path, target, resolved: resolveLinkTarget(l.path, target) }; + }); + const modes = headModes(repo, [...new Set(infos.flatMap((i) => (i.resolved === null ? [] : [i.resolved])))]); + // A regular-file target whose blob cannot be read is a read error, never "fine". + const targetOids = [...new Set([...modes.values()].filter((e) => e.mode === "100644" || e.mode === "100755").map((e) => e.oid))]; + if (targetOids.length > 0) { + const out = run(repo, ["cat-file", "--batch-check"], targetOids.join("\n") + "\n").toString("utf8"); + const lines = out.split("\n").filter((l) => l !== ""); + if (lines.length !== targetOids.length || lines.some((l) => !/^[0-9a-f]+ blob \d+$/.test(l))) { + throw new SymlinkReadError(`a symlink target blob cannot be read (${lines.find((l) => !/^[0-9a-f]+ blob \d+$/.test(l)) ?? "short output"})`); + } + } + const violations: { file: string; reason: string }[] = []; + for (const i of infos) { + const t = i.target; + let why: string | null = null; + if (i.resolved === null) { + why = `outside the repo, absolute, the repo root or empty`; + } else { + const e = modes.get(i.resolved); + if (!e) why = `missing in HEAD (${i.resolved})`; + else if (e.mode !== "100644" && e.mode !== "100755") { + why = `not a regular file in HEAD (${i.resolved}: ${e.mode === "040000" ? "directory" : e.mode === "120000" ? "symlink" : e.mode === "160000" ? "submodule" : e.mode})`; + } + } + if (why !== null) { + violations.push({ + file: i.file, + reason: `symlink ${i.file} -> ${t}: target ${why}; a symlink must resolve to a regular file inside the repo`, + }); + } + } + return { symlinks: infos.map((i) => ({ file: i.file, target: i.target })), violations }; +} diff --git a/src/core/unskip.ts b/src/core/unskip.ts index bf67394..7b20c70 100644 --- a/src/core/unskip.ts +++ b/src/core/unskip.ts @@ -16,25 +16,10 @@ const isWordChar = (c: string | undefined): boolean => c !== undefined && /\w/.t const skipAt = (s: string, i: number): boolean => s.startsWith(SKIP, i) && !isWordChar(s[i + SKIP.length]); -// Does the source contain an ACTIVE (non-skipped) test call? Matches `it`/`test` with any -// chained props (e.g. .only/.each/.skip) before the call paren; active unless the chain has -// `.skip`. `describe(` is a container, not a test, so it is ignored. -const TEST_CALL = /\b(?:it|test)((?:\.\w+)*)\s*\(/g; -export function hasActiveTest(content: string): boolean { - for (const m of content.matchAll(TEST_CALL)) { - if (!/\.skip\b/.test(m[1])) return true; - } - return false; -} - -// Unified rule for the precondition-check (runs on BOTH the spec PR and the implement PR): -// - NEW test file (old empty): authoring is allowed — but every test must be `.skip`'d, so -// nothing secretly-active lands on a green main (spec-PR authoring by spec-to-tests). -// - EXISTING test file: only `.skip` removal is allowed (implement PR). -// Safe on both: implement cannot smuggle an active test via a new file (would have to be all -// `.skip`'d = inert), nor edit assertions of existing files. +// Unified rule for the precondition-check on the implement PR: an EXISTING test file may change +// only by removing `.skip`. NEW managed test files are not judged by content at all — the CLI +// rejects them outright (they come only through a spec PR, #21). export function isAllowedTestEdit(oldContent: string, newContent: string): boolean { - if (oldContent === "") return !hasActiveTest(newContent); return isUnskipOnly(oldContent, newContent); } diff --git a/test/cli/verify-unskip-inhalte.test.ts b/test/cli/verify-unskip-inhalte.test.ts index 0559c7b..eb10423 100644 --- a/test/cli/verify-unskip-inhalte.test.ts +++ b/test/cli/verify-unskip-inhalte.test.ts @@ -79,13 +79,39 @@ test("[REQ-UNSKIPCONTENT-1] new 1.2 MB test file with an ACTIVE test is a violat expect(files(out.violations)).toEqual(["big.test.ts"]); }); -test("[REQ-UNSKIPCONTENT-1] counter-probe: new 1.2 MB file with all tests skipped passes and is checked (already green: today an empty read is 'allowed' by accident)", () => { +// Reversed by REQ-NEWTEST-1 (#21): a new managed file is a violation whatever it contains. What stays +// checked here: the size is NOT a read error — the verdict is the judged REQ-NEWTEST-1 violation +// (JSON on stdout, devloop/spec/ message), not a fail-closed read error on stderr. +test("[REQ-UNSKIPCONTENT-1][REQ-NEWTEST-1] new 1.2 MB file with all tests skipped is the REQ-NEWTEST-1 violation, not a read error", () => { startPr(); put("big.test.ts", SKIPPED + PADDING); git("add", "-A"); commit("spec-like: big skipped file"); expect(blobSize("HEAD:big.test.ts")).toBeGreaterThan(MIB); const r = run(); + expect(r.status).toBe(1); + expect(r.stderr).not.toMatch(/cannot read|read error|ENOBUFS/i); + const out = JSON.parse(r.stdout); + expect(out.ok).toBe(false); + expect(out.checked).toEqual(["big.test.ts"]); + const v = (out.violations as { file: string; reason: string }[]).filter((x) => x.file === "big.test.ts"); + expect(v.some((x) => x.reason.includes("devloop/spec/"))).toBe(true); +}); + +// Counter-probe for the reversed test above (spec: same construction as an EXISTING skipped file, +// PR only removes .skip -> exit 0). Kept separate from the base-1.2-MB counter-probe further down on +// purpose: this one starts from the same SKIPPED + PADDING content as the reversed test. +test("[REQ-UNSKIPCONTENT-1] counter-probe: the same 1.2 MB skipped file as an EXISTING file, PR only removes .skip: exit 0", () => { + put("big.test.ts", SKIPPED + PADDING); + git("add", "-A"); + commit("base: big skipped file"); + startPr(); + put("big.test.ts", (SKIPPED + PADDING).replaceAll("test.skip(", "test(")); + git("add", "-A"); + commit("implement: unskip the big file"); + expect(blobSize("HEAD:big.test.ts")).toBeGreaterThan(MIB); + const r = run(); + expect(r.stderr).toBe(""); expect(r.status).toBe(0); const out = JSON.parse(r.stdout); expect(out.violations).toEqual([]); @@ -268,14 +294,37 @@ test("[REQ-UNSKIPCONTENT-3] BASE blob of an existing test file is missing: exit expect(r.stdout).not.toMatch(/"ok":\s*true/); }); -test("[REQ-UNSKIPCONTENT-2] a plainly absent path (new file: absent in base) is NOT a read error: exit 0 for a new skipped file", () => { +// Reversed by REQ-NEWTEST-1 (#21): exit 1 now — but as the judged REQ-NEWTEST-1 violation (JSON on +// stdout, devloop/spec/ message), NOT as a read error. "Absent in base" stays a normal result. +test("[REQ-UNSKIPCONTENT-2][REQ-NEWTEST-1] a plainly absent path (new file: absent in base) is NOT a read error: the new skipped file is the REQ-NEWTEST-1 violation", () => { startPr(); put("n.test.ts", SKIPPED); git("add", "-A"); commit("spec-like: new skipped test"); const r = run(); + expect(r.status).toBe(1); + expect(r.stderr).not.toMatch(/cannot read|read error|neither/i); + const out = JSON.parse(r.stdout); + expect(out.ok).toBe(false); + expect(out.checked).toEqual(["n.test.ts"]); + const v = (out.violations as { file: string; reason: string }[]).filter((x) => x.file === "n.test.ts"); + expect(v.some((x) => x.reason.includes("devloop/spec/"))).toBe(true); +}); + +test("[REQ-UNSKIPCONTENT-2] counter-probe: the same skipped n.test.ts as an EXISTING file, PR only removes .skip: exit 0, checked", () => { + put("n.test.ts", SKIPPED); + git("add", "-A"); + commit("base: skipped n.test.ts"); + startPr(); + put("n.test.ts", SKIPPED.replaceAll("test.skip(", "test(")); + git("add", "-A"); + commit("implement: unskip"); + const r = run(); + expect(r.stderr).toBe(""); expect(r.status).toBe(0); - expect(JSON.parse(r.stdout).checked).toEqual(["n.test.ts"]); + const out = JSON.parse(r.stdout); + expect(out.violations).toEqual([]); + expect(out.checked).toEqual(["n.test.ts"]); }); test("[REQ-UNSKIPCONTENT-2] a deleted file (absent in HEAD) is judged as a deletion, not reported as a read error", () => { diff --git a/test/cli/verify-unskip-neue-tests-symlinks.test.ts b/test/cli/verify-unskip-neue-tests-symlinks.test.ts new file mode 100644 index 0000000..679de23 --- /dev/null +++ b/test/cli/verify-unskip-neue-tests-symlinks.test.ts @@ -0,0 +1,572 @@ +import { test, expect, beforeEach, afterEach } from "vitest"; +import { execFileSync, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { basename, dirname, join, resolve } from "node:path"; + +// Issues #21/#25 (docs/2026-11-28-verify-unskip-neue-tests-symlinks-design.md): +// - REQ-NEWTEST-1: outside devloop/spec/* a PR must not ADD a managed test file, whatever it contains. +// - REQ-SYMLINK-1/2: every symlink the PR adds or retargets must point to a regular file inside the repo. +// Real git repos, CLI against dist/cli/verify-unskip.js. Where the spec demands it, vitest itself is run +// in the test repo to prove that the construction is really executed (not only "looks like a test"). + +const here = dirname(fileURLToPath(import.meta.url)); +const cli = resolve(here, "../../dist/cli/verify-unskip.js"); +const vitestBin = resolve(here, "../../node_modules/vitest/vitest.mjs"); + +let repo: string; +let scratch: string; // outside the repo: vitest marker files +const git = (...args: string[]) => + execFileSync("git", ["-C", repo, ...args], { + encoding: "utf8", + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }); +const gitOk = (...args: string[]): boolean => { + try { + execFileSync("git", ["-C", repo, ...args], { stdio: "ignore" }); + return true; + } catch { + return false; + } +}; +const commit = (m: string) => git("-c", "commit.gpgsign=false", "commit", "-q", "-m", m); +const put = (rel: string, content: string) => { + mkdirSync(dirname(join(repo, rel)), { recursive: true }); + writeFileSync(join(repo, rel), content); +}; +const link = (rel: string, target: string) => { + mkdirSync(dirname(join(repo, rel)), { recursive: true }); + symlinkSync(target, join(repo, rel)); +}; +const commitAll = (m: string) => { + git("add", "-A"); + commit(m); +}; +const run = (headBranch?: string) => + spawnSync("node", [cli, repo, "main", ...(headBranch ? [headBranch] : [])], { encoding: "utf8" }); +const startPr = (name = "devloop/impl") => git("checkout", "-q", "-b", name); +const modeOf = (rel: string, ref = "HEAD") => git("ls-tree", ref, "--", rel).split(" ")[0]; +const looseObject = (spec: string) => { + const sha = git("rev-parse", spec).trim(); + return join(repo, ".git/objects", sha.slice(0, 2), sha.slice(2)); +}; + +type Violation = { file: string; reason: string }; +type Out = { + ok: boolean; + violations: Violation[]; + symlinks: { file: string; target: string }[]; + checked: string[]; + unmanaged: string[]; + skipped?: string; +}; +const parse = (r: { stdout: string }): Out => JSON.parse(r.stdout) as Out; +const violationsFor = (out: Out, file: string): Violation[] => out.violations.filter((v) => v.file === file); + +// The REQ-NEWTEST-1 violation for `file`: reason names the spec-PR route (devloop/spec/). +const expectNewTestViolation = (out: Out, file: string) => { + const v = violationsFor(out, file); + expect(v.length, JSON.stringify(out.violations)).toBeGreaterThan(0); + expect(v.some((x) => x.reason.includes("devloop/spec/")), JSON.stringify(v)).toBe(true); +}; +// The REQ-SYMLINK-1 violation for `file`: reason says "symlink" and carries the link target literally. +const expectSymlinkViolation = (out: Out, file: string, target: string) => { + const v = violationsFor(out, file); + expect(v.length, JSON.stringify(out.violations)).toBeGreaterThan(0); + expect(v.some((x) => /symlink/i.test(x.reason) && x.reason.includes(target)), JSON.stringify(v)).toBe(true); +}; + +const SKIPPED = `import { test, expect } from "vitest"; +test.skip("REQ-X-1 first behaviour", () => { expect(first()).toBe(1); }); +`; +const UNSKIPPED = SKIPPED.replaceAll("test.skip(", "test("); +// Writes a marker (outside the repo) when vitest really executes the test body. +const marking = (tag: string, call: string, importLine = `import { test } from "vitest";`) => + `${importLine} +import { appendFileSync } from "node:fs"; +${call}("evil", () => { appendFileSync(process.env.DEVLOOP_MARK, "${tag}\\n"); }); +`; + +beforeEach(() => { + repo = mkdtempSync(join(tmpdir(), "devloop-newtests-")); + scratch = mkdtempSync(join(tmpdir(), "devloop-newtests-mark-")); + git("init", "-q", "-b", "main"); + git("config", "user.name", "t"); + git("config", "user.email", "t@t"); + git("config", "core.quotePath", "true"); + git("config", "core.symlinks", "true"); + put("package.json", '{"type":"module"}\n'); + put("README.md", "base\n"); + put("a.test.ts", SKIPPED); + // A legacy cypress spec on main: vitest's default exclude (**/cypress/**) keeps it from running. + put("cypress/old.spec.js", marking("cy", "test")); + commitAll("base"); +}); +afterEach(() => { + rmSync(repo, { recursive: true, force: true }); + rmSync(scratch, { recursive: true, force: true }); +}); + +// Runs vitest in the test repo (default config) and returns what the test bodies marked. +const vitestRun = (): { status: number | null; marks: string[]; output: string } => { + const mark = join(scratch, "mark.txt"); + rmSync(mark, { force: true }); + const env: NodeJS.ProcessEnv = {}; + for (const [k, v] of Object.entries(process.env)) if (!k.startsWith("VITEST") && k !== "NODE_OPTIONS") env[k] = v; + env.DEVLOOP_MARK = mark; + const v = spawnSync("node", [vitestBin, "run", "--root", repo], { + cwd: repo, + encoding: "utf8", + env, + timeout: 60_000, + maxBuffer: 16 * 1024 * 1024, + }); + const marks = existsSync(mark) ? readFileSync(mark, "utf8").split("\n").filter(Boolean) : []; + return { status: v.status, marks, output: v.stdout + v.stderr }; +}; + +// ===================== #21: no new managed test file outside devloop/spec/* ===================== + +const ALIAS_VARIANTS: { name: string; content: string; tag: string }[] = [ + { name: "import { test as t } … t(\"evil\")", content: marking("alias", "t", `import { test as t } from "vitest";`), tag: "alias" }, + { name: "test[\"only\"](\"evil\")", content: marking("bracket", `test["only"]`), tag: "bracket" }, + { name: "(test)(\"evil\")", content: marking("paren", "(test)"), tag: "paren" }, +]; + +for (const { name, content, tag } of ALIAS_VARIANTS) { + test(`[REQ-NEWTEST-1] new managed file with ${name}: vitest executes it, the seam fails (exit 1, devloop/spec/ message)`, () => { + startPr(); + put("t/n.test.ts", content); + commitAll("implement: smuggle an active test the regex does not see"); + + // Counter-check: vitest really executes the body (this is the gap from #21, not a paper case). + const v = vitestRun(); + expect(v.marks, v.output).toContain(tag); + + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expect(out.ok).toBe(false); + expect(out.checked).toContain("t/n.test.ts"); + expectNewTestViolation(out, "t/n.test.ts"); + }); +} + +test("[REQ-NEWTEST-1] new managed file with every test skipped is a violation (exit 1, devloop/spec/ message)", () => { + startPr(); + put("t/s.test.ts", SKIPPED); + commitAll("implement: add a skipped test"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expect(out.ok).toBe(false); + expectNewTestViolation(out, "t/s.test.ts"); +}); + +test("[REQ-NEWTEST-1] new managed EMPTY file is a violation (exit 1): empty does not mean 'not new'", () => { + startPr(); + put("t/e.test.ts", ""); + commitAll("implement: add an empty test file"); + expect(modeOf("t/e.test.ts")).toBe("100644"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expect(out.ok).toBe(false); + expectNewTestViolation(out, "t/e.test.ts"); +}); + +test("[REQ-NEWTEST-1] new skipped file under a managed scope glob is a violation (scope set, path inside)", () => { + put(".devloop/managed-tests.json", JSON.stringify(["services/**/*.test.ts"]) + "\n"); + commitAll("scope the seam to services"); + startPr(); + put("services/forum/b.test.ts", SKIPPED); + commitAll("implement: skipped test in the managed area"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expect(out.checked).toEqual(["services/forum/b.test.ts"]); + expectNewTestViolation(out, "services/forum/b.test.ts"); +}); + +test("[REQ-NEWTEST-1] the same three new files (alias, all skipped, empty) on devloop/spec/x are a no-op pass (exit 0)", () => { + startPr("devloop/spec/x"); + put("t/n.test.ts", ALIAS_VARIANTS[0].content); + put("t/s.test.ts", SKIPPED); + put("t/e.test.ts", ""); + commitAll("spec PR: author tests"); + const r = run("devloop/spec/x"); + expect(r.status).toBe(0); + const out = parse(r); + expect(out.ok).toBe(true); + expect(out.skipped).toMatch(/spec/i); +}); + +test("[REQ-NEWTEST-1] counter-probe: the same three new files WITHOUT the spec head branch argument fail (exit 1, each named)", () => { + startPr("devloop/spec/x"); + put("t/n.test.ts", ALIAS_VARIANTS[0].content); + put("t/s.test.ts", SKIPPED); + put("t/e.test.ts", ""); + commitAll("spec-looking PR, judged as implement PR"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + for (const f of ["t/n.test.ts", "t/s.test.ts", "t/e.test.ts"]) expectNewTestViolation(out, f); +}); + +test("[REQ-NEWTEST-2] new UNMANAGED file with an active test (scope set) is not judged: exit 0, listed in unmanaged", () => { + put(".devloop/managed-tests.json", JSON.stringify(["services/**/*.test.ts"]) + "\n"); + commitAll("scope the seam to services"); + startPr("chore/tools"); + put("tools/scan.test.ts", marking("tools", "test")); + commitAll("chore: plain dev tool with active tests"); + const r = run(); + expect(r.status).toBe(0); + const out = parse(r); + expect(out.ok).toBe(true); + expect(out.unmanaged).toContain("tools/scan.test.ts"); + expect(out.checked).toEqual([]); + expect(out.violations).toEqual([]); +}); + +test("[REQ-NEWTEST-2] counter-probe: existing skipped file with only .skip removed passes (exit 0, checked)", () => { + startPr(); + put("a.test.ts", UNSKIPPED); + commitAll("implement: activate"); + const r = run(); + expect(r.status).toBe(0); + const out = parse(r); + expect(out.ok).toBe(true); + expect(out.violations).toEqual([]); + expect(out.checked).toEqual(["a.test.ts"]); +}); + +test("[REQ-NEWTEST-2] existing managed test emptied is still a violation (exit 1)", () => { + startPr(); + put("a.test.ts", ""); + commitAll("implement: empty the test"); + const r = run(); + expect(r.status).toBe(1); + expect(violationsFor(parse(r), "a.test.ts").length).toBeGreaterThan(0); +}); + +test("[REQ-NEWTEST-1][REQ-NEWTEST-2] pure rename a.test.ts -> c.test.ts (content unchanged): exit 1 for BOTH paths", () => { + startPr(); + git("mv", "a.test.ts", "c.test.ts"); + commit("implement: rename a managed test"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expect(violationsFor(out, "a.test.ts").length).toBeGreaterThan(0); // old path: deleted (REQ-NEWTEST-2) + expectNewTestViolation(out, "c.test.ts"); // new path: newly added (REQ-NEWTEST-1) +}); + +// ===================== #25: symlinks only to regular files inside the repo ===================== + +test("[REQ-SYMLINK-1] t/cy -> ../cypress (directory in HEAD): vitest executes t/cy/old.spec.js, the seam fails naming t/cy and ../cypress", () => { + startPr(); + link("t/cy", "../cypress"); + commitAll("implement: link the cypress folder into the test tree"); + expect(modeOf("t/cy")).toBe("120000"); + + // Counter-check: without the link vitest's default exclude skips the cypress spec; through it, it runs. + const v = vitestRun(); + expect(v.marks, v.output).toContain("cy"); + expect(v.output).toContain("t/cy/old.spec.js"); + + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expect(out.ok).toBe(false); + expectSymlinkViolation(out, "t/cy", "../cypress"); + expect(out.symlinks).toContainEqual({ file: "t/cy", target: "../cypress" }); +}); + +test("[REQ-SYMLINK-1] counter-probe for the vitest check: without the link, vitest does not run cypress/old.spec.js", () => { + const v = vitestRun(); + expect(v.marks, v.output).not.toContain("cy"); +}); + +test("[REQ-SYMLINK-1] t/dep -> ../node_modules/evilpkg (absent in HEAD, e.g. installed only in CI) is a violation", () => { + startPr(); + link("t/dep", "../node_modules/evilpkg"); + commitAll("implement: link a not-committed package folder"); + expect(gitOk("cat-file", "-e", "HEAD:node_modules/evilpkg")).toBe(false); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expectSymlinkViolation(out, "t/dep", "../node_modules/evilpkg"); + expect(out.symlinks).toContainEqual({ file: "t/dep", target: "../node_modules/evilpkg" }); +}); + +test("[REQ-SYMLINK-1] link with absolute target /tmp/x is a violation", () => { + startPr(); + link("t/abs", "/tmp/x"); + commitAll("implement: absolute link"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "t/abs", "/tmp/x"); +}); + +test("[REQ-SYMLINK-1] link with an absolute target that points at a regular file of this very checkout is still a violation", () => { + startPr(); + const target = join(repo, "README.md"); // resolves on disk to a regular file inside the checkout + link("t/abs-readme", target); + commitAll("implement: absolute link into the checkout"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "t/abs-readme", target); +}); + +test("[REQ-SYMLINK-1] absolute target /README.md from the repo root is a violation, although README.md exists in HEAD (absolute is never joined)", () => { + startPr(); + link("abs-root", "/README.md"); // joined naively with the link's dir it would be README.md, a regular file in HEAD + commitAll("implement: absolute link that a naive join would resolve into the repo"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "abs-root", "/README.md"); +}); + +test("[REQ-SYMLINK-1] link with target ../../außerhalb (beyond the repo root) is a violation", () => { + startPr(); + link("t/out", "../../außerhalb"); + commitAll("implement: link outside the repo"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "t/out", "../../außerhalb"); +}); + +test("[REQ-SYMLINK-1] link that leaves the root and comes back (..//README.md) is a violation (not in the repo)", () => { + startPr(); + const target = `../${basename(repo)}/README.md`; + link("up", target); + commitAll("implement: link out and back in"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "up", target); +}); + +for (const [file, target] of [ + ["t/self", "."], + ["t/r", ".."], + ["r", "."], +] as const) { + test(`[REQ-SYMLINK-1] link ${file} -> ${target} (a directory / the repo root) is a violation`, () => { + startPr(); + put("t/keep.txt", "x\n"); + link(file, target); + commitAll("implement: link to . or the root"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), file, target); + }); +} + +test("[REQ-SYMLINK-1] link to a link (in base) that points to a regular file is a violation (chains are not followed)", () => { + put("data/a.txt", "payload\n"); + link("data/l1", "a.txt"); + commitAll("base: file and a link to it"); + startPr(); + link("data/l2", "l1"); + commitAll("implement: link to the link"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expectSymlinkViolation(out, "data/l2", "l1"); + expect(out.symlinks).toContainEqual({ file: "data/l2", target: "l1" }); +}); + +test("[REQ-SYMLINK-1][REQ-SYMLINK-2] both links new in the PR: m1 -> a.txt allowed, m2 -> m1 a violation", () => { + put("data/a.txt", "payload\n"); + commitAll("base: file"); + startPr(); + link("data/m1", "a.txt"); + link("data/m2", "m1"); + commitAll("implement: chain of two new links"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expectSymlinkViolation(out, "data/m2", "m1"); + expect(violationsFor(out, "data/m1")).toEqual([]); + expect(out.symlinks).toContainEqual({ file: "data/m1", target: "a.txt" }); + expect(out.symlinks).toContainEqual({ file: "data/m2", target: "m1" }); +}); + +test("[REQ-SYMLINK-2] img/a.jpg -> b.jpg (regular file in the same folder) is allowed: exit 0, listed in symlinks", () => { + put("img/b.jpg", "JPEGDATA\n"); + commitAll("base: image"); + startPr(); + link("img/a.jpg", "b.jpg"); + commitAll("implement: placeholder image as a link"); + const r = run(); + expect(r.status).toBe(0); + const out = parse(r); + expect(out.ok).toBe(true); + expect(out.violations).toEqual([]); + expect(out.symlinks).toContainEqual({ file: "img/a.jpg", target: "b.jpg" }); +}); + +test("[REQ-SYMLINK-2] links whose target is a regular file only after normalisation are allowed (target kept literally)", () => { + put("y.txt", "y\n"); + put("sub/keep.txt", "k\n"); + commitAll("base: files"); + startPr(); + link("x", "sub/../y.txt"); + link("t/x", "../y.txt"); + commitAll("implement: links needing normalisation"); + const r = run(); + expect(r.status).toBe(0); + const out = parse(r); + expect(out.violations).toEqual([]); + expect(out.symlinks).toContainEqual({ file: "x", target: "sub/../y.txt" }); + expect(out.symlinks).toContainEqual({ file: "t/x", target: "../y.txt" }); +}); + +test("[REQ-SYMLINK-2] link to a regular file that the PR itself adds is allowed", () => { + startPr(); + put("img/new.jpg", "JPEG\n"); + link("img/alias.jpg", "new.jpg"); + commitAll("implement: new image plus link"); + const r = run(); + expect(r.status).toBe(0); + expect(parse(r).symlinks).toContainEqual({ file: "img/alias.jpg", target: "new.jpg" }); +}); + +test("[REQ-SYMLINK-1] an existing regular file turned into a directory link (type change) is a violation", () => { + put("docs/x", "hello\n"); + commitAll("base: regular file"); + startPr(); + unlinkSync(join(repo, "docs/x")); + link("docs/x", "../cypress"); + commitAll("implement: file becomes a directory link"); + expect(modeOf("docs/x", "main")).toBe("100644"); + expect(modeOf("docs/x")).toBe("120000"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "docs/x", "../cypress"); +}); + +test("[REQ-SYMLINK-1] an existing file link retargeted to a directory is a violation", () => { + put("data/a.txt", "payload\n"); + link("data/l", "a.txt"); + commitAll("base: link to a file"); + startPr(); + unlinkSync(join(repo, "data/l")); + link("data/l", "../cypress"); + commitAll("implement: retarget the link"); + const r = run(); + expect(r.status).toBe(1); + const out = parse(r); + expectSymlinkViolation(out, "data/l", "../cypress"); + expect(out.symlinks).toContainEqual({ file: "data/l", target: "../cypress" }); +}); + +test("[REQ-SYMLINK-1] directory link OUTSIDE the managed scope (scope set, link path unmanaged) is still a violation", () => { + put(".devloop/managed-tests.json", JSON.stringify(["services/**/*.test.ts"]) + "\n"); + commitAll("scope the seam to services"); + startPr("chore/tools"); + link("tools/cy", "../cypress"); + commitAll("chore: link a folder outside the scope"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "tools/cy", "../cypress"); +}); + +test("[REQ-SYMLINK-2] a deleted directory link is allowed (exit 0) and not listed in symlinks", () => { + link("t/cy", "../cypress"); + commitAll("base: legacy directory link"); + startPr(); + git("rm", "-q", "t/cy"); + commit("implement: drop the link"); + const r = run(); + expect(r.status).toBe(0); + const out = parse(r); + expect(out.ok).toBe(true); + expect(out.violations).toEqual([]); + expect(out.symlinks).toEqual([]); +}); + +test("[REQ-SYMLINK-3] the link's blob (its target text) is missing from the object store: exit 1, stderr names path and ref", () => { + put("img/b.jpg", "JPEGDATA\n"); + commitAll("base: image"); + startPr(); + link("img/a.jpg", "b.jpg"); + commitAll("implement: link"); + rmSync(looseObject("HEAD:img/a.jpg")); + // Preconditions: the link blob is unreadable; the diff itself still works (trees only). + expect(gitOk("cat-file", "-e", "HEAD:img/a.jpg")).toBe(false); + expect(git("diff", "--no-renames", "-z", "--name-only", "main...HEAD")).toContain("img/a.jpg"); + const r = run(); + expect(r.status).toBe(1); + expect(r.stdout).not.toMatch(/"ok":\s*true/); + // A read error, not a judged violation: it is reported on stderr with path and ref. + expect(r.stderr).toContain("img/a.jpg"); + expect(r.stderr).toContain("HEAD"); +}); + +test("[REQ-SYMLINK-3] the TARGET file's blob is missing from the object store: exit 1, stderr names the link and the ref", () => { + put("img/b.jpg", "JPEGDATA\n"); + commitAll("base: image"); + startPr(); + link("img/a.jpg", "b.jpg"); + commitAll("implement: link to an existing image"); + rmSync(looseObject("HEAD:img/b.jpg")); + expect(gitOk("cat-file", "-e", "HEAD:img/b.jpg")).toBe(false); + expect(gitOk("cat-file", "-e", "HEAD:img/a.jpg")).toBe(true); // the link's own blob is intact + const r = run(); + expect(r.status).toBe(1); + expect(r.stdout).not.toMatch(/"ok":\s*true/); + expect(r.stderr).toContain("img/a.jpg"); + expect(r.stderr).toContain("HEAD"); +}); + +test("[REQ-SYMLINK-1] link to a submodule (gitlink) is a violation", () => { + put("a.txt", "x\n"); + commitAll("base: file"); + const sha = git("rev-parse", "HEAD").trim(); + git("update-index", "--add", "--cacheinfo", `160000,${sha},sm`); + commit("base: submodule sm"); + expect(modeOf("sm")).toBe("160000"); + startPr(); + link("t/sm-link", "../sm"); + git("add", "t/sm-link"); + commit("implement: link to the submodule"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "t/sm-link", "../sm"); +}); + +test("[REQ-SYMLINK-1] the target is taken literally, not trimmed: 'a.txt ' (trailing space) is missing, a violation", () => { + put("a.txt", "x\n"); + commitAll("base: file"); + startPr(); + link("l", "a.txt "); + commitAll("implement: link with a trailing space"); + const r = run(); + expect(r.status).toBe(1); + expectSymlinkViolation(parse(r), "l", "a.txt "); +}); + +test("[REQ-UNSKIPNEU-4] spec branch with a directory link is a no-op pass (exit 0)", () => { + startPr("devloop/spec/x"); + link("t/cy", "../cypress"); + commitAll("spec PR: directory link"); + const r = run("devloop/spec/x"); + expect(r.status).toBe(0); + const out = parse(r); + expect(out.ok).toBe(true); + expect(out.skipped).toMatch(/spec/i); +}); + +test("[REQ-UNSKIPNEU-4] output keeps every previous field and adds symlinks (empty without changed links)", () => { + startPr(); + put("a.test.ts", UNSKIPPED); + commitAll("implement: activate"); + const r = run(); + expect(r.status).toBe(0); + const out = parse(r) as unknown as Record; + for (const k of ["ok", "base", "managed", "managedSource", "checked", "unmanaged", "violations", "symlinks"]) { + expect(out, k).toHaveProperty(k); + } + expect(out.symlinks).toEqual([]); +}); diff --git a/test/cli/verify-unskip.test.ts b/test/cli/verify-unskip.test.ts index 65a243f..4e10b95 100644 --- a/test/cli/verify-unskip.test.ts +++ b/test/cli/verify-unskip.test.ts @@ -63,11 +63,11 @@ test("on a devloop/spec/* branch verify-unskip is a no-op pass — even when a t }); test("spec PR: a NEW all-skipped test file is allowed (exit 0)", () => { - git("checkout", "-q", "-b", "spec"); + git("checkout", "-q", "-b", "devloop/spec/b"); writeFileSync(join(repo, "b.test.ts"), `import { test, expect } from "vitest";\ntest.skip("REQ-B-1 new", () => { expect(g()).toBe(1); });\n`); git("add", "-A"); commit("spec PR: author new skipped test"); - const r = run(); + const r = run("devloop/spec/b"); expect(r.status).toBe(0); }); diff --git a/test/core/unskip.test.ts b/test/core/unskip.test.ts index a3da776..80613ab 100644 --- a/test/core/unskip.test.ts +++ b/test/core/unskip.test.ts @@ -1,5 +1,5 @@ import { test, expect } from "vitest"; -import { isUnskipOnly, isAllowedTestEdit, hasActiveTest } from "../../src/core/unskip.js"; +import { isUnskipOnly, isAllowedTestEdit } from "../../src/core/unskip.js"; // The seam where the test<->code separation stands or falls (§11 #3): the independent // spec-to-tests station writes the COMPLETE test (skipped); implement may ONLY remove `.skip`. @@ -42,27 +42,10 @@ test("ADDING a .skip (sneaking a test off) is FORBIDDEN", () => { expect(isUnskipOnly(twoTests, next)).toBe(false); }); -// --- hasActiveTest + isAllowedTestEdit (unified rule for spec-PR vs implement-PR) ---------- -test("hasActiveTest distinguishes active test calls from fully-skipped ones", () => { - expect(hasActiveTest(`test("x", () => {})`)).toBe(true); - expect(hasActiveTest(`it("x", () => {})`)).toBe(true); - expect(hasActiveTest(`test.only("x", () => {})`)).toBe(true); - expect(hasActiveTest(`test.each([1])("x", () => {})`)).toBe(true); - expect(hasActiveTest(`test.skip("x", () => {});\nit.skip("y", () => {})`)).toBe(false); - expect(hasActiveTest(`describe.skip("g", () => { it.skip("x", () => {}); })`)).toBe(false); -}); - -test("a NEW test file (old empty) is allowed iff every test is skipped — spec-PR authoring", () => { - const allSkipped = `test.skip("REQ-A-1 a", () => { expect(f()).toBe(1); });\nit.skip("REQ-A-2 b", () => {});`; - expect(isAllowedTestEdit("", allSkipped)).toBe(true); -}); - -test("a NEW test file with any active test is FORBIDDEN (no secretly-active tests land green)", () => { - const oneActive = `test.skip("REQ-A-1 a", () => {});\ntest("REQ-A-2 active", () => { expect(1).toBe(1); });`; - expect(isAllowedTestEdit("", oneActive)).toBe(false); - expect(isAllowedTestEdit("", `test.only("focus", () => {})`)).toBe(false); -}); - +// --- isAllowedTestEdit --------------------------------------------------------------------- +// #21 (REQ-NEWTEST-1): hasActiveTest and the "new file" branch are gone — a NEW managed test file +// outside devloop/spec/* is a violation whatever it contains; that is decided by existence in +// verify-unskip and tested there (test/cli/verify-unskip-neue-tests-symlinks.test.ts), not here. test("an EXISTING test file still follows unskip-only (implement PR)", () => { expect(isAllowedTestEdit(OLD, OLD.replace("test.skip(", "test("))).toBe(true); // skip removed expect(isAllowedTestEdit(OLD, OLD.replace("toBe(42)", "toBe(0)"))).toBe(false); // assertion edited