diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 46971b6..49f53b1 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.8.1", + "version": "0.9.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/README.md b/README.md index e5c87a4..40d9e0d 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ fail-closed CI-Required-Check und GitHub-Branch-Protection. - `/devloop:spec-to-twin` — *(optional, `.devloop` `twin.enabled`)* unabhängiges Verhaltens-Orakel (triviales Referenzmodell + REQ-getaggte Invarianten + fast-check model-based) aus Domänen-Wahrheiten — Korrektheit statt nur Spec-Treue - `/devloop:implement` — konsumiert Spec+Tests, öffnet PR (schreibt Spec/Tests nicht selbst) - `/devloop:critic` — adversarial, frischer Kontext, strukturiertes Verdikt +- `/devloop:smoke` — *(optional, `.devloop` `smoke.tiers`)* Smoke gegen einen lokalen Stack auf dem PR-Stand: erst die Konsumenten des geänderten Pfads belegen, dann Browser/API/CLI, Wirkung vorher/nachher messen; liefert die Abnahme-Anleitung für den Menschen - `/devloop:loop` — der Driver (orchestriert die Stationen als isolierte Subagenten) - `/devloop:init` — verdrahtet den CI-Bindungs-Anker in ein Ziel-Repo - `/devloop:cleanup` — räumt lokale, im Remote gemergte Branches + ihre Worktrees sicher auf diff --git a/USAGE.md b/USAGE.md index 31040fd..b30ddb5 100644 --- a/USAGE.md +++ b/USAGE.md @@ -117,6 +117,16 @@ Was passiert (Spec-PR-zuerst; der Driver gehorcht dem getesteten Kern, trifft ni `devloop-precondition-check`, `verify-unskip`, Tier aus dem Diff. Rot → Defektsignal über `gh`-Rückkanal → neue `implement`-Runde (Rückkante, Max-Iter + Eskalation). 9. **critic** (eigener Subagent, adversarial) → strukturiertes Verdikt. + - *(optional, nur für Tiers in `.devloop` `smoke.tiers`)* **smoke** (eigener Subagent, ändert + nichts am Repo) nach einem akzeptierten Verdikt, **vor** `MARK_READY`: ermittelt, **wer** den + geänderten Pfad aufruft (mit `datei:zeile`), wählt danach Browser, API (echte Tokens) oder CLI, + baut den lokalen Stack nach `smoke.setup` auf dem PR-Stand auf und misst je Fall die Wirkung + vorher/nachher. Ergebnis leitet `smoke-verdict` ab (`failed` → Rückkante, `not-run` → ein + Neustart, dann Eskalation). Bericht + **Abnahme-Anleitung** kommen als PR-Kommentar; der Stack + bleibt für deine Abnahme laufen. Ersetzt sie nicht: Ob die Intention erreicht ist, prüft ein Mensch. + **Grenzen** (nicht maschinell prüfbar, nur per Prompt und deinem Blick auf den Bericht): dass + `effect` wirklich mehr als ein HTTP-Status ist, dass `not-applicable` stimmt, und dass die + Station den Arbeitsbaum nicht verändert hat. 10. **Merge je Tier:** T0/T1 Auto-Merge bei grün · T2 required Reviewer · **▣ STOPP: T3-Merge**. > **Zwei PRs, zwei Mensch-Tore:** der **Spec-PR** (Schritt 5, Spec-Review §5.1) und der @@ -185,7 +195,7 @@ Stand gebunden. ## 4. Einzelne Stationen ohne Orchestrierung Jede Station gibt es auch als Einzel-Skill (ohne die harten Stopps), z.B. zum Üben: -`/devloop:specify`, `/devloop:spec-to-tests`, `/devloop:spec-to-twin` *(optional)*, `/devloop:implement`, `/devloop:critic`. +`/devloop:specify`, `/devloop:spec-to-tests`, `/devloop:spec-to-twin` *(optional)*, `/devloop:implement`, `/devloop:critic`, `/devloop:smoke` *(optional)*. Für den echten, abgesicherten Lauf nimm `/devloop:loop`. --- diff --git a/agents/devloop-smoke.md b/agents/devloop-smoke.md new file mode 100644 index 0000000..9baefb0 --- /dev/null +++ b/agents/devloop-smoke.md @@ -0,0 +1,61 @@ +--- +name: devloop-smoke +description: Fährt den Smoke gegen einen LOKALEN Stack auf dem PR-Stand — auf dem echten Konsumentenpfad (Browser, API oder CLI, je nachdem, wer den geänderten Pfad aufruft) und mit beobachteter Wirkung, nicht nur Status. Liefert einen maschinenlesbaren Bericht plus eine Abnahme-Anleitung für den Menschen. Läuft nach einem akzeptierten Critic-Verdikt, vor MARK_READY; nur für Tiers, die das Ziel-Repo einschaltet. Ändert keinen Repo-Inhalt. +tools: Read, Glob, Grep, Bash +--- + +# Station: smoke + +Du belegst, dass die Änderung **auf dem Weg wirkt, auf dem sie benutzt wird**. Tests und Kritiker haben geprüft, ob der Code die Spec erfüllt. Du prüfst, ob das Gebaute im laufenden System das Verhalten zeigt, das die Spec verspricht. Du ersetzt **nicht** die Abnahme durch den Menschen: Ob die Intention erreicht ist, entscheidet am Ende ein Mensch. Du bereitest ihm diese Abnahme vor. + +## Eingaben + +- `spec.md` des Features, besonders den Abschnitt **„Smoke“** (Abnahme-Fälle aus Nutzersicht). +- Der PR-Diff (`git diff ...HEAD`). +- Die Aufbau-Anleitung des Ziel-Repos: `.devloop/config.json` → `smoke.setup` (Pfad zu einer Datei im Repo, die beschreibt, wie der lokale Stack startet, wie Testkonten entstehen und wie man abräumt). Fehlt sie: Bericht mit `setup.ok: false` und dem Grund in `setup.steps` — nicht improvisieren. + +## Vorgehen + +1. **Konsumenten ermitteln — zuerst, immer.** Für jeden geänderten Pfad (Endpunkt, Komponente, Job, Event): Wer ruft ihn tatsächlich auf? Belege mit `datei:zeile` (grep nach Pfad, Client-Funktion, Tool-Name). Typische Falle: Die Oberfläche benutzt einen *anderen* Endpunkt als den geänderten — dann ist ein Klicktest grün, ohne die Änderung zu berühren. +2. **Modus pro Fall wählen**, abgeleitet aus Schritt 1: + - `browser` — die Oberfläche ruft den Pfad auf: durchklicken (Playwright headless über die E2E-Werkzeuge des Repos, Screenshots als Beleg). + - `api` — nur Clients ohne Oberfläche (MCP, andere Dienste, externe Integrationen): echte Anfragen durch das Gateway mit **echten Tokens** aus dem lokalen Identity-Provider, keine selbst signierten. + - `cli` / `other` — Jobs, Konsumenten von Events usw. + Kein Laufzeitkonsument (reine Doku, Testcode, Build-Konfiguration): `cases: []` und `notApplicable` mit Begründung — die Konsumenten-Analyse muss trotzdem drinstehen. +3. **Stack aufbauen** nach `smoke.setup`, auf dem **PR-Stand** (eigener, abgekoppelter Worktree des PR-HEAD). Eigene, eindeutig benannte Testkonten anlegen. **Nur lokal:** keine Produktions-URLs, keine echten Zugangsdaten, keine geteilten Umgebungen. +4. **Fälle fahren.** Je Fall: Zustand **vorher** messen → Aktion → Zustand **nachher** messen. `effect` ist der Wirkungsbeleg (DB-Zeile, gespeicherte Datei, gerenderter Inhalt, ausgelöstes Event) — ein HTTP-Status allein ist kein Smoke. Fälle aus der Spec abdecken; dazu die Gegenfälle, die geschlossen bleiben müssen (ohne Token, falsche Rolle, gefälschte Header). +5. **Abnahme-Anleitung schreiben** (`abnahme`, Markdown): kurze, kopierbare Schritte, mit denen der Mensch dieselben Fälle **selbst** am laufenden Stack prüfen kann — woran er Erfolg erkennt, welche Testkonten es gibt. Das ist das wichtigste Ergebnis für den Menschen. +6. **Stack laufen lassen** für die Abnahme des Menschen. In `cleanup` die Befehle zum Abräumen (Container, Prozesse, Testkonten, Worktree). + +## Grenzen + +- **Kein Repo-Inhalt wird geändert**: kein Produktcode, keine Tests, keine Spec. Hilfsskripte nur unter `$TMPDIR`. +- Ein roter Fall ist ein Befund, kein Anlass, etwas „hinzubiegen“. Melde ihn mit `pass: false` und dem Beobachteten. +- Scheitert der Aufbau, ist das `setup.ok: false` — **nicht** ein roter Fall. Dasselbe gilt, wenn die Infrastruktur **während** der Fälle wegbricht (Container stirbt, Port weg): dann `setup.ok: false` mit dem Grund, nicht `pass: false`. Die Kette unterscheidet „Code falsch“ (Rückkante) von „Smoke lief nicht“ (Neustart, dann Eskalation). +- Nie Werte ausgeben, die Geheimnisse sind (Tokens, Client-Secrets) — auch nicht im Bericht. + +## Output: Bericht (letzte Nachricht, ein JSON-Objekt) + +Genau **ein** Objekt mit `cases` in der ganzen Nachricht — das Beispiel unten nicht mit ausgeben. Zwei solche Objekte gelten als mehrdeutig (`not-run`). + +```json +{ + "consumers": [ + { "changed": "PATCH /api/boardgames/{id}/versions/{vid}", "caller": "wuerfelgeist-mcp update_version", "evidence": "services/wuerfelgeist-mcp/src/domain/versions/VersionsClient.ts:42" } + ], + "setup": { "ok": true, "steps": ["infra gestartet", "Gateway aus PR-HEAD", "Testkonten smoke-user, smoke-mod"] }, + "cases": [ + { "id": "user-patch", "req": "REQ-X-1", "mode": "api", + "action": "PATCH notes als user", + "expected": "pending Contribution, Version unverändert", + "observed": "HTTP 200, contributions 37 -> 38 (pending)", + "effect": "versions.notes vorher = nachher; contributions.status = pending", + "pass": true } + ], + "notApplicable": null, + "abnahme": "## Abnahme\n1. ...", + "cleanup": ["docker rm -f ...", "..."] +} +``` + +Das Ergebnis (`passed` / `failed` / `not-applicable` / `not-run`) leitet der Orchestrator mit `smoke-verdict` aus diesem Bericht **ab**. Ein eigenes Status-Label zählt nicht. Ungültig ist ein Bericht u. a. ohne `effect` je Fall, ohne Konsumenten-Analyse, ohne Abnahme-Anleitung, oder mit `setup.ok: false` — er gilt dann als `not-run`. diff --git a/agents/devloop-specify.md b/agents/devloop-specify.md index f45de76..15d0795 100644 --- a/agents/devloop-specify.md +++ b/agents/devloop-specify.md @@ -19,6 +19,7 @@ Du erzeugst die **`spec.md`** — die Wurzel des Vertrauens (§5.1). Alles Spät ``` (Liegt die Map an einem ungewöhnlichen Ort, alternativ `{"touched":[...],"tierMap":}` durchreichen.) Schreibe das Ergebnis als `Tier:`-Feld in die `spec.md`. **Achtung:** dieses Tier ist **vorläufig/advisorisch** — es steuert nur Critic-Tiefe und Stopp-Strenge in der inneren Schleife. **Autoritativ** wird das Tier **aus dem tatsächlichen Diff auf CI** berechnet (§9/§10, derselbe `derive-tier` server-seitig), nie aus deiner Deklaration. Du kannst das Tier also nicht herunterspielen. 3. Schreibe `spec.md` (User Story, Tier, Liste der `REQ-`-Kriterien mit EARS-Typ-Tag). +4. Schreibe einen Abschnitt **`## Smoke`**: die Abnahme-Fälle aus **Nutzersicht** (wer tut was über welchen Weg, was muss danach sichtbar/gespeichert sein), inkl. der Gegenfälle, die geschlossen bleiben müssen. Getrennt davon **„Nach dem Deploy“**: was nur in Produktion nachweisbar ist (echte Konten, echte Konfiguration). Benenne, **wer den geänderten Pfad aufruft** (Oberfläche, MCP, anderer Dienst) — nachgesehen, mit `datei:zeile`, nicht angenommen. Die `smoke`-Station und der Mensch an der Abnahme arbeiten damit; der Abschnitt ist kein `REQ-`-Kriterium und erzeugt keine Tests. ## Spec-Änderung (Amend-Modus) diff --git a/dist/cli/smoke-tiers.js b/dist/cli/smoke-tiers.js new file mode 100644 index 0000000..16d8e05 --- /dev/null +++ b/dist/cli/smoke-tiers.js @@ -0,0 +1,25 @@ +// CLI: print the smoke-enabled tiers of a repo (.devloop/config.json -> smoke.tiers) as JSON. +// Usage: smoke-tiers . Missing config/section -> []. Malformed -> exit 1 (fail closed: +// a typo must not silently switch the smoke gate off). +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { readSmokeTiers } from "../core/smoke.js"; +const repo = process.argv[2] ?? "."; +let config; +try { + config = JSON.parse(readFileSync(join(repo, ".devloop", "config.json"), "utf8")); +} +catch (e) { + if (e.code === "ENOENT") + config = undefined; + else { + process.stderr.write("smoke-tiers: .devloop/config.json unlesbar; refusing to guess (fail-closed)\n"); + process.exit(1); + } +} +const tiers = readSmokeTiers(config); +if (tiers === undefined) { + process.stderr.write("smoke-tiers: smoke.tiers ungültig (erlaubt: T0..T3); refusing to guess (fail-closed)\n"); + process.exit(1); +} +process.stdout.write(JSON.stringify(tiers) + "\n"); diff --git a/dist/cli/smoke-verdict.js b/dist/cli/smoke-verdict.js new file mode 100644 index 0000000..cf5b1f4 --- /dev/null +++ b/dist/cli/smoke-verdict.js @@ -0,0 +1,21 @@ +// CLI: raw smoke report -> DERIVED smoke result for the DriverState (REQ-SMOKE-2/3). +// stdin: { rawOutput: string, retried?: boolean }. Any `status` in the input or in the report is +// ignored — the status comes from validating the report (see core/smoke.ts). +// stdout: { smoke: DriverState["smoke"], failedCases, abnahme, notApplicable } +import { parseSmokeReport } from "../core/smoke.js"; +import { readStdin } from "./_stdin.js"; +let input = {}; +try { + input = JSON.parse(await readStdin()); +} +catch { + /* unparseable input -> not-run below */ +} +const run = parseSmokeReport(typeof input.rawOutput === "string" ? input.rawOutput : ""); +const smoke = run.status === "not-run" ? { status: "not-run", retried: input.retried === true } : { status: run.status }; +process.stdout.write(JSON.stringify({ + smoke, + failedCases: run.failedCases, + abnahme: run.abnahme, + notApplicable: run.notApplicable, +}) + "\n"); diff --git a/dist/core/driver.js b/dist/core/driver.js index b64c321..b2b817d 100644 --- a/dist/core/driver.js +++ b/dist/core/driver.js @@ -20,7 +20,37 @@ // "completed" critic round: MARK_READY (draft -> ready, which arms auto-merge) only comes // from critiqued + completed + accepted; merge-pending without ready === true goes back to // the critic; a not-run critic is retried once, then ESCALATE (never read as "no findings"). +// 8. (REQ-SMOKE-1..4) Where the repo opts a tier into the smoke station (.devloop smoke.tiers), +// MARK_READY additionally requires a DERIVED smoke result "passed" or "not-applicable" — +// produced by the smoke-verdict CLI, never by the station's own label. "failed" is a defect +// signal (back-edge), "not-run" is retried once, then ESCALATE. Tiers not opted in: unchanged. import { nextLoopDecision } from "./loop.js"; +function smokeRequired(state) { + return (state.smokeTiers ?? []).includes(state.tier); +} +// Invariant 8: the smoke gate in front of MARK_READY (only for opted-in tiers). +function smokeGate(state) { + if (!smokeRequired(state)) + return undefined; + const s = state.smoke; + if (!s) + return { kind: "SPAWN_STATION", station: "smoke" }; + switch (s.status) { + case "passed": + case "not-applicable": + return undefined; + case "failed": + return handleRedGate(state); // observed wrong effect = defect signal -> back-edge + case "not-run": + // Setup broke / report unparseable: one restart, then escalate — never read as "passed". + return s.retried + ? { kind: "ESCALATE", reason: "smoke-not-run" } + : { kind: "SPAWN_STATION", station: "smoke" }; + default: + // Anything not produced by smoke-verdict (typo, hand-written label) is fail-closed. + return { kind: "ESCALATE", reason: "smoke-invalid-state" }; + } +} function handleRedGate(state) { if (!state.loop || !state.loopParams) { return { kind: "ESCALATE", reason: "loop-params-required" }; @@ -112,8 +142,12 @@ export function nextAction(state) { } if (c.verdict === "rejected") return handleRedGate(state); // back-edge via nextLoopDecision - // accepted: mark ready first (arms auto-merge), then behave like merge-pending. - return state.ready === true ? handleReady(state) : { kind: "MARK_READY" }; + // accepted: mark ready first (arms auto-merge), then behave like merge-pending. `ready` must + // mirror GitHub: the executor resets it to false on RE_GEN with markDraft, so new code after a + // human back-edge passes the smoke gate again before MARK_READY. + if (state.ready === true) + return handleReady(state); + return smokeGate(state) ?? { kind: "MARK_READY" }; } case "merge-pending": // Invariant 7: merge-pending is only legitimate for a ready PR (= accepted critic round). diff --git a/dist/core/init.js b/dist/core/init.js index ad942b2..23e7201 100644 --- a/dist/core/init.js +++ b/dist/core/init.js @@ -74,8 +74,10 @@ export function initRepo(targetRepo, ciTemplate, opts = {}) { // hook defers to CI instead of demanding the (anchor-a) local token. // anchor: CI is authoritative (b). twin: the optional spec-to-twin station, disabled by default // (discoverable here; core stays schlank). Enable via twin.enabled=true + twin.area (the protected - // oracle path, e.g. "services/foo/twin") — see the spec-to-twin station. - writeIfAbsent(".devloop/config.json", JSON.stringify({ anchor: "b", twin: { enabled: false } }, null, 2) + "\n"); + // oracle path, e.g. "services/foo/twin") — see the spec-to-twin station. smoke: the optional + // smoke station, off by default (tiers: []); enable per tier + point `setup` at a repo doc that + // says how to start the local stack and create test accounts — see the smoke station. + writeIfAbsent(".devloop/config.json", JSON.stringify({ anchor: "b", twin: { enabled: false }, smoke: { tiers: [], setup: null } }, null, 2) + "\n"); // Tier-map: NEVER shadow an existing one. resolveTierMapPath prefers .devloop/, so writing a // default there would silently override a repo's own tools/tier-map.json -> gate regression. const existingTierMap = resolveTierMapPath(targetRepo); diff --git a/dist/core/smoke.js b/dist/core/smoke.js new file mode 100644 index 0000000..67b3f36 --- /dev/null +++ b/dist/core/smoke.js @@ -0,0 +1,165 @@ +// Smoke report parsing (REQ-SMOKE-2/3). The status is DERIVED from validating the station's raw +// report — never taken from a label the station (or the caller) supplies. Anything that does not +// validate is "not-run", never "passed". +// +// A smoke case is only valid with an observed EFFECT (state before/after on the real consumer +// path, e.g. a DB row, a rendered page, a stored file) — a bare HTTP status is not a smoke. +export const SMOKE_MODES = ["browser", "api", "cli", "other"]; +const NOT_RUN = { + status: "not-run", + cases: [], + failedCases: [], + consumers: [], + notApplicable: null, + abnahme: null, +}; +const nonEmpty = (x) => typeof x === "string" && x.trim() !== ""; +// End index (exclusive) of the balanced JSON object starting at `start`, string-aware; -1 if none. +function objectEnd(s, start) { + let depth = 0; + let inStr = false; + for (let i = start; i < s.length; i++) { + const c = s[i]; + if (inStr) { + if (c === "\\") + i++; + else if (c === '"') + inStr = false; + } + else if (c === '"') + inStr = true; + else if (c === "{") + depth++; + else if (c === "}" && --depth === 0) + return i + 1; + } + return -1; +} +// THE top-level JSON object in the text that has a `cases` field. More than one such object (a +// quoted schema example, an earlier run printed alongside) is ambiguous -> undefined (not-run): +// picking the first would let a green example mask a red real report. +function findReport(raw) { + const found = []; + let i = raw.indexOf("{"); + while (i !== -1) { + const end = objectEnd(raw, i); + if (end !== -1) { + try { + const v = JSON.parse(raw.slice(i, end)); + if (v && typeof v === "object" && !Array.isArray(v)) { + if ("cases" in v) + found.push(v); + i = raw.indexOf("{", end); + continue; + } + } + catch { + /* not JSON -> next brace */ + } + } + i = raw.indexOf("{", i + 1); + } + return found.length === 1 ? found[0] : undefined; +} +const TIERS = ["T0", "T1", "T2", "T3"]; +// `.devloop/config.json` -> smoke.tiers. Absent config / absent `smoke` / absent `tiers` -> [] (off). +// Present but malformed -> undefined: the caller must fail closed (refuse), never read it as "off". +export function readSmokeTiers(config) { + if (config === undefined || config === null) + return []; + if (typeof config !== "object" || Array.isArray(config)) + return undefined; + const smoke = config.smoke; + if (smoke === undefined) + return []; + if (!smoke || typeof smoke !== "object" || Array.isArray(smoke)) + return undefined; + const tiers = smoke.tiers; + if (tiers === undefined) + return []; + if (!Array.isArray(tiers)) + return undefined; + if (!tiers.every((t) => typeof t === "string" && TIERS.includes(t))) + return undefined; + return [...new Set(tiers)]; +} +function toConsumer(x) { + if (!x || typeof x !== "object") + return undefined; + const c = x; + if (!nonEmpty(c.changed) || !nonEmpty(c.caller) || !nonEmpty(c.evidence)) + return undefined; + return { changed: c.changed, caller: c.caller, evidence: c.evidence }; +} +function toCase(x) { + if (!x || typeof x !== "object") + return undefined; + const c = x; + if (!nonEmpty(c.id) || !nonEmpty(c.action) || !nonEmpty(c.expected)) + return undefined; + if (!nonEmpty(c.observed) || !nonEmpty(c.effect)) + return undefined; + if (typeof c.pass !== "boolean") + return undefined; + if (typeof c.mode !== "string" || !SMOKE_MODES.includes(c.mode)) + return undefined; + if (c.req !== null && c.req !== undefined && typeof c.req !== "string") + return undefined; + return { + id: c.id, + req: typeof c.req === "string" ? c.req : null, + mode: c.mode, + action: c.action, + expected: c.expected, + observed: c.observed, + effect: c.effect, + pass: c.pass, + }; +} +export function parseSmokeReport(raw) { + const r = findReport(raw); + if (!r || !Array.isArray(r.cases) || !Array.isArray(r.consumers)) + return NOT_RUN; + const setup = r.setup; + if (!setup || typeof setup !== "object" || setup.ok !== true) + return NOT_RUN; // stack never stood + const consumers = []; + for (const x of r.consumers) { + const c = toConsumer(x); + if (!c) + return NOT_RUN; + consumers.push(c); + } + const cases = []; + for (const x of r.cases) { + const c = toCase(x); + if (!c) + return NOT_RUN; + cases.push(c); + } + if (new Set(cases.map((c) => c.id)).size !== cases.length) + return NOT_RUN; + const notApplicable = nonEmpty(r.notApplicable) ? r.notApplicable : null; + const abnahme = nonEmpty(r.abnahme) ? r.abnahme : null; + if (cases.length === 0) { + // "Nothing to smoke" must be argued: a reason AND the consumer analysis it rests on. + if (notApplicable === null || consumers.length === 0) + return NOT_RUN; + return { status: "not-applicable", cases, failedCases: [], consumers, notApplicable, abnahme }; + } + if (notApplicable !== null) + return NOT_RUN; // contradictory: cases ran but "not applicable" + if (abnahme === null) + return NOT_RUN; // the human's acceptance guide is part of the deliverable + if (consumers.length === 0) + return NOT_RUN; // no consumer analysis -> mode choice unfounded + const failedCases = cases.filter((c) => !c.pass).map((c) => c.id); + return { + status: failedCases.length > 0 ? "failed" : "passed", + cases, + failedCases, + consumers, + notApplicable: null, + abnahme, + }; +} diff --git a/package.json b/package.json index 8af5096..b01ea46 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "devloop", - "version": "0.8.1", + "version": "0.9.0", "private": true, "type": "module", "license": "MIT", diff --git a/skills/loop/SKILL.md b/skills/loop/SKILL.md index 4e8a57e..d3bfd05 100644 --- a/skills/loop/SKILL.md +++ b/skills/loop/SKILL.md @@ -1,6 +1,6 @@ --- name: loop -description: Driver der agentischen Dev-Loop-Kette. Orchestriert die Stationen specify→spec-to-tests→implement→critic als ISOLIERTE Subagenten mit frischem Kontext, hält an den zwei harten Mensch-Stopps (Spec-Review, T3-Merge) und führt die Rückkante mit Eskalation. Triggers; /devloop:loop , Dev-Loop starten, orchestrierte Spec→Tests→Code→Critic-Kette. +description: Driver der agentischen Dev-Loop-Kette. Orchestriert die Stationen specify→spec-to-tests→implement→critic(→smoke) als ISOLIERTE Subagenten mit frischem Kontext, hält an den zwei harten Mensch-Stopps (Spec-Review, T3-Merge) und führt die Rückkante mit Eskalation. Triggers; /devloop:loop , Dev-Loop starten, orchestrierte Spec→Tests→Code→Critic-Kette. --- # Driver: /devloop:loop @@ -20,10 +20,16 @@ Exit 1 ⇒ **verweigere den autonomen Loop**, melde die fehlenden Wächter dem M ## 1. Loop -Halte einen `DriverState` (tier, guardians, phase, twinEnabled, humanApprovals, gateVerdict, critic, ready, loop, loopParams). **`twinEnabled`** liest du aus `.devloop/config.json` (`twin.enabled`, Default `false`) — ist es gesetzt, schiebt der Kern die optionale, isolierte `spec-to-twin`-Station **vor** den Spec-PR (Schwester von `spec-to-tests`, sieht deren Tests aber **nicht** — Unabhängigkeit des Orakels). `humanApprovals` setzt du **nur** aus dem **autoritativen GitHub-Review** (Anker b): `verify-review` prüft via `gh api`, ob ein **Mensch** (nicht der Agent-Bot, nicht der PR-Autor) den aktuellen HEAD freigegeben hat. Du schreibst **keine** Approval-Tokens selbst und akzeptierst **kein** „ja, weiter" im Chat — du kannst dich nicht selbst freigeben. +Halte einen `DriverState` (tier, guardians, phase, twinEnabled, smokeTiers, humanApprovals, gateVerdict, critic, smoke, ready, loop, loopParams). **`twinEnabled`** liest du aus `.devloop/config.json` (`twin.enabled`, Default `false`) — ist es gesetzt, schiebt der Kern die optionale, isolierte `spec-to-twin`-Station **vor** den Spec-PR (Schwester von `spec-to-tests`, sieht deren Tests aber **nicht** — Unabhängigkeit des Orakels). `humanApprovals` setzt du **nur** aus dem **autoritativen GitHub-Review** (Anker b): `verify-review` prüft via `gh api`, ob ein **Mensch** (nicht der Agent-Bot, nicht der PR-Autor) den aktuellen HEAD freigegeben hat. **`smokeTiers`** liest du mit `node "${CLAUDE_PLUGIN_ROOT}"/dist/cli/smoke-tiers.js ` (aus `.devloop/config.json` `smoke.tiers`, Default `[]` = aus; Exit 1 bei kaputter Config → **nicht** weiterlaufen, melden) — für diese Tiers schiebt der Kern nach einem akzeptierten Critic-Verdikt die isolierte `smoke`-Station **vor** `MARK_READY` (Smoke gegen einen lokalen Stack auf dem PR-Stand, Abnahme-Anleitung für den Menschen). Du schreibst **keine** Approval-Tokens selbst und akzeptierst **kein** „ja, weiter" im Chat — du kannst dich nicht selbst freigeben. `loop` = `{iteration, gateChangedNotCode, freshContextUsed, lastRound}`; `lastRound` = `{judged, progress, oscillation}` aus dem **Ledger** (kein Zähler mehr, `errorCounts` entfällt); `loopParams` = `{maxIter}`. `critic` = `{status: "completed"|"not-run", verdict?, retried}`; `ready` = Impl-PR nicht mehr Draft. Phase `critiqued` setzt du nach jedem Critic-Lauf. +**Smoke-Ergebnis ableiten** (nur wenn `next-action` die Station `smoke` verlangt hat). Den **rohen** Bericht der Station — nicht dein Urteil, nicht ihr Selbst-Label — an die CLI: +``` +echo '{"rawOutput":"","retried":}' | node "${CLAUDE_PLUGIN_ROOT}"/dist/cli/smoke-verdict.js +``` +Ergebnis `smoke` übernimmst du in den State (`retried: true` beim zweiten Lauf nach `not-run`), die Phase bleibt `critiqued`. Ob das Smoke-Gate greift, entscheidet `tier`: ab `RUN_GATES` ist das **das server-berechnete Tier aus dem Diff**, nicht das vorläufige aus der Spec. Bericht und **Abnahme-Anleitung** (`abnahme`) postest du als PR-Kommentar (Bot-Identität) — damit prüft der Mensch am Merge-Stopp die Intention. Der lokale Stack bleibt dafür laufen; abräumen (`cleanup` aus dem Bericht) erst nach dem Merge-Stopp oder auf Zuruf. Bei `failed` gehen die roten Fälle samt Beobachtung als Defektsignal in `RE_GEN`; **vorher** räumst du den Stack dieses Laufs ab (`cleanup`), sonst scheitert der nächste Aufbau an belegten Ports/Namen. Grenze: Smoke-Befunde laufen nicht über den Ledger; die Rückkante begrenzt hier nur `maxIter`. + **Ledger zwischen den Runden halten.** Nach jedem Critic-Lauf gibst du dessen **rohe** Ausgabe(n) (bei T2/T3 alle Instanzen) — nicht dein Urteil, nicht ihr Selbst-Label — an die CLI (REQ-CRITIC-1): ``` echo '{"rawOutputs":["",...],"ledger":,"addressed":["",...]}' | node "${CLAUDE_PLUGIN_ROOT}"/dist/cli/critic-verdict.js @@ -48,13 +54,13 @@ echo '' | node "${CLAUDE_PLUGIN_ROOT}"/dist/cli/next-action.js | `RUN_GATES` | Gates auf dem **geschützten Runner** (CI = Gate of Record) triggern; **Verdikt nur von dort** (§5#1), inkl. `devloop-precondition-check`, Protected-Set-Ratchet und **server-berechnetem Tier aus dem Diff** (nicht agent-deklariert, §9). Fehler-Logs über den schmalen Rückkanal lesen (`gh pr checks`, `gh run view --log-failed`). | | `STOP_FOR_HUMAN` | **Turn beenden.** Übergib Kontext an den Menschen und warte. Bei `STOP_FOR_HUMAN` und `ESCALATE` schreibst du vorher den Ledger als Tabelle in den PR (`renderLedgerTable`, REQ-LEDGER-10; offene blocker/major oben, `fixed-claimed` als „behoben (unverifiziert)") per `gh pr comment`. Der Stopp gilt erst als passiert, wenn ein **Mensch per GitHub-PR-Review** (CODEOWNERS) den aktuellen Stand freigibt — verifiziert durch `verify-review` auf CI (Anker b). T3-Merge ist zusätzlich durch Branch-Protection erzwungen. **Nicht** du gibst frei. | | `MARK_READY` | Critic hat (abgeleitet) akzeptiert → `gh pr ready ` (REQ-BIND-2); armiert bei T0/T1 den Auto-Merge. Danach `ready: true` setzen. Impl-PRs sind bis hierhin **Draft**. | -| `RE_GEN` | Defektsignal (Datei:Zeile:Regel / überlebende Mutante / offene Critic-Befunde) in eine neue `implement`-Runde geben — als **Signal, nicht Lösung**; `implement` meldet je adressiertem Befund Key + `datei:zeile`. Bei `freshContext:true` neue isolierte Instanz. Bei `markDraft:true` **vor** dem nächsten Push `gh pr ready --undo` (REQ-BIND-3). | -| `ESCALATE` | Sauberer Stopp + Kontext-Übergabe an den benannten Owner. Gründe u.a. `ESCALATE_OSCILLATION`, `ESCALATE_STAGNATION`, `critic-not-run` (Critic zweimal ohne gültige Ausgabe). | +| `RE_GEN` | Defektsignal (Datei:Zeile:Regel / überlebende Mutante / offene Critic-Befunde) in eine neue `implement`-Runde geben — als **Signal, nicht Lösung**; `implement` meldet je adressiertem Befund Key + `datei:zeile`. Bei `freshContext:true` neue isolierte Instanz. **`critic` und `smoke` im State löschen** — neuer Code braucht neue Belege. Bei `markDraft:true` außerdem **`ready: false`** setzen (der PR ist wieder Draft; sonst liefe neuer Code am Smoke vorbei zu `DONE`), und **vor** dem nächsten Push `gh pr ready --undo` (REQ-BIND-3). | +| `ESCALATE` | Sauberer Stopp + Kontext-Übergabe an den benannten Owner. Gründe u.a. `ESCALATE_OSCILLATION`, `ESCALATE_STAGNATION`, `critic-not-run` (Critic zweimal ohne gültige Ausgabe), `smoke-not-run` (Smoke zweimal ohne gültigen Bericht oder Stack nicht aufgebaut). | | `DONE` | Fertig (T0/T1 Auto-Merge bei grün; T2/T3 erst nach Mensch-Stopp). | ## Zwei Schleifen (§10 „Wo der Loop läuft") -- **Innere Schleife (Sandbox, Tempo):** `specify→spec-to-tests→implement→critic` lokal, voller Gate-Satz **advisorisch** (vitest/stryker/semgrep), Lichter aus. Kauft Geschwindigkeit, **nicht** Vertrauen. +- **Innere Schleife (Sandbox, Tempo):** `specify→spec-to-tests→implement→critic(→smoke)` lokal, voller Gate-Satz **advisorisch** (vitest/stryker/semgrep), Lichter aus. Kauft Geschwindigkeit, **nicht** Vertrauen. - **Capability-Grenze:** PR/Push auf den **Feature-Branch** (nie main); Egress nur gh-API · git-Remote · Registry; keine echten Secrets. - **Äußere Schleife (CI = Gate of Record):** Gates **autoritativ** re-run; rot → Logs über den Rückkanal → `RE_GEN` innen; grün → Merge je Tier. diff --git a/skills/resume/SKILL.md b/skills/resume/SKILL.md index 9547453..e567e4b 100644 --- a/skills/resume/SKILL.md +++ b/skills/resume/SKILL.md @@ -21,7 +21,7 @@ Branch), nicht im Agenten-Kontext; diese Skill rekonstruiert ihn daraus. mappt sie auf `{phase, humanApprovals, reviewDecision, gateVerdict, ready, done}`. Ein grüner **Draft**-Impl-PR kommt als `gated`/`green` zurück → der Critic läuft (nie direkt `merge-pending`). - `done: true` → der PR ist schon gemergt, nichts zu tun. -3. **Tier** ableiten (`derive-tier --repo`) und mit dem rekonstruierten Teil zum `DriverState` mergen. +3. **Tier** ableiten (`derive-tier --repo`) und **`smokeTiers`** lesen (`node "${CLAUDE_PLUGIN_ROOT}"/dist/cli/smoke-tiers.js `, Exit 1 → nicht weiterlaufen), beides mit dem rekonstruierten Teil zum `DriverState` mergen. Ohne `smokeTiers` liefe ein eingeschaltetes Tier nach dem Critic am Smoke vorbei zu `MARK_READY`. Ein früheres Smoke-Ergebnis wird nicht rekonstruiert: Ein grüner Draft-PR durchläuft Critic **und** Smoke neu. 4. **Weiterlaufen:** `DriverState` an `next-action` geben und die Aktion ausführen — exakt wie im normalen Loop (`/devloop:loop`). Du fährst also mittendrin fort, ohne von vorn zu beginnen. diff --git a/skills/smoke/SKILL.md b/skills/smoke/SKILL.md new file mode 100644 index 0000000..bb8e37f --- /dev/null +++ b/skills/smoke/SKILL.md @@ -0,0 +1,16 @@ +--- +name: smoke +description: Smoke gegen einen lokalen Stack auf dem PR-Stand — Konsumenten des geänderten Pfads ermitteln, passenden Modus wählen (Browser/API/CLI), Wirkung vorher/nachher messen, Abnahme-Anleitung für den Menschen schreiben. Einzelaufruf-Form; im orchestrierten Lauf spawnt /devloop:loop dies als isolierten Subagenten. Triggers; /devloop:smoke, Smoke-Test, lokale Abnahme vorbereiten, Klicktest. +--- + +# /devloop:smoke (Einzelaufruf) + +Standalone-Form. Im orchestrierten Lauf nutze **`/devloop:loop`**. + +Folge `agents/devloop-smoke.md`: erst die Konsumenten des geänderten Pfads mit `datei:zeile` belegen, daraus den Modus je Fall ableiten, den lokalen Stack nach `.devloop/config.json` → `smoke.setup` auf dem PR-Stand aufbauen, je Fall Zustand vorher/nachher messen. Nur lokal, kein Repo-Inhalt wird geändert. Output: JSON-Bericht nach dem Schema in `agents/devloop-smoke.md`; das Ergebnis leitet + +``` +echo '{"rawOutput": ""}' | node "${CLAUDE_PLUGIN_ROOT}"/dist/cli/smoke-verdict.js +``` + +ab — ein Selbst-Label zählt nicht. Die Abnahme-Anleitung (`abnahme`) geht an den Menschen; der Stack bleibt für seine Abnahme laufen. diff --git a/src/cli/smoke-tiers.ts b/src/cli/smoke-tiers.ts new file mode 100644 index 0000000..4fda299 --- /dev/null +++ b/src/cli/smoke-tiers.ts @@ -0,0 +1,25 @@ +// CLI: print the smoke-enabled tiers of a repo (.devloop/config.json -> smoke.tiers) as JSON. +// Usage: smoke-tiers . Missing config/section -> []. Malformed -> exit 1 (fail closed: +// a typo must not silently switch the smoke gate off). + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { readSmokeTiers } from "../core/smoke.js"; + +const repo = process.argv[2] ?? "."; +let config: unknown; +try { + config = JSON.parse(readFileSync(join(repo, ".devloop", "config.json"), "utf8")); +} catch (e) { + if ((e as NodeJS.ErrnoException).code === "ENOENT") config = undefined; + else { + process.stderr.write("smoke-tiers: .devloop/config.json unlesbar; refusing to guess (fail-closed)\n"); + process.exit(1); + } +} +const tiers = readSmokeTiers(config); +if (tiers === undefined) { + process.stderr.write("smoke-tiers: smoke.tiers ungültig (erlaubt: T0..T3); refusing to guess (fail-closed)\n"); + process.exit(1); +} +process.stdout.write(JSON.stringify(tiers) + "\n"); diff --git a/src/cli/smoke-verdict.ts b/src/cli/smoke-verdict.ts new file mode 100644 index 0000000..c3395ba --- /dev/null +++ b/src/cli/smoke-verdict.ts @@ -0,0 +1,27 @@ +// CLI: raw smoke report -> DERIVED smoke result for the DriverState (REQ-SMOKE-2/3). +// stdin: { rawOutput: string, retried?: boolean }. Any `status` in the input or in the report is +// ignored — the status comes from validating the report (see core/smoke.ts). +// stdout: { smoke: DriverState["smoke"], failedCases, abnahme, notApplicable } + +import { parseSmokeReport } from "../core/smoke.js"; +import { readStdin } from "./_stdin.js"; + +let input: { rawOutput?: unknown; retried?: unknown } = {}; +try { + input = JSON.parse(await readStdin()); +} catch { + /* unparseable input -> not-run below */ +} + +const run = parseSmokeReport(typeof input.rawOutput === "string" ? input.rawOutput : ""); +const smoke = + run.status === "not-run" ? { status: "not-run", retried: input.retried === true } : { status: run.status }; + +process.stdout.write( + JSON.stringify({ + smoke, + failedCases: run.failedCases, + abnahme: run.abnahme, + notApplicable: run.notApplicable, + }) + "\n", +); diff --git a/src/core/driver.ts b/src/core/driver.ts index c4518d0..335d37c 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -20,12 +20,16 @@ // "completed" critic round: MARK_READY (draft -> ready, which arms auto-merge) only comes // from critiqued + completed + accepted; merge-pending without ready === true goes back to // the critic; a not-run critic is retried once, then ESCALATE (never read as "no findings"). +// 8. (REQ-SMOKE-1..4) Where the repo opts a tier into the smoke station (.devloop smoke.tiers), +// MARK_READY additionally requires a DERIVED smoke result "passed" or "not-applicable" — +// produced by the smoke-verdict CLI, never by the station's own label. "failed" is a defect +// signal (back-edge), "not-run" is retried once, then ESCALATE. Tiers not opted in: unchanged. import type { Tier } from "./tier.js"; import type { Stop } from "./types.js"; import { nextLoopDecision, type LoopState, type LoopParams } from "./loop.js"; -export type Station = "specify" | "spec-to-tests" | "spec-to-twin" | "implement" | "critic"; +export type Station = "specify" | "spec-to-tests" | "spec-to-twin" | "implement" | "critic" | "smoke"; export type Phase = | "init" @@ -68,10 +72,45 @@ export interface DriverState { | { status: "completed"; verdict: "accepted" | "rejected"; retried: boolean } | { status: "not-run"; retried: boolean }; ready?: boolean; // the impl PR is marked ready for review (not draft) + // Optional smoke station (REQ-SMOKE): tiers the target repo opts in via .devloop/config.json + // `smoke.tiers` (default: none -> chain unchanged). Runs after an accepted critic round, before + // MARK_READY, against a LOCAL stack — it observes the effect on the real consumer path. + smokeTiers?: Tier[]; + // Result of the last smoke run, DERIVED by the smoke-verdict CLI from the station's raw report. + // The executor clears it together with `critic` on every RE_GEN (new code -> new evidence). + smoke?: + | { status: "passed" | "not-applicable" | "failed" } + | { status: "not-run"; retried: boolean }; loop?: LoopState; loopParams?: LoopParams; } +function smokeRequired(state: DriverState): boolean { + return (state.smokeTiers ?? []).includes(state.tier); +} + +// Invariant 8: the smoke gate in front of MARK_READY (only for opted-in tiers). +function smokeGate(state: DriverState): Action | undefined { + if (!smokeRequired(state)) return undefined; + const s = state.smoke; + if (!s) return { kind: "SPAWN_STATION", station: "smoke" }; + switch (s.status) { + case "passed": + case "not-applicable": + return undefined; + case "failed": + return handleRedGate(state); // observed wrong effect = defect signal -> back-edge + case "not-run": + // Setup broke / report unparseable: one restart, then escalate — never read as "passed". + return s.retried + ? { kind: "ESCALATE", reason: "smoke-not-run" } + : { kind: "SPAWN_STATION", station: "smoke" }; + default: + // Anything not produced by smoke-verdict (typo, hand-written label) is fail-closed. + return { kind: "ESCALATE", reason: "smoke-invalid-state" }; + } +} + function handleRedGate(state: DriverState): Action { if (!state.loop || !state.loopParams) { return { kind: "ESCALATE", reason: "loop-params-required" }; @@ -173,8 +212,11 @@ export function nextAction(state: DriverState): Action { : { kind: "SPAWN_STATION", station: "critic" }; } if (c.verdict === "rejected") return handleRedGate(state); // back-edge via nextLoopDecision - // accepted: mark ready first (arms auto-merge), then behave like merge-pending. - return state.ready === true ? handleReady(state) : { kind: "MARK_READY" }; + // accepted: mark ready first (arms auto-merge), then behave like merge-pending. `ready` must + // mirror GitHub: the executor resets it to false on RE_GEN with markDraft, so new code after a + // human back-edge passes the smoke gate again before MARK_READY. + if (state.ready === true) return handleReady(state); + return smokeGate(state) ?? { kind: "MARK_READY" }; } case "merge-pending": diff --git a/src/core/init.ts b/src/core/init.ts index 3730084..8e3d1d9 100644 --- a/src/core/init.ts +++ b/src/core/init.ts @@ -113,10 +113,12 @@ export function initRepo( // hook defers to CI instead of demanding the (anchor-a) local token. // anchor: CI is authoritative (b). twin: the optional spec-to-twin station, disabled by default // (discoverable here; core stays schlank). Enable via twin.enabled=true + twin.area (the protected - // oracle path, e.g. "services/foo/twin") — see the spec-to-twin station. + // oracle path, e.g. "services/foo/twin") — see the spec-to-twin station. smoke: the optional + // smoke station, off by default (tiers: []); enable per tier + point `setup` at a repo doc that + // says how to start the local stack and create test accounts — see the smoke station. writeIfAbsent( ".devloop/config.json", - JSON.stringify({ anchor: "b", twin: { enabled: false } }, null, 2) + "\n", + JSON.stringify({ anchor: "b", twin: { enabled: false }, smoke: { tiers: [], setup: null } }, null, 2) + "\n", ); // Tier-map: NEVER shadow an existing one. resolveTierMapPath prefers .devloop/, so writing a diff --git a/src/core/smoke.ts b/src/core/smoke.ts new file mode 100644 index 0000000..33a9e7c --- /dev/null +++ b/src/core/smoke.ts @@ -0,0 +1,176 @@ +// Smoke report parsing (REQ-SMOKE-2/3). The status is DERIVED from validating the station's raw +// report — never taken from a label the station (or the caller) supplies. Anything that does not +// validate is "not-run", never "passed". +// +// A smoke case is only valid with an observed EFFECT (state before/after on the real consumer +// path, e.g. a DB row, a rendered page, a stored file) — a bare HTTP status is not a smoke. + +export type SmokeStatus = "passed" | "not-applicable" | "failed" | "not-run"; +export const SMOKE_MODES = ["browser", "api", "cli", "other"] as const; + +export interface SmokeCase { + id: string; + req: string | null; + mode: (typeof SMOKE_MODES)[number]; + action: string; + expected: string; + observed: string; + effect: string; + pass: boolean; +} + +export interface SmokeConsumer { + changed: string; + caller: string; + evidence: string; +} + +export interface SmokeRun { + status: SmokeStatus; + cases: SmokeCase[]; + failedCases: string[]; + consumers: SmokeConsumer[]; + notApplicable: string | null; + abnahme: string | null; +} + +const NOT_RUN: SmokeRun = { + status: "not-run", + cases: [], + failedCases: [], + consumers: [], + notApplicable: null, + abnahme: null, +}; + +const nonEmpty = (x: unknown): x is string => typeof x === "string" && x.trim() !== ""; + +// End index (exclusive) of the balanced JSON object starting at `start`, string-aware; -1 if none. +function objectEnd(s: string, start: number): number { + let depth = 0; + let inStr = false; + for (let i = start; i < s.length; i++) { + const c = s[i]; + if (inStr) { + if (c === "\\") i++; + else if (c === '"') inStr = false; + } else if (c === '"') inStr = true; + else if (c === "{") depth++; + else if (c === "}" && --depth === 0) return i + 1; + } + return -1; +} + +// THE top-level JSON object in the text that has a `cases` field. More than one such object (a +// quoted schema example, an earlier run printed alongside) is ambiguous -> undefined (not-run): +// picking the first would let a green example mask a red real report. +function findReport(raw: string): Record | undefined { + const found: Record[] = []; + let i = raw.indexOf("{"); + while (i !== -1) { + const end = objectEnd(raw, i); + if (end !== -1) { + try { + const v: unknown = JSON.parse(raw.slice(i, end)); + if (v && typeof v === "object" && !Array.isArray(v)) { + if ("cases" in v) found.push(v as Record); + i = raw.indexOf("{", end); + continue; + } + } catch { + /* not JSON -> next brace */ + } + } + i = raw.indexOf("{", i + 1); + } + return found.length === 1 ? found[0] : undefined; +} + +const TIERS = ["T0", "T1", "T2", "T3"] as const; +export type SmokeTier = (typeof TIERS)[number]; + +// `.devloop/config.json` -> smoke.tiers. Absent config / absent `smoke` / absent `tiers` -> [] (off). +// Present but malformed -> undefined: the caller must fail closed (refuse), never read it as "off". +export function readSmokeTiers(config: unknown): SmokeTier[] | undefined { + if (config === undefined || config === null) return []; + if (typeof config !== "object" || Array.isArray(config)) return undefined; + const smoke = (config as Record).smoke; + if (smoke === undefined) return []; + if (!smoke || typeof smoke !== "object" || Array.isArray(smoke)) return undefined; + const tiers = (smoke as Record).tiers; + if (tiers === undefined) return []; + if (!Array.isArray(tiers)) return undefined; + if (!tiers.every((t) => typeof t === "string" && (TIERS as readonly string[]).includes(t))) return undefined; + return [...new Set(tiers as SmokeTier[])]; +} + +function toConsumer(x: unknown): SmokeConsumer | undefined { + if (!x || typeof x !== "object") return undefined; + const c = x as Record; + if (!nonEmpty(c.changed) || !nonEmpty(c.caller) || !nonEmpty(c.evidence)) return undefined; + return { changed: c.changed, caller: c.caller, evidence: c.evidence }; +} + +function toCase(x: unknown): SmokeCase | undefined { + if (!x || typeof x !== "object") return undefined; + const c = x as Record; + if (!nonEmpty(c.id) || !nonEmpty(c.action) || !nonEmpty(c.expected)) return undefined; + if (!nonEmpty(c.observed) || !nonEmpty(c.effect)) return undefined; + if (typeof c.pass !== "boolean") return undefined; + if (typeof c.mode !== "string" || !(SMOKE_MODES as readonly string[]).includes(c.mode)) return undefined; + if (c.req !== null && c.req !== undefined && typeof c.req !== "string") return undefined; + return { + id: c.id, + req: typeof c.req === "string" ? c.req : null, + mode: c.mode as SmokeCase["mode"], + action: c.action, + expected: c.expected, + observed: c.observed, + effect: c.effect, + pass: c.pass, + }; +} + +export function parseSmokeReport(raw: string): SmokeRun { + const r = findReport(raw); + if (!r || !Array.isArray(r.cases) || !Array.isArray(r.consumers)) return NOT_RUN; + + const setup = r.setup as Record | undefined; + if (!setup || typeof setup !== "object" || setup.ok !== true) return NOT_RUN; // stack never stood + + const consumers: SmokeConsumer[] = []; + for (const x of r.consumers) { + const c = toConsumer(x); + if (!c) return NOT_RUN; + consumers.push(c); + } + const cases: SmokeCase[] = []; + for (const x of r.cases) { + const c = toCase(x); + if (!c) return NOT_RUN; + cases.push(c); + } + if (new Set(cases.map((c) => c.id)).size !== cases.length) return NOT_RUN; + + const notApplicable = nonEmpty(r.notApplicable) ? r.notApplicable : null; + const abnahme = nonEmpty(r.abnahme) ? r.abnahme : null; + + if (cases.length === 0) { + // "Nothing to smoke" must be argued: a reason AND the consumer analysis it rests on. + if (notApplicable === null || consumers.length === 0) return NOT_RUN; + return { status: "not-applicable", cases, failedCases: [], consumers, notApplicable, abnahme }; + } + if (notApplicable !== null) return NOT_RUN; // contradictory: cases ran but "not applicable" + if (abnahme === null) return NOT_RUN; // the human's acceptance guide is part of the deliverable + if (consumers.length === 0) return NOT_RUN; // no consumer analysis -> mode choice unfounded + + const failedCases = cases.filter((c) => !c.pass).map((c) => c.id); + return { + status: failedCases.length > 0 ? "failed" : "passed", + cases, + failedCases, + consumers, + notApplicable: null, + abnahme, + }; +} diff --git a/test/artifacts.test.ts b/test/artifacts.test.ts index e92c616..0892246 100644 --- a/test/artifacts.test.ts +++ b/test/artifacts.test.ts @@ -7,7 +7,7 @@ const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const read = (rel: string) => readFileSync(resolve(root, rel), "utf8"); const has = (rel: string) => existsSync(resolve(root, rel)); -const STATIONS = ["specify", "spec-to-tests", "implement", "critic"] as const; +const STATIONS = ["specify", "spec-to-tests", "implement", "critic", "smoke"] as const; function frontmatter(md: string): string { const m = md.match(/^---\n([\s\S]*?)\n---/); @@ -208,3 +208,30 @@ test("composite action manifests carry no ${{ }} expression in any description f } } }); + +test("[REQ-SMOKE-5] the smoke subagent changes no repo content (no Write/Edit)", () => { + const fm = frontmatter(read("agents/devloop-smoke.md")); + expect(fm).not.toMatch(/\bWrite\b/); + expect(fm).not.toMatch(/\bEdit\b/); +}); + +test("[REQ-SMOKE-5] the loop skill derives smoke via smoke-verdict and clears critic+smoke on RE_GEN", () => { + const md = read("skills/loop/SKILL.md"); + expect(md).toMatch(/smoke-verdict/); + expect(md).toMatch(/smokeTiers/); + expect(md).toMatch(/`critic` und `smoke` im State löschen/); +}); + +test("[REQ-SMOKE-5] specify asks for a Smoke section with the verified caller of the changed path", () => { + const md = read("agents/devloop-specify.md"); + expect(md).toMatch(/## Smoke/); + expect(md).toMatch(/wer den geänderten Pfad aufruft/i); +}); + +test("[REQ-SMOKE-6] loop resets ready on markDraft and reads smokeTiers fail-closed; resume reads smokeTiers too", () => { + const loop = read("skills/loop/SKILL.md"); + expect(loop).toMatch(/\*\*`ready: false`\*\*/); + expect(loop).toMatch(/smoke-tiers\.js/); + expect(loop).toMatch(/server-berechnete Tier aus dem Diff/); + expect(read("skills/resume/SKILL.md")).toMatch(/smoke-tiers\.js/); +}); diff --git a/test/cli/smoke-verdict.test.ts b/test/cli/smoke-verdict.test.ts new file mode 100644 index 0000000..929cf57 --- /dev/null +++ b/test/cli/smoke-verdict.test.ts @@ -0,0 +1,30 @@ +import { test, expect } from "vitest"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { dirname, resolve } from "node:path"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const script = resolve(root, "dist/cli/smoke-verdict.js"); +const run = (input: unknown) => { + const r = spawnSync("node", [script], { encoding: "utf8", input: typeof input === "string" ? input : JSON.stringify(input), cwd: root }); + return { status: r.status, out: JSON.parse(r.stdout) }; +}; +const report = (pass: boolean) => + JSON.stringify({ + consumers: [{ changed: "a", caller: "b", evidence: "c:1" }], + setup: { ok: true, steps: [] }, + cases: [{ id: "c1", req: null, mode: "api", action: "x", expected: "y", observed: "z", effect: "w", pass }], + notApplicable: null, + abnahme: "## Abnahme", + }); + +test("[REQ-SMOKE-2] CLI leitet passed/failed ab und reicht die Abnahme-Anleitung durch", () => { + expect(run({ rawOutput: report(true) }).out).toMatchObject({ smoke: { status: "passed" }, abnahme: "## Abnahme" }); + expect(run({ rawOutput: report(false) }).out).toMatchObject({ smoke: { status: "failed" }, failedCases: ["c1"] }); +}); + +test("[REQ-SMOKE-3] CLI: ein status im Input wird ignoriert; not-run trägt retried", () => { + expect(run({ rawOutput: "Müll", status: "passed" }).out.smoke).toEqual({ status: "not-run", retried: false }); + expect(run({ rawOutput: "Müll", retried: true }).out.smoke).toEqual({ status: "not-run", retried: true }); + expect(run("kein json").out.smoke).toEqual({ status: "not-run", retried: false }); +}); diff --git a/test/core/smoke-driver.test.ts b/test/core/smoke-driver.test.ts new file mode 100644 index 0000000..1dfb4fb --- /dev/null +++ b/test/core/smoke-driver.test.ts @@ -0,0 +1,116 @@ +import { test, expect } from "vitest"; +import { nextAction, type DriverState } from "../../src/core/driver.js"; +import type { LoopState, LoopParams } from "../../src/core/loop.js"; + +// REQ-SMOKE-1/4: the optional smoke gate between an accepted critic round and MARK_READY. +const loop: LoopState = { + iteration: 1, + gateChangedNotCode: false, + freshContextUsed: false, + lastRound: { judged: true, progress: true, oscillation: false }, +}; +const loopParams: LoopParams = { maxIter: 5 }; +const TIERS = ["T0", "T1", "T2", "T3"] as const; +type Smoke = NonNullable; +const accepted = { status: "completed", verdict: "accepted", retried: false } as const; +const st = (over: Partial = {}): DriverState => ({ + tier: "T3", + guardians: { ok: true, missing: [] }, + phase: "critiqued", + gateVerdict: "green", + critic: accepted, + humanApprovals: {}, + loop, + loopParams, + ...over, +}); + +test("[REQ-SMOKE-1] ohne smokeTiers bleibt die Kette unverändert: accepted -> MARK_READY (jedes Tier)", () => { + for (const tier of TIERS) { + expect(nextAction(st({ tier }))).toEqual({ kind: "MARK_READY" }); + expect(nextAction(st({ tier, smokeTiers: [] }))).toEqual({ kind: "MARK_READY" }); + } +}); + +test("[REQ-SMOKE-1] Tier nicht eingeschaltet -> kein Smoke, auch wenn andere Tiers es sind", () => { + expect(nextAction(st({ tier: "T1", smokeTiers: ["T2", "T3"] }))).toEqual({ kind: "MARK_READY" }); +}); + +test("[REQ-SMOKE-1] eingeschaltetes Tier, noch kein Smoke -> smoke-Station spawnen statt MARK_READY", () => { + for (const tier of TIERS) + expect(nextAction(st({ tier, smokeTiers: [tier] }))).toEqual({ kind: "SPAWN_STATION", station: "smoke" }); +}); + +test("[REQ-SMOKE-1] passed oder not-applicable -> MARK_READY", () => { + for (const status of ["passed", "not-applicable"] as const) + expect(nextAction(st({ smokeTiers: ["T3"], smoke: { status } }))).toEqual({ kind: "MARK_READY" }); +}); + +test("[REQ-SMOKE-4] failed ist ein Defektsignal -> Rückkante über nextLoopDecision (RE_GEN), nie MARK_READY", () => { + expect(nextAction(st({ smokeTiers: ["T3"], smoke: { status: "failed" } }))).toEqual({ + kind: "RE_GEN", + feedback: "defect-signal", + freshContext: false, + }); + expect(nextAction(st({ smokeTiers: ["T3"], smoke: { status: "failed" }, loop: { ...loop, iteration: 5 } }))).toEqual({ + kind: "ESCALATE", + reason: "ESCALATE_MAX_ITER", + }); +}); + +test("[REQ-SMOKE-4] not-run: genau ein Neustart, dann ESCALATE smoke-not-run", () => { + expect(nextAction(st({ smokeTiers: ["T3"], smoke: { status: "not-run", retried: false } }))).toEqual({ + kind: "SPAWN_STATION", + station: "smoke", + }); + expect(nextAction(st({ smokeTiers: ["T3"], smoke: { status: "not-run", retried: true } }))).toEqual({ + kind: "ESCALATE", + reason: "smoke-not-run", + }); +}); + +test("[REQ-SMOKE-1] Invariante: MARK_READY bei eingeschaltetem Tier nur mit passed/not-applicable", () => { + const smokes: (Smoke | undefined)[] = [ + undefined, + { status: "passed" }, + { status: "not-applicable" }, + { status: "failed" }, + { status: "not-run", retried: false }, + { status: "not-run", retried: true }, + ]; + const critics: DriverState["critic"][] = [ + undefined, + accepted, + { status: "completed", verdict: "rejected", retried: false }, + { status: "not-run", retried: false }, + ]; + for (const tier of TIERS) + for (const smoke of smokes) + for (const critic of critics) + for (const ready of [undefined, false]) + for (const phase of ["gated", "critiqued", "merge-pending"] as const) { + const a = nextAction(st({ tier, smokeTiers: [tier], smoke, critic, ready, phase })); + if (a.kind === "MARK_READY" || a.kind === "DONE") { + expect(["passed", "not-applicable"]).toContain(smoke?.status); + } + } +}); + +test("[REQ-SMOKE-1] smoke spawnt nie vor einem akzeptierten Critic-Verdikt", () => { + for (const critic of [undefined, { status: "not-run", retried: false } as const, { status: "completed", verdict: "rejected", retried: false } as const]) { + const a = nextAction(st({ smokeTiers: ["T3"], critic })); + expect(a).not.toEqual({ kind: "SPAWN_STATION", station: "smoke" }); + } +}); + +test("[REQ-SMOKE-1] ein bereits ready PR (z. B. aus resume) wird nicht erneut gesmoket", () => { + expect(nextAction(st({ smokeTiers: ["T3"], ready: true }))).toEqual({ kind: "STOP_FOR_HUMAN", stop: "t3-merge" }); +}); + +test("[REQ-SMOKE-1] unbekannter smoke-Status (Tippfehler, Handlabel) ist fail-closed -> ESCALATE", () => { + for (const status of ["PASSED", "ok", undefined]) + expect(nextAction(st({ smokeTiers: ["T3"], smoke: { status } as unknown as DriverState["smoke"] }))).toEqual({ + kind: "ESCALATE", + reason: "smoke-invalid-state", + }); +}); diff --git a/test/core/smoke-tiers.test.ts b/test/core/smoke-tiers.test.ts new file mode 100644 index 0000000..6ac4ba4 --- /dev/null +++ b/test/core/smoke-tiers.test.ts @@ -0,0 +1,38 @@ +import { test, expect } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { readSmokeTiers } from "../../src/core/smoke.js"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); + +test("[REQ-SMOKE-6] fehlende Config/Sektion -> [] (aus)", () => { + expect(readSmokeTiers(undefined)).toEqual([]); + expect(readSmokeTiers({ anchor: "b" })).toEqual([]); + expect(readSmokeTiers({ smoke: { setup: "x" } })).toEqual([]); + expect(readSmokeTiers({ smoke: { tiers: ["T3", "T2", "T3"] } })).toEqual(["T3", "T2"]); +}); + +test("[REQ-SMOKE-6] kaputte Werte -> undefined (fail-closed), nie still aus", () => { + for (const c of [{ smoke: { tiers: ["t1"] } }, { smoke: { tiers: "T2" } }, { smoke: true }, [], "x"]) + expect(readSmokeTiers(c)).toBeUndefined(); +}); + +function cli(config: string | null) { + const dir = mkdtempSync(join(tmpdir(), "smoke-tiers-")); + if (config !== null) { + mkdirSync(join(dir, ".devloop")); + writeFileSync(join(dir, ".devloop", "config.json"), config); + } + const r = spawnSync("node", [resolve(root, "dist/cli/smoke-tiers.js"), dir], { encoding: "utf8" }); + return { status: r.status, out: r.stdout.trim() }; +} + +test("[REQ-SMOKE-6] CLI: Tiers aus der Config, [] ohne Config, Exit 1 bei kaputter Config", () => { + expect(cli('{"smoke":{"tiers":["T2","T3"]}}')).toEqual({ status: 0, out: '["T2","T3"]' }); + expect(cli(null)).toEqual({ status: 0, out: "[]" }); + expect(cli('{"smoke":{"tiers":["T9"]}}').status).toBe(1); + expect(cli("{kaputt").status).toBe(1); +}); diff --git a/test/core/smoke.test.ts b/test/core/smoke.test.ts new file mode 100644 index 0000000..f4d6106 --- /dev/null +++ b/test/core/smoke.test.ts @@ -0,0 +1,106 @@ +import { test, expect } from "vitest"; +import { parseSmokeReport } from "../../src/core/smoke.js"; + +const C = (over: Record = {}) => ({ + id: "c1", + req: "REQ-X-1", + mode: "api", + action: "PATCH als user", + expected: "pending contribution, Zeile unverändert", + observed: "HTTP 200, contributions 37 -> 38 (pending), notes unverändert", + effect: "select status from contributions ... -> pending", + pass: true, + ...over, +}); +const K = { changed: "PATCH /versions/:id", caller: "wuerfelgeist-mcp update_version", evidence: "VersionsClient.ts:42" }; +const R = (over: Record = {}) => + JSON.stringify({ consumers: [K], setup: { ok: true, steps: ["up"] }, cases: [C()], notApplicable: null, abnahme: "## Abnahme\n1. ...", ...over }); + +test("[REQ-SMOKE-2] gültiger Bericht, alle Fälle grün -> passed", () => { + expect(parseSmokeReport(R()).status).toBe("passed"); +}); + +test("[REQ-SMOKE-2] Text und Codezaun um das JSON sind erlaubt", () => { + expect(parseSmokeReport("Bericht:\n```json\n" + R() + "\n```\n").status).toBe("passed"); +}); + +test("[REQ-SMOKE-2] ein roter Fall -> failed mit Fall-ID", () => { + const r = parseSmokeReport(R({ cases: [C(), C({ id: "c2", pass: false })] })); + expect(r.status).toBe("failed"); + expect(r.failedCases).toEqual(["c2"]); +}); + +test("[REQ-SMOKE-3] ein Selbst-Label status: passed zählt nicht", () => { + expect(parseSmokeReport(R({ status: "passed", cases: [C({ pass: false })] })).status).toBe("failed"); + expect(parseSmokeReport(JSON.stringify({ status: "passed" })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] Fall ohne beobachtete Wirkung (effect) ist ungültig -> not-run", () => { + expect(parseSmokeReport(R({ cases: [C({ effect: "" })] })).status).toBe("not-run"); + expect(parseSmokeReport(R({ cases: [C({ effect: undefined })] })).status).toBe("not-run"); + expect(parseSmokeReport(R({ cases: [C({ observed: " " })] })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] pass muss boolean sein, mode aus der Liste", () => { + expect(parseSmokeReport(R({ cases: [C({ pass: "true" })] })).status).toBe("not-run"); + expect(parseSmokeReport(R({ cases: [C({ mode: "gefühlt" })] })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] Stack nicht aufgebaut (setup.ok false/fehlt) -> not-run, nie failed oder passed", () => { + expect(parseSmokeReport(R({ setup: { ok: false, steps: [] } })).status).toBe("not-run"); + expect(parseSmokeReport(R({ setup: undefined })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] Fälle ohne Konsumenten-Analyse -> not-run", () => { + expect(parseSmokeReport(R({ consumers: [] })).status).toBe("not-run"); + expect(parseSmokeReport(R({ consumers: [{ changed: "x", caller: "y", evidence: "" }] })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] Fälle ohne Abnahme-Anleitung für den Menschen -> not-run", () => { + expect(parseSmokeReport(R({ abnahme: "" })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] doppelte Fall-IDs -> not-run", () => { + expect(parseSmokeReport(R({ cases: [C(), C()] })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-2] not-applicable nur mit Begründung UND Konsumenten-Analyse", () => { + expect(parseSmokeReport(R({ cases: [], notApplicable: "reine Doku-Änderung, kein Laufzeitpfad" })).status).toBe("not-applicable"); + expect(parseSmokeReport(R({ cases: [], notApplicable: null })).status).toBe("not-run"); + expect(parseSmokeReport(R({ cases: [], consumers: [], notApplicable: "egal" })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] widersprüchlich: Fälle UND notApplicable -> not-run", () => { + expect(parseSmokeReport(R({ notApplicable: "doch nicht" })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] Müll, leerer Text, kein cases-Feld -> not-run", () => { + for (const raw of ["", "kein json", "{}", JSON.stringify({ consumers: [K], setup: { ok: true } })]) + expect(parseSmokeReport(raw).status).toBe("not-run"); +}); + +// --- Nachschärfung nach Critic-Runde 1 ------------------------------------------------------- +test("[REQ-SMOKE-3] zwei Berichte im Text (z. B. zitiertes Schema-Beispiel + echter roter) -> not-run, nie passed", () => { + const green = R(); + const red = R({ cases: [C({ pass: false })] }); + expect(parseSmokeReport(green + "\n" + red).status).toBe("not-run"); + expect(parseSmokeReport(red + "\n" + green).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] ein ungültiger Fall neben gültigen wird nicht still verworfen -> not-run", () => { + expect(parseSmokeReport(R({ cases: [C(), C({ id: "c2", pass: false, effect: "" })] })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] ein ungültiger Konsument neben gültigen -> not-run", () => { + expect(parseSmokeReport(R({ consumers: [K, { changed: "x", caller: "", evidence: "e" }] })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] expected fehlt oder leer -> not-run", () => { + expect(parseSmokeReport(R({ cases: [C({ expected: undefined })] })).status).toBe("not-run"); + expect(parseSmokeReport(R({ cases: [C({ expected: " " })] })).status).toBe("not-run"); +}); + +test("[REQ-SMOKE-3] req muss String oder null sein", () => { + expect(parseSmokeReport(R({ cases: [C({ req: 7 })] })).status).toBe("not-run"); + expect(parseSmokeReport(R({ cases: [C({ req: null })] })).status).toBe("passed"); +});