Superpowers – praktický tutoriál

Samostatný soubor, který nepotřebuje nic dalšího (CSS, skript i obrázky jsou uvnitř). Verze repozitáře 7.0.1.

55kapitol a příkladů
505otázek kvízu
569pojmů ve slovníku
6kategorií

Superpowers je sada „dovedností“ (skills) pro kódovací agenty: brainstorming, plány, TDD, systematické ladění, review, práce s git worktrees a další. Tato aplikace je lokální rozcestník nad repozitářem. Má menu, fulltext se zvýrazněním, stránky skills a dokumentace a ke každému příkladu popis, zdroj, kvíz a slovník. Tento soubor je jeho offline verze.

Rychlý start

docker compose up -d                                  # rozcestník na http://localhost:8080
docker compose ps                                     # stav healthy
docker compose --profile tests run --rm tests         # node --check, node --test, testy brainstorm serveru
docker compose --profile lint run --rm lint           # ShellCheck
docker compose down                                   # zastavení

Node ani PHP se na hostiteli neinstalují, vše běží v Dockeru. Port 8080 je standardní port workspace; jiný projekt před startem zastav. Nic se neposílá na žádný remote.

Jak číst tutoriál: každá kapitola má popis, zdrojový kód (rozbalovací), kvíz (klikni na otázku, odpověď se rozbalí; nejdřív zkus odpovědět sám) a za ním slovník pojmů k danému příkladu.

(kvízy a slovníky)

Architektura

Prohlížeč127.0.0.1:8080 web-t375Node 22, server.mjsbez závislostíread_only, cap_drop ALL Repozitář :roskills, docs, tests site/examples55 příkladů, kvíz, slovník site/guide.md
Prohlížeč mluví jen s kontejnerem web-t375 (loopback). Ten čte repozitář pouze pro čtení a obsah příkladů z site/examples.

Úvodní stránka

Úvodní stránka rozcestníku s menu vlevo, vyhledáváním a dlaždicemi
Úvodní stránka: menu vlevo, hero s vyhledáváním, statistiky a odkazy na skills, dokumentaci a příklady.

Oblasti aplikace

Oblast: Docker, testy a generování tutoriálu

Jak se aplikace spouští jen v Dockeru, jaké testy a statická analýza existují a jak se generuje docs/tutorial.html a prezentace.

Podle pravidel workspace běží Node a PHP jen v Dockeru; na hostiteli se nic neinstaluje. compose.yaml má čtyři služby:

SlužbaKontejnerÚčel
webweb-t375Rozcestník na 127.0.0.1:8080, repozitář :ro, healthcheck /healthz
brainstorm (profil)brainstorm-t375Vizuální companion brainstormingu na 8082, telemetrie vypnutá
tests (profil)tests-t375node --check, node --test site/test a testy brainstorm serveru
lint (profil)lint-t375ShellCheck (obdoba phpstan pro tento ne-PHP projekt)

Projekt není PHP, takže se phpstan a phpunit nepoužívají. Jejich roli plní statická analýza (node --check, ShellCheck) a automatické testy (node:test). Offline tutoriál a prezentaci generují skripty site/build-tutorial.mjs a site/build-presentation.mjs, takže se nepíší ručně.

Praktický postup: (1) docker compose up -d; (2) docker compose ps ukáže stav healthy; (3) docker compose --profile tests run --rm tests spustí všechny testy; (4) docker compose --profile lint run --rm lint spustí ShellCheck; (5) po přidání příkladu přegeneruj docs/tutorial.html; (6) docker compose down služby zastaví. Port 8080 je sdílený s ostatními projekty workspace, takže před startem zastav jiný běžící projekt.

Zdrojový kód

compose.yaml 74 řádků
services:
  web:
    image: node:22
    container_name: web-t375
    user: node
    working_dir: /app
    volumes:
      - .:/app:ro
    environment:
      REPO_ROOT: /app
      PORT: "8080"
    command: node site/server.mjs
    ports:
      - "127.0.0.1:8080:8080"
    read_only: true
    cap_drop: [ALL]
    security_opt:
      - no-new-privileges:true
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8080/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 5s

  brainstorm:
    profiles: ["brainstorm"]
    image: node:22
    container_name: brainstorm-t375
    user: node
    working_dir: /app
    volumes:
      - .:/app
    environment:
      BRAINSTORM_HOST: 0.0.0.0
      BRAINSTORM_URL_HOST: localhost
      BRAINSTORM_PORT: "8080"
      BRAINSTORM_TOKEN: dev
      BRAINSTORM_DIR: /tmp/brainstorm
      SUPERPOWERS_DISABLE_TELEMETRY: "true"
    command: node skills/brainstorming/scripts/server.cjs
    ports:
      - "127.0.0.1:8082:8080"

  # Všechny testy: testy brainstorm serveru (vlastní npm ci) a testy rozcestníku.
  tests:
    profiles: ["tests"]
    image: node:22
    container_name: tests-t375
    user: node
    working_dir: /app
    volumes:
      - .:/app
    command: >
      bash -c "node --check site/server.mjs && node --test 'site/test/*.test.mjs'
      && (cd tests/brainstorm-server && npm ci --silent && npm test)"

  # Statická analýza shellu (obdoba phpstan pro tento ne-PHP projekt).
  lint:
    profiles: ["lint"]
    image: koalaman/shellcheck-alpine:stable
    container_name: lint-t375
    working_dir: /app
    volumes:
      - .:/app:ro
    entrypoint:
      - sh
      - -c
      - |
        set -e
        shellcheck --severity=warning -x $$(find skills scripts hooks -type f \( -name '*.sh' -o -path '*/scripts/*' -o -name session-start \) ! -name '*.js' ! -name '*.cjs' ! -name '*.html')
        shellcheck --severity=error -x $$(find tests -name '*.sh')
        echo "shellcheck OK"
site/test/server.test.mjs 109 řádků
// Tests for the home page server. Run: node --test site/test  (from the repository root)
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const PORT = 18475;
const BASE = `http://127.0.0.1:${PORT}`;
let child;

before(async () => {
  child = spawn('node', ['site/server.mjs'], { cwd: ROOT, env: { ...process.env, PORT: String(PORT), REPO_ROOT: ROOT }, stdio: 'ignore' });
  for (let i = 0; i < 50; i++) {
    try { if ((await fetch(`${BASE}/healthz`)).ok) return; } catch { /* not up yet */ }
    await new Promise((r) => setTimeout(r, 100));
  }
  throw new Error('server did not start');
});
after(() => child && child.kill());

const get = (p, init) => fetch(BASE + p, init);

test('every main page responds 200 with security headers', async () => {
  for (const p of ['/', '/examples', '/guide', '/skill/brainstorming', '/section/Specifikace', '/search?q=worktree', '/file?path=README.md']) {
    const r = await get(p);
    assert.equal(r.status, 200, p);
    assert.match(r.headers.get('content-security-policy'), /frame-ancestors 'none'/);
    assert.equal(r.headers.get('x-content-type-options'), 'nosniff');
    assert.equal(r.headers.get('x-frame-options'), 'DENY');
  }
});

test('path traversal and non-viewable files are rejected', async () => {
  for (const p of ['../etc/passwd', '../../etc/passwd', '.git/config', 'node_modules/x', '/etc/passwd', 'assets/app-icon.png']) {
    assert.equal((await get('/file?path=' + encodeURIComponent(p))).status, 404, p);
  }
});

test('unknown routes and malformed URLs do not crash the server', async () => {
  assert.equal((await get('/nope')).status, 404);
  assert.equal((await get('/skill/%E0%A4%A')).status, 400);
  assert.equal((await get('/skill/nope')).status, 404);
  assert.equal((await get('/example/../../x')).status, 404);
  assert.equal((await get('/healthz')).status, 200);
});

test('only GET and HEAD are allowed', async () => {
  const r = await get('/', { method: 'POST' });
  assert.equal(r.status, 405);
  assert.equal(r.headers.get('allow'), 'GET, HEAD');
  assert.equal((await get('/', { method: 'HEAD' })).status, 200);
});

test('search highlights the query and escapes HTML', async () => {
  const html = await (await get('/search?q=backoff')).text();
  assert.match(html, /<mark>backoff<\/mark>/i);
  const xss = await (await get('/search?q=' + encodeURIComponent('<script>alert(1)</script>'))).text();
  assert.ok(!xss.includes('<script>alert(1)</script>'));
  const short = await (await get('/search?q=a')).text();
  assert.match(short, /alespoň 2 znaky/);
});

test('hl parameter on file and example pages is escaped and highlighted', async () => {
  const f = await (await get('/file?path=README.md&hl=skills')).text();
  assert.match(f, /<mark>/);
  const e = await (await get('/example/script-task-done?hl=%3Cimg%20src%3Dx%3E')).text();
  assert.ok(!e.includes('<img src=x>'));
});

test('markdown renderer blocks javascript: links', async () => {
  const { markdown } = await import('../server.mjs');
  assert.ok(!markdown('[x](javascript:alert(1))').includes('javascript:'));
  assert.match(markdown('[x](https://example.com)'), /rel="noopener noreferrer"/);
  assert.match(markdown('`a<b`'), /<code>a&lt;b<\/code>/);
});

test('example content: every unit is complete and references existing files', async () => {
  const { exampleUnits } = await import('../server.mjs');
  const units = exampleUnits();
  assert.ok(units.length >= 49);
  for (const u of units) {
    assert.ok(u.title && u.summary && u.kind, u.id);
    assert.ok(u.files.length > 0, u.id);
    for (const f of u.files) assert.ok(fs.existsSync(path.join(ROOT, f)), `${u.id}: missing ${f}`);
    assert.ok(u.description.length > 200, `${u.id}: description too short`);
    assert.ok(u.quiz.length >= 8, `${u.id}: ${u.quiz.length} questions`);
    assert.ok(u.glossary.length >= 8, `${u.id}: ${u.glossary.length} terms`);
    for (const x of [...u.quiz, ...u.glossary]) assert.ok(x.head && x.text, `${u.id}: empty item`);
    assert.equal((await get('/example/' + u.id)).status, 200, u.id);
  }
});

test('home page links every example unit and the final guide', async () => {
  const { exampleUnits } = await import('../server.mjs');
  const html = await (await get('/')).text();
  for (const u of exampleUnits()) assert.ok(html.includes(`href="/example/${u.id}"`), u.id);
  assert.ok(html.includes('href="/guide"'));
});

test('forbidden Czech translations of English terms are absent from content', () => {
  const re = /mezipam|tajemstv|sekret|otisk hesla|otisk řetězce/i;
  for (const f of [...fs.readdirSync(path.join(ROOT, 'site/examples')).map((x) => `site/examples/${x}`), 'site/guide.md']) {
    assert.ok(!re.test(fs.readFileSync(path.join(ROOT, f), 'utf8')), f);
  }
});
site/build-tutorial.mjs 140 řádků
// Generates docs/tutorial.html: a standalone, single-file tutorial (inline CSS, JS and images, no other files needed).
// Per example/area: description, source code, quiz, then glossary. Left navigation with filter and scrollspy.
// Usage (from the repository root, in Docker): node site/build-tutorial.mjs
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

process.env.REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const { markdown, exampleKinds } = await import('./server.mjs');
const ROOT = process.env.REPO_ROOT;
const read = (p) => fs.readFileSync(path.join(ROOT, p));
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
const dataUri = (p, mime) => `data:${mime};base64,${read(p).toString('base64')}`;
const kinds = exampleKinds();
const units = kinds.flatMap((k) => k.units);
const version = JSON.parse(read('package.json').toString()).version;
const totalQ = units.reduce((n, u) => n + u.quiz.length, 0);
const totalG = units.reduce((n, u) => n + u.glossary.length, 0);

const qa = (items, term) => items.map((x, i) => `<details class="qa"><summary>${term ? `<b>${esc(x.head)}</b>` : `<span class="n">${i + 1}.</span> ${esc(x.head)}`}</summary><div class="ans">${markdown(x.text)}</div></details>`).join('\n');

// Source code: each file once (first unit that lists it); later units link to it.
const shown = new Map();
const sourceBlock = (u, f) => {
  if (u.id === 'area-guide') return '';
  if (shown.has(f)) return `<p class="srcref">Zdroj <code>${esc(f)}</code> je uvedený v <a href="#${shown.get(f)}-src">kapitole ${esc(shown.get(f))}</a>.</p>`;
  shown.set(f, u.id);
  let text;
  try { text = read(f).toString('utf8'); } catch { return `<p class="srcref"><code>${esc(f)}</code> (soubor nenalezen)</p>`; }
  const lines = text.split('\n').length;
  return `<details class="src" id="${u.id}-src"><summary><code>${esc(f)}</code> <span class="mut">${lines} řádků</span></summary><pre><code>${esc(text)}</code></pre></details>`;
};

const guideHtml = markdown(read('site/guide.md').toString());
const unitHtml = (u) => `
<section class="unit" id="${u.id}" data-nav="${esc(u.title)}"><h3>${esc(u.title)}</h3>
<p class="lead">${esc(u.summary)}</p>
<div class="desc">${markdown(u.description)}</div>
${u.id === 'area-guide' ? `<details class="src"><summary>Celý text závěrečného dílu <span class="mut">(site/guide.md)</span></summary><div class="guide">${guideHtml}</div></details>` : ''}
${u.files.length ? `<h4>Zdrojový kód</h4>${u.files.map((f) => sourceBlock(u, f)).join('\n')}` : ''}
<h4 class="quiz-h">Kvíz <span class="mut">(${u.quiz.length} otázek, odpověď se rozbalí kliknutím)</span></h4>${qa(u.quiz, false)}
<h4 class="gl-h">Slovník pojmů <span class="mut">(${u.glossary.length})</span></h4>${qa(u.glossary, true)}
<p class="up"><a href="#top">↑ nahoru</a></p></section>`;

const nav = [
  `<div class="grp"><a href="#uvod" data-t="úvod rychlý start">Úvod a rychlý start</a><a href="#architektura" data-t="architektura">Architektura</a><a href="#screenshot" data-t="home page screenshot">Úvodní stránka</a></div>`,
  ...kinds.map((k) => `<details class="grp" open><summary>${esc(k.title)} <span class="c">${k.units.length}</span></summary>${k.units.map((u) => `<a href="#${u.id}" data-t="${esc((u.title + ' ' + u.summary).toLowerCase())}">${esc(u.title.replace(/^Oblast: /, ''))}</a>`).join('')}</details>`),
  `<div class="grp"><a href="#shrnuti" data-t="shrnutí audit">Shrnutí a audit</a></div>`,
].join('\n');

const diagram = `<svg viewBox="0 0 760 260" role="img" aria-label="Architektura rozcestníku" xmlns="http://www.w3.org/2000/svg" font-family="system-ui,sans-serif" font-size="14">
<defs><marker id="ar" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 z" fill="#5b5bd6"/></marker></defs>
<rect x="10" y="90" width="130" height="70" rx="10" fill="#eef0ff" stroke="#5b5bd6"/><text x="75" y="120" text-anchor="middle" fill="#1b1f2a" font-weight="700">Prohlížeč</text><text x="75" y="141" text-anchor="middle" fill="#475467" font-size="12">127.0.0.1:8080</text>
<rect x="230" y="60" width="190" height="130" rx="10" fill="#5b5bd6"/><text x="325" y="95" text-anchor="middle" fill="#fff" font-weight="700">web-t375</text><text x="325" y="118" text-anchor="middle" fill="#e0e0ff" font-size="12">Node 22, server.mjs</text><text x="325" y="138" text-anchor="middle" fill="#e0e0ff" font-size="12">bez závislostí</text><text x="325" y="158" text-anchor="middle" fill="#e0e0ff" font-size="12">read_only, cap_drop ALL</text>
<rect x="510" y="20" width="160" height="60" rx="10" fill="#f2f4f7" stroke="#98a2b3"/><text x="590" y="48" text-anchor="middle" fill="#1b1f2a" font-weight="700">Repozitář :ro</text><text x="590" y="66" text-anchor="middle" fill="#475467" font-size="12">skills, docs, tests</text>
<rect x="510" y="110" width="160" height="60" rx="10" fill="#f2f4f7" stroke="#98a2b3"/><text x="590" y="138" text-anchor="middle" fill="#1b1f2a" font-weight="700">site/examples</text><text x="590" y="156" text-anchor="middle" fill="#475467" font-size="12">${units.length} příkladů, kvíz, slovník</text>
<rect x="510" y="200" width="160" height="50" rx="10" fill="#f2f4f7" stroke="#98a2b3"/><text x="590" y="230" text-anchor="middle" fill="#1b1f2a" font-weight="700">site/guide.md</text>
<path d="M140,125 H228" stroke="#5b5bd6" stroke-width="2" marker-end="url(#ar)"/><path d="M420,100 L508,55" stroke="#5b5bd6" stroke-width="2" marker-end="url(#ar)"/><path d="M420,125 H508" stroke="#5b5bd6" stroke-width="2" marker-end="url(#ar)"/><path d="M420,150 L508,222" stroke="#5b5bd6" stroke-width="2" marker-end="url(#ar)"/>
</svg>`;

const html = `<!doctype html><html lang="cs"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Superpowers – praktický tutoriál</title><link rel="icon" href="${dataUri('assets/superpowers-small.svg', 'image/svg+xml')}"><style>
:root{color-scheme:light dark;--bg:#fff;--fg:#1b1f2a;--mut:#667085;--bd:#e4e7ec;--ac:#5b5bd6;--code:#f2f4f7;--side:#f8f9fc;--hl:#fff3a3}
@media(prefers-color-scheme:dark){:root{--bg:#0e1117;--fg:#e7eaf0;--mut:#8b95a7;--bd:#252c39;--ac:#9a9af5;--code:#1d2330;--side:#131824;--hl:#6b5d00}}
*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:1rem}
body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 system-ui,-apple-system,Segoe UI,sans-serif}
#nt{display:none}.side{position:fixed;inset:0 auto 0 0;width:300px;background:var(--side);border-right:1px solid var(--bd);overflow:auto;padding:1rem .8rem 2rem}
.brand{display:flex;gap:.6rem;align-items:center;font-weight:700;margin-bottom:.2rem}.brand img{width:30px;height:30px}.sub{font-size:.75rem;font-style:italic;color:var(--mut);margin:0 0 .8rem}
.side input{width:100%;padding:.5rem .7rem;border:1px solid var(--bd);border-radius:8px;background:var(--bg);color:var(--fg);margin-bottom:.8rem}
.side a{display:block;padding:.28rem .6rem;border-radius:6px;color:var(--fg);text-decoration:none;font-size:.9rem}.side a:hover{background:var(--code)}
.side a.on{background:var(--ac);color:#fff}.grp{margin-bottom:.5rem}.grp summary{cursor:pointer;font-weight:700;padding:.3rem .4rem;font-size:.82rem;text-transform:uppercase;letter-spacing:.04em;color:var(--mut)}
.c{background:var(--code);border-radius:99px;padding:0 .5rem;font-size:.72rem;margin-left:.3rem}
main{margin-left:300px;max-width:1040px;padding:2rem 2rem 5rem}
.burger{display:none}
h1{font-size:2.1rem;margin:.2rem 0}h2{margin-top:3.2rem;border-bottom:2px solid var(--bd);padding-bottom:.3rem}h3{font-size:1.6rem;margin:0 0 .3rem}h4{margin:1.6rem 0 .5rem;font-size:1.05rem}
.lead{color:var(--mut);margin-top:0}.mut{color:var(--mut);font-weight:400;font-size:.85rem}
a{color:var(--ac)}code{background:var(--code);padding:.1rem .35rem;border-radius:5px;font-size:.9em}
pre{background:var(--code);padding:1rem;overflow:auto;border-radius:8px;max-height:70vh;font-size:.82rem;line-height:1.5}pre code{background:none;padding:0}
section.unit{margin:2.5rem 0;padding:1.5rem;border:1px solid var(--bd);border-radius:12px}
.quiz-h{color:var(--ac)}.gl-h{color:#1a7f5a}
details.qa,details.src{border:1px solid var(--bd);border-radius:8px;margin:.4rem 0;background:var(--bg)}
details.qa>summary,details.src>summary{padding:.55rem .9rem;cursor:pointer;font-weight:600}.n{color:var(--ac)}
.ans{padding:.1rem 1.2rem .6rem;border-top:1px dashed var(--bd)}.srcref{color:var(--mut);font-size:.9rem}.guide{padding:0 1.2rem 1rem}
table{border-collapse:collapse;display:block;overflow:auto}th,td{border:1px solid var(--bd);padding:.3rem .7rem;text-align:left}
blockquote{border-left:3px solid var(--ac);margin:1rem 0;padding:.2rem 1rem;color:var(--mut)}
figure{margin:1.2rem 0}figure img,figure svg{max-width:100%;height:auto;border:1px solid var(--bd);border-radius:10px;background:#fff}figcaption{color:var(--mut);font-size:.85rem;margin-top:.3rem}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.8rem;margin:1.2rem 0}.stat{border:1px solid var(--bd);border-radius:10px;padding:.8rem 1rem}.stat b{display:block;font-size:1.7rem;color:var(--ac)}
.tools{margin:.8rem 0}.tools button{border:1px solid var(--bd);background:var(--code);color:var(--fg);border-radius:8px;padding:.35rem .8rem;cursor:pointer}
.up{text-align:right;margin:.5rem 0 0}mark{background:var(--hl);color:inherit}
@media(max-width:900px){.side{transform:translateX(-100%);transition:transform .2s;z-index:5;width:280px}#nt:checked~.side{transform:none}main{margin-left:0;padding:1rem}.burger{display:block;position:sticky;top:0;background:var(--bg);padding:.5rem 0;z-index:4;cursor:pointer;font-weight:700}}
</style></head><body><span id="top"></span>
<input type="checkbox" id="nt"><label class="burger" for="nt">☰ Obsah</label>
<nav class="side" aria-label="Obsah tutoriálu"><div class="brand"><img alt="" src="${dataUri('assets/superpowers-small.svg', 'image/svg+xml')}"> Superpowers tutoriál</div><p class="sub">t375-plugin-superpowers-obra</p>
<input id="q" type="search" placeholder="Filtrovat kapitoly…" aria-label="Filtrovat kapitoly">
${nav}</nav>
<main>
<h1 id="uvod">Superpowers – praktický tutoriál</h1>
<p class="lead">Samostatný soubor, který nepotřebuje nic dalšího (CSS, skript i obrázky jsou uvnitř). Verze repozitáře ${esc(version)}.</p>
<div class="stats"><div class="stat"><b>${units.length}</b>kapitol a příkladů</div><div class="stat"><b>${totalQ}</b>otázek kvízu</div><div class="stat"><b>${totalG}</b>pojmů ve slovníku</div><div class="stat"><b>${kinds.length}</b>kategorií</div></div>
<p><b>Superpowers</b> je sada „dovedností“ (skills) pro kódovací agenty: brainstorming, plány, TDD, systematické ladění, review, práce s git worktrees a další. Tato aplikace je lokální rozcestník nad repozitářem. Má menu, fulltext se zvýrazněním, stránky skills a dokumentace a ke každému příkladu popis, zdroj, kvíz a slovník. Tento soubor je jeho offline verze.</p>
<h2>Rychlý start</h2>
<pre><code>docker compose up -d                                  # rozcestník na http://localhost:8080
docker compose ps                                     # stav healthy
docker compose --profile tests run --rm tests         # node --check, node --test, testy brainstorm serveru
docker compose --profile lint run --rm lint           # ShellCheck
docker compose down                                   # zastavení</code></pre>
<p>Node ani PHP se na hostiteli neinstalují, vše běží v Dockeru. Port 8080 je standardní port workspace; jiný projekt před startem zastav. Nic se neposílá na žádný remote.</p>
<p><b>Jak číst tutoriál:</b> každá kapitola má popis, zdrojový kód (rozbalovací), <b>kvíz</b> (klikni na otázku, odpověď se rozbalí; nejdřív zkus odpovědět sám) a za ním <b>slovník pojmů</b> k danému příkladu.</p>
<div class="tools"><button type="button" id="open">Rozbalit vše</button> <button type="button" id="close">Sbalit vše</button> <span class="mut">(kvízy a slovníky)</span></div>
<h2 id="architektura">Architektura</h2>
<figure>${diagram}<figcaption>Prohlížeč mluví jen s kontejnerem web-t375 (loopback). Ten čte repozitář pouze pro čtení a obsah příkladů z <code>site/examples</code>.</figcaption></figure>
<h2 id="screenshot">Úvodní stránka</h2>
<figure><img alt="Úvodní stránka rozcestníku s menu vlevo, vyhledáváním a dlaždicemi" src="${dataUri('docs/images/home-page.png', 'image/png')}"><figcaption>Úvodní stránka: menu vlevo, hero s vyhledáváním, statistiky a odkazy na skills, dokumentaci a příklady.</figcaption></figure>
${kinds.map((k) => `<h2 class="kind" id="kind-${k.id}">${esc(k.title)}</h2>${k.units.map(unitHtml).join('\n')}`).join('\n')}
<h2 id="shrnuti">Shrnutí a audit</h2>
<ul><li>Ověřeno proti dokumentaci Claude Code (lokální verze 2.1.314): skills, subagenti, hooky, best practices.</li>
<li>Testy: <code>node --check</code>, <code>node --test</code> (rozcestník), testy brainstorm serveru a ShellCheck. Dva testy file watchingu v brainstorm serveru jsou nestabilní (upstream časování).</li>
<li>Body k rozhodnutí maintainera (neměněno, vyžadují eval důkazy): limit 20 000 bajtů v <code>tests/skill-size</code>, matcher <code>SessionStart</code> bez <code>resume</code>/<code>fork</code>, nová pole skills.</li>
<li>Neověřeno: živé integrační testy <code>tests/claude-code</code> a <code>tests/explicit-skill-requests</code>.</li></ul>
<p class="mut">Generováno skriptem <code>site/build-tutorial.mjs</code>. Needituj ručně.</p>
</main>
<script>
(function(){
var links=[].slice.call(document.querySelectorAll('.side a'));
var q=document.getElementById('q');
q.addEventListener('input',function(){var v=q.value.toLowerCase().trim();links.forEach(function(a){a.style.display=!v||(a.dataset.t||a.textContent).toLowerCase().indexOf(v)>-1||a.textContent.toLowerCase().indexOf(v)>-1?'':'none'});
document.querySelectorAll('.side details.grp').forEach(function(d){if(v)d.open=true})});
document.getElementById('open').onclick=function(){document.querySelectorAll('details.qa').forEach(function(d){d.open=true})};
document.getElementById('close').onclick=function(){document.querySelectorAll('details.qa').forEach(function(d){d.open=false})};
links.forEach(function(a){a.addEventListener('click',function(){document.getElementById('nt').checked=false})});
var targets=links.map(function(a){return document.getElementById(a.getAttribute('href').slice(1))});
function spy(){var y=window.scrollY+80,cur=0;targets.forEach(function(t,i){if(t&&t.offsetTop<=y)cur=i});
links.forEach(function(a,i){a.classList.toggle('on',i===cur)});var on=links[cur];if(on&&on.offsetParent){var s=document.querySelector('.side');if(on.offsetTop<s.scrollTop||on.offsetTop>s.scrollTop+s.clientHeight-40)s.scrollTop=on.offsetTop-80}}
window.addEventListener('scroll',spy,{passive:true});spy();
})();
</script></body></html>`;
fs.mkdirSync(path.join(ROOT, 'docs'), { recursive: true });
fs.writeFileSync(path.join(ROOT, 'docs/tutorial.html'), html);
console.log(`docs/tutorial.html: ${units.length} units, ${totalQ} questions, ${totalG} terms, ${(html.length / 1024).toFixed(0)} KiB`);

Kvíz (11 otázek, odpověď se rozbalí kliknutím)

1. Proč běží Node jen v Dockeru, a ne na hostiteli?

Reprodukovatelnost a čistota hostitele: každý, kdo repozitář naklonuje, dostane stejné verze nástrojů (node:22) bez ohledu na svůj systém. Nic se neinstaluje globálně, nevznikají konflikty verzí a úklid je docker compose down.

2. Proč jsou testy, lint a companion v profilech?

Běžný docker compose up -d má spustit jen rozcestník. Profily (--profile tests) zapínají služby jen na požádání, takže se zbytečně nespouští npm install ani lint a porty se neblokují.

3. Co v tomto projektu nahrazuje phpstan a phpunit?

Projekt je v JavaScriptu a shellu. Statická analýza je node --check (syntaxe) a ShellCheck (shell skripty); automatické testy node --test a testy brainstorm serveru. Princip zůstává: rychlá kontrola bez spuštění a testy chování.

4. Proč se ShellCheck pouští se `--severity=warning` na skripty a `--severity=error` na testy?

U skriptů, které se dodávají uživatelům, je přísnější práh správný. Testy upstream obsahují záměrné konstrukce (literální ~ v uvozovkách), které by na úrovni warning hlásily falešné poplachy, proto se u nich ohlídají jen skutečné chyby.

5. Proč má služba `web` healthcheck?

Stav healthy říká, že server skutečně odpovídá, ne jen že proces běží. Docker i nástroje nad ním tak poznají zaseknutý kontejner. Check volá /healthz a vrací ok.

6. Proč jsou kontejnery pojmenované s kódem projektu na konci (`web-t375`)?

Pravidlo workspace: automatické názvy Compose se mohou lišit podle adresáře a kolidovat. Pevné názvy se dají předvídat, zastavit a dohledat v docker ps, a kód projektu na konci řadí kontejnery podle služby.

7. Proč je port 8080 společný všem projektům?

Zjednodušuje to dokumentaci a návyky: web je vždy na 8080. Cenou je, že naráz běží jen jeden projekt; před startem dalšího se předchozí zastaví.

8. Proč se tutoriál a prezentace generují skriptem?

Obsah (příklady, kvízy, slovníky) už existuje v Markdown souborech. Generování zaručuje, že tutoriál nikdy nezastará oproti aplikaci a že jde přegenerovat jedním příkazem. Ruční kopie by se rozcházely.

9. Proč některé testy repozitáře v obyčejném `node:22` selhaly a jak se to poznalo?

Chyběly nástroje (jq, mikefarah yq, graphviz, unzip, rsync). Po jejich doinstalování v jednorázovém kontejneru všechny prošly, takže šlo o prostředí, ne o chybu v kódu. Je to ukázka správného postupu: ověřit příčinu, než se tvrdí, že test je rozbitý.

10. Proč je jeden test brainstorm serveru označen jako nestabilní?

Dva testy file watchingu závisí na časování událostí souborového systému; při opakovaných během občas selžou a občas projdou bez změny kódu. Je správné to přiznat a nezakrývat, místo aby se test potichu přeskakoval.

11. Proč jsou testy spouštěny proti skutečnému serveru (spawn) a ne jen jako unit testy funkcí?

Hlavičky, stavové kódy a chování při chybných adresách jsou vlastnosti serveru jako celku. Test, který proces opravdu spustí a zavolá, ověří přesně to, co uvidí uživatel.

Slovník pojmů (15)

Docker Compose

Nástroj pro popis a spuštění více kontejnerů pomocí compose.yaml.

Služba (service)

Jeden kontejner v compose souboru (web, tests, lint, brainstorm).

Profil

Označení služby, která se spouští jen na požádání (--profile tests).

`container_name`

Pevný název kontejneru; zde <služba>-t375.

Healthcheck

Pravidelná kontrola, že kontejner skutečně funguje; výsledek healthy.

`node --check`

Kontrola syntaxe JavaScriptu bez spuštění; rychlá statická analýza.

`node --test`

Vestavěný testovací runner Node (node:test).

ShellCheck

Statický analyzátor shell skriptů.

`--severity`

Práh závažnosti nálezů ShellChecku (error, warning…).

Statická analýza

Kontrola kódu bez jeho spuštění.

Flaky test

Test, který občas selže bez změny kódu; zde dva testy file watchingu.

`build-tutorial.mjs`

Skript generující samostatný docs/tutorial.html z obsahu příkladů.

`build-presentation.mjs`

Skript generující docs/presentation.pptx.

`:ro` mount

Připojení adresáře jen pro čtení.

Port mapping `127.0.0.1:8080:8080`

Port kontejneru je dostupný jen z lokálního počítače.

↑ nahoru

Oblast: stránky příkladů, kvíz a slovník

Jak se z jednoho Markdown souboru vytvoří stránka s popisem, zdrojem, kvízem se skrytými odpověďmi a slovníkem.

Každý příklad je jeden soubor site/examples/<id>.md v jednoduchém značkovacím formátu. Hlavička má titul (# …), druh (kind:), jednovětý souhrn (summary:) a seznam zdrojových souborů (files:). Dále následují sekce: @popis (Markdown), @kviz (řádek ? otázka, odpověď začíná ! ) a @slovnik (řádek = pojem, definice začíná : ). Server soubor při požadavku naparsuje (parseExample) a vykreslí stránku: popis, zdrojový kód v rozbalovacích blocích (malé soubory otevřené, nad 9 000 znaků sbalené), kvíz a slovník jako <details> se skrytou odpovědí a odkazy na předchozí a další příklad.

Kvíz míří na otázky „jak to funguje“, „proč právě takhle“ a „proč je to bezpečné“. Slovník definuje pojmy tak, jak se uplatňují právě v daném příkladu. Test site/test/server.test.mjs vynucuje kvalitu: každý příklad musí mít alespoň 8 otázek, 8 pojmů, popis nad 200 znaků a existující soubory.

Praktický postup (nový příklad): (1) vytvoř site/examples/muj-priklad.md podle vzoru; (2) spusť docker compose --profile tests run --rm tests; (3) otevři /example/muj-priklad; (4) přegeneruj offline tutoriál příkazem node site/build-tutorial.mjs (v Dockeru).

Zdrojový kód

site/server.mjs 544 řádků
// Home page for the Superpowers repository: links to every area (skills,
// docs, harness integrations, tests) and to the examples inside them.
// Zero dependencies; reads the repository mounted at ROOT on every request.
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(process.env.REPO_ROOT || '.');
const PORT = Number(process.env.PORT || 8080);
const VIEWABLE = /\.(md|sh|js|cjs|mjs|ts|json|html|yml|yaml|dot|cmd|txt)$|^[^.]+$/;
const SKIP = new Set(['.git', 'node_modules', 'evals', '.worktrees']);
const PROJECT_CODE = 't375-plugin-superpowers-obra';
const MAX_QUERY = 200;
const MAX_SEARCH_FILE_BYTES = 1024 * 1024;
const MIME = { '.svg': 'image/svg+xml', '.png': 'image/png' };

const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
const fileHref = (rel) => `/file?path=${encodeURIComponent(rel)}`;
const link = (rel, label = rel) => `<a href="${fileHref(rel)}">${esc(label)}</a>`;

function walk(rel) {
  const abs = path.join(ROOT, rel);
  if (!fs.existsSync(abs)) return [];
  return fs.readdirSync(abs, { withFileTypes: true }).flatMap((e) => {
    if (SKIP.has(e.name)) return [];
    const r = path.posix.join(rel, e.name);
    return e.isDirectory() ? walk(r) : [r];
  }).sort();
}

function readFrontmatter(rel) {
  const text = fs.readFileSync(path.join(ROOT, rel), 'utf8');
  const m = text.match(/^---\n([\s\S]*?)\n---/);
  const desc = m && m[1].match(/^description:\s*(.*)$/m);
  return desc ? desc[1].replace(/^"|"$/g, '') : '';
}

const skills = () => fs.readdirSync(path.join(ROOT, 'skills'), { withFileTypes: true })
  .filter((e) => e.isDirectory()).map((e) => e.name).sort();

const SKILL_GROUPS = [
  ['Pracovní postup', ['using-superpowers', 'brainstorming', 'using-git-worktrees', 'writing-plans', 'subagent-driven-development', 'executing-plans', 'finishing-a-development-branch']],
  ['Kvalita a ladění', ['test-driven-development', 'systematic-debugging', 'verification-before-completion']],
  ['Spolupráce a review', ['requesting-code-review', 'receiving-code-review', 'dispatching-parallel-agents']],
  ['Meta', ['writing-skills', 'diagnosing-superpowers']],
];
const groupedSkills = () => {
  const all = skills();
  const groups = SKILL_GROUPS.map(([t, l]) => [t, l.filter((n) => all.includes(n))]);
  const rest = all.filter((n) => !groups.some(([, l]) => l.includes(n)));
  return rest.length ? [...groups, ['Ostatní', rest]] : groups;
};

// Example = supporting material shipped with a skill, plus the test suites.
const EXAMPLE_KINDS = [
  ['areas', 'Oblasti aplikace', /^$/],
  ['prompts', 'Prompty pro subagenty', /\/(prompts\/|[a-z-]*-prompt\.md$|code-reviewer\.md$)/],
  ['templates', 'Šablony', /\/templates\//],
  ['scripts', 'Skripty', /^skills\/[^/]+\/(scripts\/|find-polluter|render-graphs)/],
  ['examples', 'Ukázky kódu', /example/],
  ['tests', 'Testy', /^tests\//],
];
const examplesOf = (files) => EXAMPLE_KINDS.map(([id, title, re]) => ({ id, title, files: files.filter((f) => re.test(f)) }))
  .filter((k) => k.files.length);

// ---------- example units ----------
// One content file per example in site/examples/<id>.md:
//   # Title / kind: / summary: / files: a, b      (header)
//   @popis  markdown | @kviz  "? question" + "! answer" | @slovnik  "= term" + definition
const EX_DIR = path.join(ROOT, 'site', 'examples');
const sectionItems = (body, marker) => {
  const items = [];
  for (const line of body.split('\n')) {
    if (line.startsWith(marker + ' ')) items.push({ head: line.slice(2).trim(), text: [] });
    else if (items.length) items[items.length - 1].text.push(line.replace(/^[!:] ?/, (m, o) => (o === 0 && items[items.length - 1].text.length === 0 ? '' : m)));
  }
  return items.map((i) => ({ head: i.head, text: i.text.join('\n').trim() }));
};

function parseExample(id) {
  const text = fs.readFileSync(path.join(EX_DIR, `${id}.md`), 'utf8');
  const [header, ...parts] = text.split(/^@(?=popis|kviz|slovnik)/m);
  const meta = (k) => (header.match(new RegExp(`^${k}:\\s*(.*)$`, 'm')) || [])[1] || '';
  const sec = Object.fromEntries(parts.map((p) => [p.slice(0, p.indexOf('\n')).trim(), p.slice(p.indexOf('\n') + 1)]));
  return {
    id, title: (header.match(/^#\s+(.*)$/m) || [, id])[1], kind: meta('kind'), summary: meta('summary'),
    files: meta('files').split(',').map((f) => f.trim()).filter(Boolean),
    description: sec.popis || '', quiz: sectionItems(sec.kviz || '', '?'), glossary: sectionItems(sec.slovnik || '', '='),
  };
}

const exampleUnits = () => (fs.existsSync(EX_DIR) ? fs.readdirSync(EX_DIR).filter((f) => f.endsWith('.md')).map((f) => parseExample(f.slice(0, -3))) : [])
  .sort((a, b) => EXAMPLE_KINDS.findIndex((k) => k[0] === a.kind) - EXAMPLE_KINDS.findIndex((k) => k[0] === b.kind) || a.id.localeCompare(b.id));
const exampleKinds = () => {
  const units = exampleUnits();
  return EXAMPLE_KINDS.map(([id, title]) => ({ id, title, units: units.filter((u) => u.kind === id) })).filter((k) => k.units.length);
};

const harnesses = () => fs.readdirSync(ROOT, { withFileTypes: true })
  .filter((e) => e.isDirectory() && /^\.(.+-plugin|opencode|pi|agents)$/.test(e.name)).map((e) => e.name).sort();

const SECTIONS = {
  'Dokumentace': { dirs: ['docs'], exclude: /^docs\/(plans|superpowers)\//, note: 'Návody k portování, testování a platformám.' },
  'Plány': { dirs: ['docs/plans'], note: 'Historické návrhy a implementační plány.' },
  'Specifikace': { dirs: ['docs/superpowers/specs'], note: 'Návrhy změn a výsledky evaluací.' },
  'Hooks': { dirs: ['hooks'], note: 'Session-start hooky pro jednotlivé agenty.' },
  'Skripty repozitáře': { dirs: ['scripts'], note: 'Release a údržbové skripty.' },
};

// ---------- minimal markdown renderer ----------
function inline(s) {
  return esc(s)
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>')
    .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, h) => `<a href="${/^(https?:|#)/.test(h) ? h : '#'}" rel="noopener noreferrer">${t}</a>`);
}

function markdown(src) {
  const lines = src.replace(/^---\n[\s\S]*?\n---\n/, '').split('\n');
  const out = [];
  let i = 0;
  while (i < lines.length) {
    const l = lines[i];
    let m;
    if ((m = l.match(/^```(\w*)/))) {
      const buf = [];
      for (i++; i < lines.length && !lines[i].startsWith('```'); i++) buf.push(lines[i]);
      i++;
      out.push(`<pre><code>${esc(buf.join('\n'))}</code></pre>`);
    } else if ((m = l.match(/^(#{1,6})\s+(.*)/))) {
      out.push(`<h${m[1].length}>${inline(m[2])}</h${m[1].length}>`); i++;
    } else if (/^\s*[-*]\s+/.test(l) || /^\s*\d+\.\s+/.test(l)) {
      const tag = /^\s*\d+\./.test(l) ? 'ol' : 'ul';
      const items = [];
      while (i < lines.length && (/^\s*([-*]|\d+\.)\s+/.test(lines[i]) || /^\s{2,}\S/.test(lines[i]))) {
        if (/^\s*([-*]|\d+\.)\s+/.test(lines[i])) items.push(lines[i].replace(/^\s*([-*]|\d+\.)\s+/, ''));
        else items[items.length - 1] += ' ' + lines[i].trim();
        i++;
      }
      out.push(`<${tag}>${items.map((x) => `<li>${inline(x)}</li>`).join('')}</${tag}>`);
    } else if (l.startsWith('>')) {
      const buf = [];
      while (i < lines.length && lines[i].startsWith('>')) buf.push(lines[i++].replace(/^>\s?/, ''));
      out.push(`<blockquote>${inline(buf.join(' '))}</blockquote>`);
    } else if (/^\|.*\|\s*$/.test(l) && /^\|[\s:|-]+\|\s*$/.test(lines[i + 1] || '')) {
      const cells = (r) => r.replace(/^\||\|\s*$/g, '').split('|').map((c) => c.trim());
      const head = cells(l); i += 2;
      const rows = [];
      while (i < lines.length && /^\|.*\|\s*$/.test(lines[i])) rows.push(cells(lines[i++]));
      out.push(`<div class="tablewrap"><table><thead><tr>${head.map((c) => `<th>${inline(c)}</th>`).join('')}</tr></thead><tbody>${rows.map((r) => `<tr>${r.map((c) => `<td>${inline(c)}</td>`).join('')}</tr>`).join('')}</tbody></table></div>`);
    } else if (/^---+\s*$/.test(l)) {
      out.push('<hr>'); i++;
    } else if (l.trim() === '') {
      i++;
    } else {
      const buf = [];
      while (i < lines.length && lines[i].trim() !== '' && !/^(```|#{1,6}\s|>|\s*[-*]\s|\s*\d+\.\s|\|)/.test(lines[i])) buf.push(lines[i++]);
      if (!buf.length) { buf.push(lines[i++]); }
      out.push(`<p>${inline(buf.join(' '))}</p>`);
    }
  }
  return out.join('\n');
}

// ---------- full-text search ----------
const MAX_FILES = 100;
const MAX_SNIPPETS = 4;
const searchableFiles = () => fs.readdirSync(ROOT, { withFileTypes: true })
  .filter((e) => !SKIP.has(e.name))
  .flatMap((e) => (e.isDirectory() ? walk(e.name) : [e.name]))
  .filter((f) => VIEWABLE.test(path.basename(f)) && path.basename(f) !== 'package-lock.json');

const queryRegex = (q) => new RegExp(esc(q).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
const mark = (escaped, re) => escaped.replace(re, '<mark>$&</mark>');
// Highlights text nodes only: tags and character entities are left intact.
const markHtml = (html, re) => html.split(/(<[^>]+>|&[a-z]+;)/).map((p) => (/^[<&]/.test(p) && /[>;]$/.test(p) ? p : mark(p, re))).join('');

function snippet(line, q) {
  const t = line.trim();
  const at = t.toLowerCase().indexOf(q.toLowerCase());
  const from = Math.max(0, at - 70);
  return (from > 0 ? '…' : '') + t.slice(from, from + 200) + (t.length - from > 200 ? '…' : '');
}

const searchForm = (q, cls = '') => `<form class="searchbox ${cls}" action="/search" method="get" role="search">
<input name="q" value="${esc(q)}" placeholder="Hledat v popisech a zdrojových kódech…" autocomplete="off" aria-label="Fulltextové vyhledávání"><button>Hledat</button></form>`;

function searchPage(raw) {
  const q = raw.trim().slice(0, MAX_QUERY);
  const head = `<h1>Vyhledávání</h1>${searchForm(q)}`;
  if (q.length < 2) return page('Vyhledávání', `${head}<p class="lead">Zadej alespoň 2 znaky. Hledá se v popisech skills a v obsahu všech souborů repozitáře.</p>`, '', [['', 'Vyhledávání']], q);
  const re = queryRegex(q);
  const hl = `&amp;hl=${encodeURIComponent(q)}`;
  const test = (s) => { re.lastIndex = 0; return re.test(s); };

  const skillHits = skills().map((n) => ({ n, d: readFrontmatter(`skills/${n}/SKILL.md`) })).filter(({ n, d }) => test(n) || test(d));
  const fileHits = [];
  let total = 0;
  for (const f of searchableFiles()) {
    const abs = path.join(ROOT, f);
    if (fs.statSync(abs).size > MAX_SEARCH_FILE_BYTES) continue;
    const text = fs.readFileSync(abs, 'utf8');
    const lines = text.split('\n').map((l, i) => [i + 1, l]).filter(([, l]) => test(l));
    const nameHit = test(f);
    if (!lines.length && !nameHit) continue;
    total += lines.length;
    fileHits.push({ f, lines, nameHit });
  }
  fileHits.sort((a, b) => (b.nameHit - a.nameHit) || (b.lines.length - a.lines.length) || a.f.localeCompare(b.f));
  const shown = fileHits.slice(0, MAX_FILES);

  const skillsHtml = skillHits.length ? `<h2>Popisy skills <span class="badge">${skillHits.length}</span></h2><div class="grid">${skillHits.map(({ n, d }) =>
    `<a class="card" href="/skill/${n}"><b>${mark(esc(n), re)}</b><small>${mark(esc(d), re)}</small></a>`).join('')}</div>` : '';
  const filesHtml = shown.length ? `<h2>Zdrojové soubory <span class="badge">${fileHits.length}</span></h2>
<p class="lead">${total} shod v ${fileHits.length} souborech${fileHits.length > shown.length ? ` (zobrazeno prvních ${shown.length})` : ''}.</p>
<div class="results">${shown.map(({ f, lines }) => `<div class="result"><a class="rtitle" href="${f === 'site/guide.md' ? `/guide?hl=${encodeURIComponent(q)}` : /^site\/examples\/.+\.md$/.test(f) ? `/example/${path.posix.basename(f, '.md')}?hl=${encodeURIComponent(q)}` : `${fileHref(f)}${hl}`}">${mark(esc(f), re)}</a>${lines.length ? `<span class="badge">${lines.length}</span>` : ''}
${lines.slice(0, MAX_SNIPPETS).map(([n, l]) => `<div class="hit"><span class="ln">${n}</span><code>${mark(esc(snippet(l, q)), re)}</code></div>`).join('')}
${lines.length > MAX_SNIPPETS ? `<div class="more">… a dalších ${lines.length - MAX_SNIPPETS} shod</div>` : ''}</div>`).join('')}</div>` : '';
  const none = !skillsHtml && !filesHtml ? `<p class="lead">Pro „${esc(q)}“ nebylo nic nalezeno.</p>` : '';
  return page(`Hledání: ${q}`, `${head}${skillsHtml}${filesHtml}${none}`, '', [['', 'Vyhledávání']], q);
}

// ---------- layout ----------
const CSS = `
:root{color-scheme:light dark;--bg:#f7f8fa;--panel:#fff;--fg:#1b1f2a;--mut:#667085;--bd:#e4e7ec;--ac:#5b5bd6;--ac-soft:#eeeefc;--code:#f2f4f7;--shadow:0 1px 2px rgba(16,24,40,.06),0 1px 3px rgba(16,24,40,.08);--side:292px}
@media(prefers-color-scheme:dark){:root{--bg:#0e1117;--panel:#151a23;--fg:#e7eaf0;--mut:#8b95a7;--bd:#252c39;--ac:#8b8bf0;--ac-soft:#232346;--code:#1d2330;--shadow:none}}
*{box-sizing:border-box}html{scroll-behavior:smooth}
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.65 Inter,system-ui,-apple-system,"Segoe UI",sans-serif}
a{color:var(--ac);text-decoration:none}a:hover{text-decoration:underline}
#nav-toggle{display:none}
.side{position:fixed;inset:0 auto 0 0;width:var(--side);background:var(--panel);border-right:1px solid var(--bd);display:flex;flex-direction:column;z-index:20}
.brand{display:flex;align-items:center;gap:.7rem;padding:1.1rem 1.2rem;border-bottom:1px solid var(--bd);color:var(--fg);font-weight:700;font-size:1.05rem}
.brand img{width:30px;height:30px;border-radius:7px}.brand small{display:block;font-weight:500;color:var(--mut);font-size:.75rem;line-height:1.1}
.brand:hover{text-decoration:none}
.code{display:block;font-style:italic;font-weight:400;font-size:.72rem;line-height:1.3;color:var(--mut)}
.search{padding:.8rem 1rem .4rem}.search input{width:100%;padding:.5rem .75rem;border:1px solid var(--bd);border-radius:8px;background:var(--bg);color:var(--fg);font:inherit;font-size:.88rem}
.search input:focus{outline:2px solid var(--ac);outline-offset:-1px}
.menu{flex:1;overflow-y:auto;padding:.4rem .6rem 1.5rem}
.menu a.top,.menu summary{display:flex;align-items:center;gap:.5rem;padding:.42rem .6rem;border-radius:7px;color:var(--fg);font-weight:600;font-size:.9rem;cursor:pointer;list-style:none}
.menu summary::-webkit-details-marker{display:none}
.menu summary::after{content:"›";margin-left:auto;color:var(--mut);transition:transform .15s}
details[open]>summary::after{transform:rotate(90deg)}
.menu a.top:hover,.menu summary:hover{background:var(--bg);text-decoration:none}
.menu .count{margin-left:auto;font-weight:500;font-size:.72rem;color:var(--mut);background:var(--bg);border-radius:99px;padding:0 .45rem}
.menu summary .count{margin-left:auto;margin-right:.3rem}
.menu .grp{font-size:.68rem;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);padding:.6rem .6rem .15rem}
.menu ul{list-style:none;margin:0 0 .3rem;padding:0 0 0 .55rem;border-left:1px solid var(--bd);margin-left:1rem}
.menu li a{display:block;padding:.24rem .6rem;border-radius:6px;color:var(--mut);font-size:.84rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.menu li a:hover{color:var(--fg);background:var(--bg);text-decoration:none}
.menu a.active{background:var(--ac-soft)!important;color:var(--ac)!important;font-weight:600}
.menu .hide{display:none}
.top-bar{display:none}
.skip{position:absolute;left:-999px;top:0;background:var(--ac);color:#fff;padding:.5rem 1rem;z-index:100}.skip:focus{left:0}
.content{margin-left:var(--side);min-height:100vh}
main{max-width:980px;margin:0 auto;padding:2rem 2.2rem 4rem}
.crumbs{font-size:.82rem;color:var(--mut);margin-bottom:1rem}.crumbs a{color:var(--mut)}.crumbs span{margin:0 .35rem}
h1{font-size:1.9rem;line-height:1.25;margin:.2rem 0 .6rem;letter-spacing:-.02em}
h2{font-size:1.25rem;margin:2.4rem 0 .9rem;letter-spacing:-.01em}h3{font-size:1.05rem;margin:1.6rem 0 .5rem}
.lead{color:var(--mut);font-size:1.05rem;max-width:70ch}
.hero{background:linear-gradient(135deg,var(--ac) 0%,#8b5cf6 100%);color:#fff;border-radius:16px;padding:2.2rem 2.4rem;margin-bottom:1.6rem;box-shadow:var(--shadow)}
.hero h1{margin:0 0 .5rem;font-size:2.2rem}.hero p{margin:0;opacity:.92;max-width:62ch}
.hero .links{margin-top:1.2rem;display:flex;flex-wrap:wrap;gap:.6rem}
.hero .links a{background:rgba(255,255,255,.18);color:#fff;padding:.4rem .9rem;border-radius:99px;font-size:.85rem;font-weight:600}
.hero .links a:hover{background:rgba(255,255,255,.3);text-decoration:none}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.8rem;margin-bottom:.5rem}
.stat{background:var(--panel);border:1px solid var(--bd);border-radius:12px;padding:.9rem 1.1rem;box-shadow:var(--shadow)}
.stat b{display:block;font-size:1.6rem;line-height:1.2}.stat span{color:var(--mut);font-size:.82rem}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:.9rem}
.card{display:block;background:var(--panel);border:1px solid var(--bd);border-radius:12px;padding:1rem 1.1rem;color:var(--fg);box-shadow:var(--shadow);transition:transform .12s,border-color .12s,box-shadow .12s}
.card:hover{transform:translateY(-2px);border-color:var(--ac);text-decoration:none;box-shadow:0 6px 16px rgba(16,24,40,.1)}
.card b{display:block;margin-bottom:.25rem;color:var(--ac)}
.card small{display:block;color:var(--mut);font-size:.84rem;line-height:1.5;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
.files{list-style:none;padding:0;margin:0;background:var(--panel);border:1px solid var(--bd);border-radius:12px;box-shadow:var(--shadow);overflow:hidden}
.files li{border-bottom:1px solid var(--bd)}.files li:last-child{border:0}
.files a{display:flex;gap:.6rem;align-items:baseline;padding:.55rem 1rem;color:var(--fg);font-size:.9rem}
.files a:hover{background:var(--ac-soft);text-decoration:none}
.files .dir{color:var(--mut);font-size:.78rem;font-family:ui-monospace,monospace;margin-left:auto;white-space:nowrap}
.badge{display:inline-block;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;padding:.05rem .45rem;border-radius:5px;background:var(--ac-soft);color:var(--ac)}
pre{background:var(--code);border:1px solid var(--bd);border-radius:10px;padding:1rem 1.2rem;overflow:auto;font:13px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace}
code{background:var(--code);padding:.1rem .35rem;border-radius:5px;font:.88em ui-monospace,SFMono-Regular,Menlo,monospace}pre code{background:none;padding:0}
.doc{background:var(--panel);border:1px solid var(--bd);border-radius:12px;padding:1.2rem 2rem 1.6rem;box-shadow:var(--shadow)}
.doc h1{font-size:1.6rem}.doc h2{border-bottom:1px solid var(--bd);padding-bottom:.3rem}
blockquote{margin:1rem 0;padding:.3rem 1rem;border-left:3px solid var(--ac);background:var(--ac-soft);border-radius:0 8px 8px 0}
.tablewrap{overflow:auto}table{border-collapse:collapse;margin:1rem 0;font-size:.9rem}th,td{border:1px solid var(--bd);padding:.4rem .75rem;text-align:left}th{background:var(--code)}
hr{border:0;border-top:1px solid var(--bd);margin:1.6rem 0}
.tabs{display:inline-flex;border:1px solid var(--bd);border-radius:8px;overflow:hidden;margin-bottom:1rem;background:var(--panel)}
.tabs a{padding:.35rem .9rem;font-size:.84rem;color:var(--mut)}.tabs a.on{background:var(--ac);color:#fff}.tabs a:hover{text-decoration:none}
.qa{background:var(--panel);border:1px solid var(--bd);border-radius:10px;margin:.5rem 0;box-shadow:var(--shadow)}
.qa summary{padding:.7rem 1rem;cursor:pointer;font-weight:600;list-style:none;display:flex;gap:.7rem;align-items:baseline}
.qa summary::-webkit-details-marker{display:none}.qa summary::before{content:"+";color:var(--ac);font-weight:700}.qa[open] summary::before{content:"-"}
.qa[open] summary{border-bottom:1px solid var(--bd)}.qa .ans{padding:.3rem 1.2rem .6rem 2.4rem;font-weight:400}
.qn{color:var(--ac);min-width:1.6rem}.qa b{color:var(--ac)}
.toggles{display:flex;gap:.5rem;margin:.3rem 0 .6rem}.toggles button{border:1px solid var(--bd);background:var(--panel);color:var(--fg);border-radius:8px;padding:.3rem .8rem;font:inherit;font-size:.82rem;cursor:pointer}
.toggles button:hover{border-color:var(--ac);color:var(--ac)}
.src{background:var(--panel);border:1px solid var(--bd);border-radius:10px;margin:.6rem 0}.src summary{padding:.6rem 1rem;cursor:pointer;display:flex;gap:.6rem;align-items:center;flex-wrap:wrap}
.src summary a{margin-left:auto;font-size:.82rem}.src pre{margin:0;border:0;border-top:1px solid var(--bd);border-radius:0 0 10px 10px;max-height:70vh}
.pager{display:grid;grid-template-columns:1fr 1fr;gap:.9rem;margin-top:2.5rem}.pager .card:last-child{text-align:right}
mark{background:#ffe27a;color:#1b1f2a;border-radius:3px;padding:0 .12em}
.searchbox{display:flex;gap:.5rem;margin:.4rem 0 1.2rem}
.searchbox input{flex:1;padding:.65rem .9rem;border:1px solid var(--bd);border-radius:10px;background:var(--panel);color:var(--fg);font:inherit}
.searchbox input:focus{outline:2px solid var(--ac);outline-offset:-1px}
.searchbox button{padding:.65rem 1.2rem;border:0;border-radius:10px;background:var(--ac);color:#fff;font:inherit;font-weight:600;cursor:pointer}
.searchbox.hero-search{margin:1.2rem 0 0;max-width:640px}.hero-search input{border:0;box-shadow:0 2px 8px rgba(0,0,0,.15)}
.hero-search button{background:rgba(255,255,255,.2)}.hero-search button:hover{background:rgba(255,255,255,.32)}
.results{display:flex;flex-direction:column;gap:.7rem}
.result{background:var(--panel);border:1px solid var(--bd);border-radius:12px;padding:.7rem 1rem;box-shadow:var(--shadow)}
.rtitle{font-weight:600;font-size:.92rem;margin-right:.5rem;word-break:break-all}
.hit{display:flex;gap:.7rem;padding:.15rem 0;font-size:.84rem;overflow:hidden}.hit .ln{color:var(--mut);min-width:2.6rem;text-align:right;font:12px ui-monospace,monospace;padding-top:.2rem}
.hit code{background:none;padding:0;white-space:pre-wrap;word-break:break-word;color:var(--fg)}.more{color:var(--mut);font-size:.8rem;padding-left:3.3rem}
@media(max-width:900px){
 .side{transform:translateX(-100%);transition:transform .2s;box-shadow:var(--shadow)}
 #nav-toggle:checked~.side{transform:none}
 #nav-toggle:checked~.scrim{display:block}
 .scrim{display:none;position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:15}
 .content{margin-left:0}
 .top-bar{display:flex;align-items:center;gap:.8rem;position:sticky;top:0;z-index:10;background:var(--panel);border-bottom:1px solid var(--bd);padding:.6rem 1rem;font-weight:700}
 .top-bar label{cursor:pointer;font-size:1.4rem;line-height:1}
 main{padding:1.2rem 1rem 3rem}.hero{padding:1.5rem}.doc{padding:1rem 1.1rem}
}`;

const SEARCH_JS = `
const q=document.getElementById('q');
q&&q.addEventListener('input',()=>{
  const v=q.value.trim().toLowerCase();
  document.querySelectorAll('.menu li').forEach(li=>li.classList.toggle('hide',v&&!li.textContent.toLowerCase().includes(v)));
  document.querySelectorAll('.menu details').forEach(d=>{if(v)d.open=[...d.querySelectorAll('li')].some(li=>!li.classList.contains('hide'));});
});
document.querySelectorAll('.toggles button').forEach(b=>b.addEventListener('click',()=>{let n=b.parentElement.nextElementSibling;while(n&&n.classList.contains('qa')){n.open=b.dataset.all==='open';n=n.nextElementSibling;}}));
document.addEventListener('keydown',e=>{if(e.key==='/'&&document.activeElement!==q){e.preventDefault();q&&q.focus();}});
const a=document.querySelector('.menu a.active');a&&a.scrollIntoView({block:'center'});`;

function sidebar(active, query = '') {
  const li = (href, label) => `<li><a href="${href}"${href === active ? ' class="active"' : ''}>${esc(label)}</a></li>`;
  const group = (title, count, items, open) => `<details${open ? ' open' : ''}><summary>${title}<span class="count">${count}</span></summary>${items}</details>`;
  const isIn = (hrefs) => hrefs.includes(active);

  const skillGroups = groupedSkills();
  const skillHrefs = skills().map((n) => `/skill/${n}`);
  const skillsHtml = skillGroups.map(([t, l]) => `<div class="grp">${t}</div><ul>${l.map((n) => li(`/skill/${n}`, n)).join('')}</ul>`).join('');

  const docNames = Object.keys(SECTIONS);
  const docHrefs = docNames.map((t) => `/section/${encodeURIComponent(t)}`);
  const harnessNames = harnesses();
  const harnessHrefs = harnessNames.map((h) => `/section/${encodeURIComponent(h)}`);
  const ex = exampleKinds();
  const exHrefs = ['/examples', ...ex.map((k) => `/examples#${k.id}`)];

  return `<aside class="side">
<a class="brand" href="/"><img src="/assets/app-icon.png" alt=""><span>Superpowers<em class="code">${PROJECT_CODE}</em><small>rozcestník repozitáře</small></span></a>
<form class="search" action="/search" method="get" role="search"><input id="q" name="q" type="search" value="${esc(query)}" placeholder="Hledat v repozitáři (/)" autocomplete="off" aria-label="Hledat"></form>
<nav class="menu" aria-label="Hlavní navigace">
<a class="top${active === '/' ? ' active' : ''}" href="/">Úvod</a>
${group('Skills', skills().length, skillsHtml, isIn(skillHrefs))}
${group('Dokumentace', docNames.length, `<ul>${docNames.map((t) => li(`/section/${encodeURIComponent(t)}`, t)).join('')}</ul>`, isIn(docHrefs))}
${group('Integrace s agenty', harnessNames.length, `<ul>${harnessNames.map((h) => li(`/section/${encodeURIComponent(h)}`, h)).join('')}</ul>`, isIn(harnessHrefs))}
${group('Příklady', ex.length, `<ul>${li('/examples', 'Všechny příklady')}${ex.map((k) => li(`/examples#${k.id}`, k.title)).join('')}</ul>`, isIn(exHrefs))}
<a class="top${active === '/guide' ? ' active' : ''}" href="/guide">Závěrečný díl: AI v praxi</a>
<div class="grp">Projekt</div>
<ul>${['README.md', 'AGENTS.md', 'RELEASE-NOTES.md', 'LICENSE'].map((f) => li(fileHref(f), f)).join('')}</ul>
</nav></aside>`;
}

function page(title, body, active = '', crumbs = [], query = '') {
  const trail = crumbs.length ? `<div class="crumbs"><a href="/">Úvod</a>${crumbs.map(([h, t]) => `<span>/</span>${h ? `<a href="${h}">${esc(t)}</a>` : esc(t)}`).join('')}</div>` : '';
  return `<!doctype html><html lang="cs"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(title)} · Superpowers</title><link rel="icon" href="/assets/superpowers-small.svg"><style>${CSS}</style></head>
<body><a class="skip" href="#main">Přeskočit na obsah</a><input type="checkbox" id="nav-toggle">${sidebar(active, query)}<label class="scrim" for="nav-toggle"></label>
<div class="content"><div class="top-bar"><label for="nav-toggle" aria-label="Menu">☰</label><span>Superpowers<em class="code">${PROJECT_CODE}</em></span></div>
<main id="main">${trail}${body}</main></div><script>${SEARCH_JS}</script></body></html>`;
}

// ---------- pages ----------
const dirOf = (f) => path.posix.dirname(f);
const relDir = (f, strip) => dirOf(f).replace(strip, '').replace(/^\//, '');
const fileList = (files, strip = '') => `<ul class="files">${files.map((f) => `<li><a href="${fileHref(f)}"><span>${esc(path.posix.basename(f))}</span><span class="dir">${esc(relDir(f, strip))}</span></a></li>`).join('')}</ul>`;

function home() {
  const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
  const names = skills();
  const ex = exampleKinds();
  const exCount = ex.reduce((n, k) => n + k.units.length, 0);
  const docCount = Object.values(SECTIONS).reduce((n, s) => n + s.dirs.flatMap(walk).filter((f) => !s.exclude || !s.exclude.test(f)).length, 0);
  const card = (href, title, text) => `<a class="card" href="${href}"><b>${esc(title)}</b><small>${esc(text)}</small></a>`;
  return page('Úvod', `
<section class="hero"><h1>Superpowers</h1>
<p>Kompletní metodika vývoje softwaru pro kódovací agenty, postavená na komponovatelných skills. Tento rozcestník vede ke všem oblastem repozitáře i k příkladům.</p>
<div class="links"><a href="${fileHref('README.md')}">README</a><a href="${fileHref('AGENTS.md')}">AGENTS</a><a href="${fileHref('RELEASE-NOTES.md')}">Release notes</a><a href="/examples">Příklady</a></div>${searchForm('', 'hero-search')}</section>
<div class="stats"><div class="stat"><b>${esc(pkg.version)}</b><span>verze</span></div><div class="stat"><b>${names.length}</b><span>skills</span></div>
<div class="stat"><b>${harnesses().length}</b><span>integrací s agenty</span></div><div class="stat"><b>${docCount}</b><span>dokumentů</span></div><div class="stat"><b>${exCount}</b><span>příkladů</span></div></div>
<h2 id="skills">Skills</h2>
${groupedSkills().map(([t, l]) => `<h3>${t}</h3><div class="grid">${l.map((n) => card(`/skill/${n}`, n, readFrontmatter(`skills/${n}/SKILL.md`))).join('')}</div>`).join('')}
<h2 id="docs">Dokumentace a návrhy</h2><div class="grid">${Object.entries(SECTIONS).map(([t, s]) => card(`/section/${encodeURIComponent(t)}`, t, s.note)).join('')}</div>
<h2 id="harnesses">Integrace s agenty</h2><div class="grid">${harnesses().map((h) => card(`/section/${encodeURIComponent(h)}`, h, `${walk(h).length} souborů`)).join('')}</div>
<h2 id="guide">Závěrečný díl</h2><div class="grid">${card('/guide', 'Praktický průvodce: AI dovednosti, tools a triky', 'Jak pracovat s kódovacím agentem užitečně, bezpečně a levně: skills, subagenti, hooky, kontext, ověřování a časté problémy.')}</div>
<h2 id="examples">Příklady</h2><p class="lead">Ke každému příkladu patří stránka s popisem, zdrojovým kódem, kvízem a slovníkem pojmů.</p>
${ex.map((k) => `<h3 id="${k.id}">${k.title} <span class="badge">${k.units.length}</span></h3><div class="grid">${k.units.map((u) => card(`/example/${u.id}`, u.title, u.summary)).join('')}</div>`).join('')}`, '/');
}

function guidePage(hl = '') {
  const file = path.join(ROOT, 'site', 'guide.md');
  if (!fs.existsSync(file)) return null;
  const html = `<div class="doc">${markdown(fs.readFileSync(file, 'utf8'))}</div>`;
  return page('Praktický průvodce', hl.length >= 2 ? markHtml(html, queryRegex(hl)) : html, '/guide', [['', 'Závěrečný díl']], hl);
}

function skillPage(name) {
  if (!skills().includes(name)) return null;
  const dir = `skills/${name}`;
  const files = walk(dir);
  const ex = examplesOf(files);
  const exSet = new Set(ex.flatMap((k) => k.files));
  const rest = files.filter((f) => !exSet.has(f));
  const skillMd = fs.readFileSync(path.join(ROOT, dir, 'SKILL.md'), 'utf8');
  return page(name, `<h1>${esc(name)}</h1><p class="lead">${esc(readFrontmatter(`${dir}/SKILL.md`))}</p>
<h2>Soubory skillu</h2>${fileList(rest, dir)}
${ex.map((k) => `<h2>${k.title}</h2>${fileList(k.files, dir)}`).join('')}
<h2>SKILL.md</h2><div class="doc">${markdown(skillMd)}</div>`, `/skill/${name}`, [['', 'Skills'], ['', name]]);
}

function sectionPage(title) {
  const s = SECTIONS[title];
  const dirs = s ? s.dirs : harnesses().includes(title) ? [title] : null;
  if (!dirs) return null;
  const files = dirs.flatMap(walk).filter((f) => !s || !s.exclude || !s.exclude.test(f));
  return page(title, `<h1>${esc(title)}</h1><p class="lead">${esc(s ? s.note : 'Konfigurace integrace s agentem.')}</p>${fileList(files, dirs[0])}`,
    `/section/${encodeURIComponent(title)}`, [['', s ? 'Dokumentace' : 'Integrace'], ['', title]]);
}

const examplesPage = () => page('Příklady', `<h1>Příklady</h1>
<p class="lead">Prompty, šablony, skripty, ukázky a testy dodávané s repozitářem. U každého je popis, zdrojový kód, kvíz a slovník pojmů.</p>
${exampleKinds().map((k) => `<h2 id="${k.id}">${k.title} <span class="badge">${k.units.length}</span></h2><div class="grid">${k.units.map((u) => `<a class="card" href="/example/${u.id}"><b>${esc(u.title)}</b><small>${esc(u.summary)}</small></a>`).join('')}</div>`).join('')}`, '/examples', [['', 'Příklady']]);

function examplePage(id, hl = '') {
  const units = exampleUnits();
  const idx = units.findIndex((u) => u.id === id);
  if (idx < 0) return null;
  const u = units[idx];
  const kindTitle = (EXAMPLE_KINDS.find((k) => k[0] === u.kind) || [, u.kind])[1];
  const qa = (items, term) => items.map((x, n) => `<details class="qa"><summary>${term ? '' : `<span class="qn">${n + 1}</span>`}${term ? `<b>${inline(x.head)}</b>` : inline(x.head)}</summary><div class="ans">${markdown(x.text)}</div></details>`).join('');
  const toggles = '<div class="toggles"><button type="button" data-all="open">Rozbalit vše</button><button type="button" data-all="close">Sbalit vše</button></div>';
  const sources = u.files.filter((f) => fs.existsSync(path.join(ROOT, f))).map((f) => {
    const text = fs.readFileSync(path.join(ROOT, f), 'utf8');
    return `<details class="src"${text.length < 9000 ? ' open' : ''}><summary><code>${esc(f)}</code> <span class="badge">${text.split('\n').length} řádků</span> <a href="${fileHref(f)}">otevřít samostatně</a></summary><pre><code>${esc(text)}</code></pre></details>`;
  }).join('');
  const nav = (x, label) => (x ? `<a class="card" href="/example/${x.id}"><small>${label}</small><b>${esc(x.title)}</b></a>` : '<span></span>');
  const body = `<h1>${esc(u.title)}</h1><p><span class="badge">${kindTitle}</span></p>
<h2>Popis příkladu</h2><div class="doc">${markdown(u.description)}</div>
<h2>Zdrojový kód</h2>${sources}
<h2 id="kviz">Kvíz <span class="badge">${u.quiz.length} otázek</span></h2><p class="lead">Klikni na otázku a odpověď se rozbalí.</p>${toggles}${qa(u.quiz, false)}
<h2 id="slovnik">Slovník pojmů <span class="badge">${u.glossary.length} pojmů</span></h2><p class="lead">Pojmy vysvětlené tak, jak se uplatňují právě v tomto příkladu.</p>${toggles}${qa(u.glossary, true)}
<div class="pager">${nav(units[idx - 1], '← předchozí')}${nav(units[idx + 1], 'další →')}</div>`;
  return page(u.title, hl.length >= 2 ? markHtml(body, queryRegex(hl)) : body,
    `/example/${u.id}`, [['/examples', 'Příklady'], ['', u.title]], hl);
}

function filePage(rel, raw, hl = '') {
  const abs = path.resolve(ROOT, rel);
  const inside = abs.startsWith(ROOT + path.sep) && !abs.split(path.sep).some((p) => p === '.git' || p === 'node_modules');
  if (!inside || !fs.existsSync(abs) || !fs.statSync(abs).isFile() || !VIEWABLE.test(path.basename(abs))) return null;
  const text = fs.readFileSync(abs, 'utf8');
  const isMd = abs.endsWith('.md');
  const q = fileHref(rel);
  const unit = exampleUnits().find((x) => x.files.includes(rel));
  const re = hl.length >= 2 ? queryRegex(hl) : null;
  const qs = hl ? `&amp;hl=${encodeURIComponent(hl)}` : '';
  const tabs = isMd ? `<div class="tabs"><a class="${raw ? '' : 'on'}" href="${q}${qs}">Náhled</a><a class="${raw ? 'on' : ''}" href="${q}&amp;raw=1${qs}">Zdroj</a></div>` : '';
  const html = isMd && !raw ? `<div class="doc">${markdown(text)}</div>` : `<pre><code>${esc(text)}</code></pre>`;
  const body = re ? `<p class="lead">Zvýrazněno: <mark>${esc(hl)}</mark> · <a href="/search?q=${encodeURIComponent(hl)}">zpět na výsledky</a></p>${markHtml(html, re)}` : html;
  const parent = rel.split('/')[0];
  const crumbs = [[crumbHref(parent), rel.includes('/') ? parent : 'Projekt'], ['', path.basename(rel)]];
  const banner = unit ? `<p class="lead">Tento soubor je součástí příkladu <a href="/example/${unit.id}">${esc(unit.title)}</a> (popis, kvíz, slovník).</p>` : '';
  return page(path.basename(rel), `${banner}${tabs}${body}`, q, crumbs, hl);
}

function crumbHref(top) {
  if (top === 'skills') return '';
  if (top === 'docs') return `/section/Dokumentace`;
  if (top === 'tests') return '/examples#tests';
  if (harnesses().includes(top)) return `/section/${encodeURIComponent(top)}`;
  return '';
}

const SCRIPT_HASH = crypto.createHash('sha256').update(SEARCH_JS).digest('base64');
const SECURITY_HEADERS = {
  'Content-Security-Policy': `default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-${SCRIPT_HASH}'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
  'X-Content-Type-Options': 'nosniff',
  'X-Frame-Options': 'DENY',
  'Referrer-Policy': 'no-referrer',
  'Cross-Origin-Resource-Policy': 'same-origin',
};

function send(req, res, status, body, type = 'text/html; charset=utf-8') {
  res.writeHead(status, { ...SECURITY_HEADERS, 'content-type': type, ...(status === 405 ? { Allow: 'GET, HEAD' } : {}) });
  res.end(req.method === 'HEAD' ? undefined : body);
}

export function route(url) {
  const u = new URL(url, 'http://x');
  const arg = (prefix) => decodeURIComponent(u.pathname.slice(prefix.length));
  const hl = (u.searchParams.get('hl') || '').slice(0, MAX_QUERY);
  if (u.pathname === '/') return home();
  if (u.pathname === '/examples') return examplesPage();
  if (u.pathname === '/guide') return guidePage(hl);
  if (u.pathname.startsWith('/example/')) return examplePage(arg('/example/'), hl);
  if (u.pathname.startsWith('/skill/')) return skillPage(arg('/skill/'));
  if (u.pathname.startsWith('/section/')) return sectionPage(arg('/section/'));
  if (u.pathname === '/file') return filePage(u.searchParams.get('path') || '', u.searchParams.has('raw'), hl);
  if (u.pathname === '/search') return searchPage(u.searchParams.get('q') || '');
  return null;
}

export function createServer() {
  return http.createServer((req, res) => {
    if (req.method !== 'GET' && req.method !== 'HEAD') return send(req, res, 405, 'Method Not Allowed', 'text/plain; charset=utf-8');
    let pathname = '';
    try { pathname = new URL(req.url, 'http://x').pathname; } catch { return send(req, res, 400, 'Bad Request', 'text/plain; charset=utf-8'); }
    if (pathname === '/healthz') return send(req, res, 200, 'ok', 'text/plain; charset=utf-8');
    if (pathname.startsWith('/assets/')) {
      const f = path.join(ROOT, 'assets', path.basename(pathname));
      if (MIME[path.extname(f)] && fs.existsSync(f)) return send(req, res, 200, fs.readFileSync(f), MIME[path.extname(f)]);
      return send(req, res, 404, page('404', '<h1>Nenalezeno</h1>'));
    }
    let html;
    try {
      html = route(req.url);
    } catch (e) {
      if (e instanceof URIError) return send(req, res, 400, 'Bad Request', 'text/plain; charset=utf-8');
      console.error(e);
      return send(req, res, 500, 'Internal Server Error', 'text/plain; charset=utf-8');
    }
    if (html === null) return send(req, res, 404, page('404', '<h1>Nenalezeno</h1><p class="lead">Taková stránka neexistuje.</p>'));
    return send(req, res, 200, html);
  });
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  createServer().listen(PORT, '0.0.0.0', () => console.log(`Home page on :${PORT}`));
}

export { markdown, exampleUnits, exampleKinds, guidePage };

Zdroj site/test/server.test.mjs je uvedený v kapitole area-docker-tests.

Kvíz (11 otázek, odpověď se rozbalí kliknutím)

1. Proč jsou obsah příkladů Markdown soubory, a ne databáze nebo JSON?

Markdown se dobře čte, verzuje v gitu a upravuje v libovolném editoru; diff ukáže přesně, co se změnilo. Databáze by vyžadovala další službu, migrace a zálohy a obsah by nebyl součástí repozitáře, což je v rozporu s požadavkem, aby šel projekt naklonovat a spustit.

2. Proč se odpovědi skrývají v `<details>`?

Kvíz má testovat znalost. Pokud je odpověď vidět hned, čtenář ji jen přečte. Skrytá odpověď nutí zkusit odpovědět nahlas a potom si ji ověřit. <details> funguje i bez JavaScriptu.

3. Co vynucuje minimální počet otázek a pojmů?

Automatický test. Kvalita obsahu se tak nezhorší tiše při přidání příkladu; pokud autor napíše pět otázek, test selže a řekne, který soubor a kolik jich chybí.

4. Proč test kontroluje, že soubory v `files:` existují?

Přejmenování nebo smazání zdrojového souboru by jinak nechalo stránku s prázdným zdrojem. Test odhalí rozbitý odkaz hned, ne až když ho někdo najde.

5. Proč se zdroje větší než 9 000 znaků zobrazují sbalené?

Stránka s třicetikilobajtovým zdrojem nahoře by zakryla popis i kvíz. Sbalený blok má jen záhlaví (název, počet řádků), a kdo chce kód, jedním kliknutím ho otevře.

6. Proč nikdy nezačínat řádek odpovědi znaky `? ` nebo `= `?

Parser tyto prefixy bere jako začátek nové otázky nebo pojmu. Řádek s tímto začátkem uvnitř odpovědi by ji rozdělil a vytvořil falešnou položku.

7. Proč se odpověď a definice renderují přes Markdown, ale otázka přes `inline`?

Otázky jsou krátké a potřebují jen kód a zvýraznění (` kód `), odpovědi mohou mít odstavce a seznamy. Obojí prochází escapováním, takže obsah souboru nemůže vložit HTML.

8. Proč jsou tlačítka „Rozbalit vše“ a „Sbalit vše“ obsluhována skriptem, a ne odkazem?

Hromadné otevření více <details> bez skriptu v HTML nejde. Skript je malý, nepovinný, a bez něj kvíz funguje dál po jednotlivých otázkách.

9. Proč pager odkazuje na předchozí a další příklad podle pořadí kategorií?

Čtenář může tutoriál procházet postupně jako knihu. Pořadí je dané seznamem druhů (EXAMPLE_KINDS) a potom abecedou id, takže je stabilní.

10. Proč je parser vlastní a nepoužívá YAML?

Formát je záměrně minimální (čtyři značky) a snadno se píše ručně. YAML by vyžadoval závislost, což by porušilo zásadu bez npm balíčků, a víceřádkové odpovědi se v YAML píší nepohodlně.

11. Proč jsou id příkladů pevně dané názvem souboru?

Název souboru je stabilní adresa (/example/<id>). Žádná mapování navíc, žádné kolize, a adresa se dá přidat do záložek i odkazovat z README.

Slovník pojmů (12)

Příklad (unit)

Jeden soubor v site/examples/ reprezentující logický celek (prompt, skript, sadu testů, oblast aplikace).

`kind`

Druh příkladu: areas, prompts, templates, scripts, examples nebo tests; určuje seskupení.

`summary`

Jednovětý souhrn zobrazený na kartě příkladu.

`files:`

Čárkou oddělený seznam zdrojových souborů zobrazených na stránce.

`@popis` / `@kviz` / `@slovnik`

Značky oddělující sekce souboru příkladu.

Řádek `?` a `!`

Otázka kvízu a začátek její odpovědi.

Řádek `=` a `:`

Pojem slovníku a začátek jeho definice.

`parseExample`

Funkce, která rozloží soubor příkladu na metadata, popis, kvíz a slovník.

Rozbalovací odpověď

<details> se zobrazenou otázkou a skrytou odpovědí.

Pager

Dvojice odkazů na předchozí a další příklad.

Integrity test

Test ověřující úplnost každého příkladu (počty, existence souborů).

Source block

Rozbalovací blok se zdrojovým kódem; malé soubory otevřené, velké sbalené.

↑ nahoru

Oblast: závěrečný díl – AI v praxi

Praktický průvodce skills, subagenty, hooky, kontextem, ověřováním, bezpečností a náklady, s kvízem a slovníkem.

Závěrečný díl (site/guide.md, v aplikaci /guide, v tutoriálu za touto kapitolou celý text) shrnuje, jak s kódovacím agentem pracovat užitečně, bezpečně a levně. Opírá se o oficiální dokumentaci Claude Code ověřenou 30. 10. 2026 (lokálně verze 2.1.314). Vysvětluje čtyři mechanismy řízení agenta (CLAUDE.md, skills, subagenti, hooky), pole frontmatteru skills, chování po compaction (prvních 5 000 tokenů na skill a sdílený rozpočet 25 000), vnořené subagenty a isolation: worktree, události hooků a význam exit kódů (0, 2, jiný), správu kontextu, ověřování, bezpečnost (auto mode, deny pravidla, sandbox, prompt injection) a náklady. Končí tabulkou častých problémů a body, kde se repozitář liší od aktuální dokumentace.

Níže je kvíz a slovník k obsahu tohoto dílu. Odpovědi předpokládají, že jsi díl přečetl.

Celý text závěrečného dílu (site/guide.md)

Praktický průvodce: AI dovednosti, tools a triky

Poslední díl tutoriálu. Shrnuje, jak se s kódovacím agentem pracuje užitečně, bezpečně a levně, a opírá se o to, co ukazují předchozí příklady. Údaje o funkcích Claude Code jsou ověřené proti oficiální dokumentaci k 30. 10. 2026 (lokálně nainstalovaná verze 2.1.314). Claude Code se vyvíjí rychle, proto si při pochybnostech ověř konkrétní pole nebo příkaz v /help a v dokumentaci na code.claude.com.

1. Jak o agentovi přemýšlet

Agent je model + nástroje + kontext. Model je pořád stejný; rozdíl v kvalitě dělá to, co mu dáš do kontextu a co mu dovolíš udělat. Skills, subagenti a hooky jsou tři různé způsoby, jak kontext a chování řídit:

MechanismusK čemuKdy se načtePříklad v tomto repozitáři
CLAUDE.mdStálá pravidla projektuVždy, celéAGENTS.md, GEMINI.md
SkillPostup nebo znalost na požádáníPopis vždy, tělo až při použitískills/*/SKILL.md
SubagentIzolovaná práce s vlastním kontextemPři spuštěníimplementer-prompt.md
HookPravidlo bez výjimek, vynucené skriptemPři událostihooks/session-start
Pravidlo palce: pokud se instrukce musí splnit vždy, patří do hooku (skript ji vynutí). Pokud je to doporučení, stačí CLAUDE.md nebo skill.

2. Skills: psaní a používání

Skill je adresář se SKILL.md (YAML frontmatter + Markdown) a volitelnými podpůrnými soubory. Funguje podle otevřeného standardu Agent Skills a Claude Code k němu přidává vlastní pole.

Pole frontmatteruVýznam
name, descriptionJméno a kdy skill použít (klíčový případ na začátek)
when_to_useDoplňující spouštěče, přidává se k popisu
disable-model-invocationtrue = skill spustí jen člověk (deploy, commit)
user-invocablefalse = jen agent, skryté v menu /
allowed-tools / disallowed-toolsPovolené a odebrané nástroje po dobu skillu
context: fork + agentSkill běží jako subagent bez historie konverzace
model, effortPřepsání modelu a úsilí pro daný tah
pathsGlob vzory omezující automatickou aktivaci
hooksHooky platné po vyvolání skillu

Nerozpoznaná pole se ignorují bez chyby, takže překlep ve jménu pole nic nehlásí. Skills žijí v ~/.claude/skills/ (osobní), .claude/skills/ (projekt, commitovat), v pluginu, nebo v enterprise nastavení.

Praktická pravidla

  1. Popis začíná situací, ne obsahem: „Use when …“. Agent podle popisu rozhoduje, zda skill načíst. Popis + when_to_use se ve výpisu zkracuje na 1 536 znaků; Agent Skills standard dovoluje popis max. 1 024 znaků, a proto ho tento repozitář testuje.
  2. Drž SKILL.md krátký (dokumentace doporučuje pod 500 řádků). Co se potřebuje jen někdy, patří do references/, kde to agent přečte čerstvě v kroku, který to vyžaduje.
  3. Po compaction se skill připojí zkrácený: podle aktuální dokumentace si každý vyvolaný skill podrží prvních 5 000 tokenů a všechny znovu připojené sdílejí rozpočet 25 000 tokenů. Repozitář to hlídá testem na 20 000 bajtů (tests/skill-size), což je konzervativnější než dokumentace; chrání před ztrátou instrukcí.
  4. Skill, který má vedlejší účinky, nech vyvolávat jen člověku (disable-model-invocation: true).
  5. Testuj skill proti základní linii: čerstvá session bez skillu (RED), se skillem (GREEN), pod tlakem (PRESSURE). Přesně to dělá tests/claude-code/test-worktree-native-preference.sh.
  6. Audituj používání: /skill-doctor ukáže skills, které stojí kontext a nikdy se nepoužijí.

3. Pracovní postup Superpowers

Doporučené pořadí, ve kterém se skills navazují:

  1. brainstorming: zjisti, co člověk skutečně chce, než se začne stavět; hotový návrh ověř čerstvým „builderem“ (viz příklad Builder check).
  2. using-git-worktrees: izolovaný pracovní adresář pro práci.
  3. writing-plans: plán do souboru, úkoly po malých krocích.
  4. subagent-driven-development (subagent na úkol + review) nebo executing-plans (inline, s ledgerem).
  5. test-driven-development: nejdřív selhávající test (RED), pak implementace (GREEN).
  6. requesting-code-review: read-only review proti plánu.
  7. verification-before-completion: tvrzení o hotové práci musí podložit výstup příkazu.
  8. finishing-a-development-branch: rozhodnutí o integraci.

Proč to funguje: každý krok vytváří ověřitelný artefakt (návrh, plán, test, diff, ledger). Agent, který nic nezapíše, se nedá zkontrolovat.

4. Subagenti

  • Čerstvý kontext je funkce, ne chyba. Implementátor nezná historii a nemůže si domýšlet; reviewer nezná autorovy záměry a vidí jen diff.
  • Model volíš podle úkolu: levnější (např. haiku) pro čtení a průzkum, silnější pro architekturu. Pole model v definici, parametr při volání, proměnná CLAUDE_CODE_SUBAGENT_MODEL a model hlavní konverzace se uplatní v tomto pořadí. Repozitář model u implementátora vyžaduje, aby se nezdědil nejdražší.
  • isolation: worktree dá subagentovi dočasnou kopii repozitáře; při paralelní práci brání kolizím souborů a po práci bez změn se smaže.
  • Vnořování je technicky povolené: subagenti mohou spouštět další subagenty až do hloubky 3 (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, hodnota 1 vnořování vypne). Zákaz spouštět další reviewery v promptech Superpowers je tedy procesní pravidlo, ne omezení platformy: duplicitní review stojí plnou cenu a nic nepřidá.
  • Fan-out měj pod kontrolou: souběžně může běžet výchozích 20 subagentů a každý spotřebovává vlastní tokeny.
  • Pošli jen cestu, ne obsah: brief a report předávej souborem (task-brief, review-package), aby se kontext controlleru nezaplnil.

5. Hooky

Hook je skript spouštěný při události. Dokumentace dnes uvádí desítky událostí (mimo jiné SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop, SubagentStop, PreCompact, PostCompact, WorktreeCreate) a typy command, http, mcp_tool, prompt a experimentální agent.

Exit kódVýznam
0Úspěch; na SessionStart se text ze stdout přidá do kontextu
2Blokující chyba: akce se zastaví a stderr je důvod (u událostí, které blokovat umějí)
jiný (i 1)Neblokující chyba; akce pokračuje
  • Stop hook je nejlepší způsob, jak vynutit „hotovo = testy prošly“: agent nemůže skončit, dokud kontrola selhává.
  • SessionStart má matchery startup, resume, clear, compact, fork. Hook Superpowers registruje startup|clear|compact; při resume se spoléhá na to, že bootstrap už je v obnovené konverzaci.
  • Hook, který pípá nebo zasahuje do výstupu, ruší práci. Tichá notifikace stačí.
  • Hook nikdy nespoléhej na nástroj, který nemusí být nainstalovaný (viz testy run-hook.cmd).

6. Kontext a paměť

  • CLAUDE.md drž krátký; co se týká jen části kódu, patří do pravidel vázaných na cestu nebo do skillu.
  • Dlouhý výstup příkazu ulož do souboru a vypiš jen konec (vzor task-done).
  • Příkazy /clear (nové téma), /compact (zkrácení s pokyny, co zachovat) a /rewind (návrat k dřívějšímu bodu) používej aktivně, ne až když je kontext plný.
  • Pracovní stav drž v souborech (plán, ledger), ne v hlavě agenta: přežije compaction i novou session.
  • Jedna session = jedno téma. Druhá úloha = druhá session nebo worktree.

7. Ověřování a kvalita

  • Dej agentovi kontrolu, kterou může spustit (test, linter, curl na endpoint). Bez ní jen hádá.
  • Nevěř reportu, ověřuj proti diffu (task reviewer prompt).
  • TDD s důkazem: v reportu příkaz a výstup RED a GREEN.
  • Selhávající test nikdy neobcházej oslabením testu; hledej kořenovou příčinu (systematic-debugging).
  • Flaky test se opravuje čekáním na podmínku, ne delším sleep (příklad condition-based waiting).
  • Statická analýza patří do rutiny: v shellu shellcheck, v JavaScriptu node --check a testy node --test, v PHP phpstan a phpunit.

8. Bezpečnost

  • Oprávnění: Claude Code dnes začíná v terminálu a VS Code v auto mode (klasifikátor kontroluje riskantní akce). Ruční schvalování vede k „schvaluji bez čtení“; bypassPermissions patří jen do jednorázového kontejneru.
  • Pravidla bez výjimek vynucuj permissions.deny a sandboxem, ne prosbou v promptu.
  • Secrets nikdy do promptů, CLAUDE.md ani commitů; .env.local mimo repozitář.
  • Prompt injection: cokoli, co agent přečte (web, issue, soubor), může obsahovat pokyny. Proto companion server vyžaduje token, kontroluje Origin a nastavuje bezpečnostní hlavičky.
  • Supply chain: cizí skills a pluginy jsou kód, který agent vykonává. Před instalací je přečti. Preferuj zero-dependency řešení (viz server.cjs) a zámky závislostí.
  • Least privilege: subagentovi dej jen potřebné tools; v Dockeru připojuj repozitář :ro, pokud zápis nepotřebuješ.

8a. Náklady

  • Každé volání nástroje v inline session znovu čte celý kontext, proto sdružuj kroky do jednoho skriptu (task-start, task-done).
  • Levný model na průzkum, silný na návrh; nastav effort podle obtížnosti.
  • Měř: tests/claude-code/analyze-token-usage.py rozloží spotřebu po agentech; diagnosing-superpowers odhalí opakovanou práci a velké výsledky nástrojů.

9. Triky, které se vyplatí

  1. Piš konkrétní prompty: co, kde, jak poznám, že je hotovo.
  2. Nejdřív plán, pak kód; plán ulož do souboru a nech ho schválit.
  3. Commit po každém úkolu; malé commity se snadno reviewují a vrací.
  4. Paralelní práce = worktrees (.worktrees/, isolation: worktree).
  5. Headless režim (claude -p, --output-format stream-json, --max-turns) pro automatizaci a testy skills.
  6. Nech agenta ptát se dřív, než začne; hádání je nejdražší chyba.
  7. Zapisuj, proč (rozhodnutí, ne jen co); budoucí session to nezná.
  8. Pravidelně čisti: smaž skills a pravidla, která se nepoužívají.
  9. Zkoušej na čerstvé session: co funguje jen v dlouhé konverzaci, nefunguje spolehlivě.

10. Časté problémy

PříznakPravděpodobná příčinaŘešení
Agent ignoruje pravidloPravidlo je dlouhé nebo skryté v CLAUDE.mdZkrať; kritické pravidlo převeď na hook
Skill se nespustíPopis neříká, kdy ho použítPřepiš popis jako „Use when …“
Po compaction agent „zapomněl“ postupSkill je dlouhý a zkrátil seRozděl na references/, drž tělo krátké
Agent tvrdí „hotovo“, ale nic neběželoChybí ověřeníStop hook nebo verification-before-completion
Stejný soubor se čte pořád dokolaZtracený kontextUkládej stav do souboru, použij /clear s novým briefem
Paralelní agenti se perou o souborySdílený checkoutisolation: worktree
Náklady rostouVelké výsledky nástrojů, drahý model na lehké práciVýstup do souboru, levnější model

11. Co v tomto repozitáři stojí za ověření

Audit narazil na místa, kde se repozitář liší od aktuální dokumentace. Nejde o chyby, ale o body k vědomému rozhodnutí maintainera:

  • Limit 20 000 bajtů (tests/skill-size) vychází z dřívějšího chování; dokumentace dnes uvádí 5 000 tokenů na skill a sdílený rozpočet 25 000 tokenů po compaction. Test je konzervativní a stále užitečný.
  • SessionStart matcher startup|clear|compact nepokrývá resume a fork. Bootstrap tam většinou přežije v obnovené konverzaci, ale stojí za ověření.
  • Nové pole skills (when_to_use, disable-model-invocation, context: fork, paths) repozitář zatím nevyužívá; u skills s vedlejšími účinky by se hodilo disable-model-invocation.
  • Vnořené subagenty platforma dovoluje, zákaz je jen v promptech.
Tyto body jsou pozorování, ne změny: AGENTS.md upozorňuje, že úpravy chování skills vyžadují rozsáhlé eval důkazy.

Zdrojový kód

Kvíz (14 otázek, odpověď se rozbalí kliknutím)

1. Kdy patří pravidlo do hooku a kdy stačí do `CLAUDE.md`?

Pokud se musí splnit vždy a bez výjimek, patří do hooku, protože ho vynutí skript, nikoli model. CLAUDE.md je doporučení, které model většinou dodrží, ale nezaručuje. Proto „testy musí projít“ patří do Stop hooku, zatímco styl komentářů do CLAUDE.md.

2. Co znamená exit kód 2 u command hooku?

Blokující chyba: u událostí, které blokovat umějí, se akce zastaví a stderr se předá jako důvod. Exit 0 je úspěch, jakýkoli jiný kód (včetně 1) je neblokující chyba a akce pokračuje. Častá chyba je očekávat, že exit 1 blokuje.

3. Proč má popis skillu začínat situací („Use when …“)?

Agent podle popisu rozhoduje, zda skill načte. Popis, který shrnuje obsah, ale neříká kdy, se spouští náhodně. Popis, který je v kontextu pořád, navíc musí být krátký, protože zabírá místo u každé session.

4. Co se stane se skillem po compaction?

Podle aktuální dokumentace si každý vyvolaný skill podrží prvních 5 000 tokenů a všechny znovu připojené skills sdílejí rozpočet 25 000 tokenů. Instrukce za řezem agent ztratí, dokud soubor znovu nepřečte. Proto se dlouhé podpůrné texty dávají do references/.

5. Proč jsou nerozpoznaná pole ve frontmatteru nebezpečná?

Claude Code je ignoruje bez chyby. Překlep (disable-model-invokation) tak nic nehlásí a skill se chová jinak, než autor čekal. Po napsání pole je nutné ověřit jeho účinek, třeba testem v čerstvé session.

6. K čemu je `disable-model-invocation: true`?

Skill může spustit jen člověk (např. /deploy). Hodí se pro akce s vedlejšími účinky, které nemá agent spouštět sám podle odhadu.

7. Brání platforma vnořeným subagentům?

Ne, dovoluje je do hloubky 3 (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH). Zákaz v promptech Superpowers je procesní pravidlo proti duplicitnímu review. Tvrdě ho lze vynutit odebráním nástroje Agent v definici subagenta.

8. Proč subagent s `isolation: worktree` pomáhá při paralelní práci?

Dostane vlastní dočasnou kopii repozitáře, takže paralelní agenti nepřepisují stejné soubory. Pokud nic nezmění, worktree se smaže.

9. Proč je „dej agentovi kontrolu, kterou může spustit“ nejdůležitější tip?

Bez ověření agent jen hádá, že je hotovo. S testem nebo příkazem vidí výsledek a opravuje se podle něj. Stop hook tuto kontrolu navíc vynutí.

10. Proč se pracovní stav ukládá do souborů a ne jen do konverzace?

Soubory (plán, ledger, report) přežijí compaction i novou session. Konverzaci agent po zkrácení kontextu neúplně pamatuje. Stav v souboru je také ověřitelný člověkem.

11. Proč je `bypassPermissions` doporučen jen v jednorázovém kontejneru?

Vypíná téměř všechny kontroly. Pokud se něco pokazí (chyba, prompt injection), nic nezabrání škodě. V kontejneru bez cenných dat je dopad omezený.

12. Co je prompt injection a jak se brání tento projekt?

Škodlivé pokyny ukryté v datech, která agent čte (web, soubor, issue). Obrana je vrstvená: omezit oprávnění, nepovolovat nedůvěryhodný obsah, ověřovat výstupy a u serveru vyžadovat token, kontrolovat Origin a nastavit bezpečnostní hlavičky.

13. Proč se sdružují kroky do jednoho skriptu (`task-start`, `task-done`)?

Každé volání nástroje v inline session znovu čte celý kontext a stojí tokeny i čas. Jeden skript místo dvou volání ušetří turn, aniž by se ztratila funkce.

14. Jak poznáš, že je skill zbytečný?

/skill-doctor ukáže skills, které stojí kontext, ale nikdy se nespouštějí. Takové skills se smažou nebo se jejich popis upraví.

Slovník pojmů (17)

`CLAUDE.md`

Soubor se stálými pravidly projektu, načítaný do kontextu vždy; má být krátký.

Skill

Adresář se SKILL.md; popis je v kontextu vždy, tělo až při vyvolání.

Frontmatter

YAML metadata skillu (name, description, disable-model-invocation, context…).

`when_to_use`

Doplňující pole, které se přidá k popisu a pomáhá spouštění.

`disable-model-invocation`

Skill spustí jen člověk; model ho sám nevyvolá.

`context: fork`

Skill běží jako subagent bez historie konverzace.

Compaction

Automatické zkrácení kontextu; skills se připojí zkrácené.

Subagent

Pomocný agent s vlastním kontextem, nástroji a případně modelem.

`isolation: worktree`

Subagent běží v dočasné kopii repozitáře.

Hook

Skript spouštěný při události (SessionStart, PreToolUse, Stop…).

Stop hook

Hook při pokusu agenta skončit; může ho přinutit pokračovat, dokud kontrola selhává.

Exit kód 2

Blokující chyba hooku; stderr je důvod.

Auto mode

Režim oprávnění, kdy klasifikátor kontroluje riskantní akce před spuštěním.

`permissions.deny`

Pravidlo, které akci zakáže bez ohledu na prosbu v promptu.

Prompt injection

Škodlivé pokyny ukryté v datech čtených agentem.

`/skill-doctor`

Příkaz zobrazující skills, které stojí kontext a nepoužívají se.

Ledger

Soubor se záznamem postupu práce, který přežije compaction.

↑ nahoru

Oblast: rozcestník a navigační menu

Jak je postavená úvodní stránka, levé menu, drobečková navigace a přepínání světlého a tmavého vzhledu.

Rozcestník je zero-dependency Node server (site/server.mjs), který při každém požadavku přečte repozitář a vygeneruje HTML. Nic se necachuje ani neukládá do databáze, takže nově přidaná skill, dokument nebo příklad se objeví po obnovení stránky.

Úvodní stránka (/) obsahuje hero banner s vyhledávacím polem, dlaždice se statistikami (verze, počet skills, integrací, dokumentů a příkladů), skills seskupené podle fáze práce (Pracovní postup, Kvalita a ladění, Spolupráce a review, Meta), dokumentaci, integrace s agenty, závěrečný díl a všechny příklady po kategoriích. Levé menu je na každé stránce: rozbalovací skupiny (<details>), zvýraznění aktuální stránky, živé filtrování položek při psaní, klávesa / pro skok do pole a na úzkých displejích (do 900 px) hamburger. Vzhled se řídí systémem (prefers-color-scheme).

Praktický postup: (1) spusť docker compose up -d a otevři http://localhost:8080; (2) klikni na skill v menu, uvidíš její soubory, příklady a vyrenderovaný SKILL.md; (3) do pole v menu napiš část názvu, položky se průběžně filtrují; (4) stiskni Enter a spustíš fulltext; (5) zúžením okna pod 900 px si ověř mobilní menu.

Zdrojový kód

Zdroj site/server.mjs je uvedený v kapitole area-example-pages.

Kvíz (11 otázek, odpověď se rozbalí kliknutím)

1. Proč server generuje stránky při každém požadavku, a ne jednou při startu?

Repozitář se při práci s agentem neustále mění (nové skills, plány, příklady). Čtení za běhu zaručuje, že rozcestník nikdy neukazuje zastaralý stav, a nepotřebuje žádný build ani invalidaci cache. Cenou je trochu práce navíc na požadavek, což u lokálního nástroje nevadí.

2. Proč je menu postavené na `<details>` a ne na JavaScriptu?

Rozbalování řeší prohlížeč sám, takže funguje i při vypnutém skriptu, je přístupné z klávesnice a nic se nemůže rozbít. JavaScript je jen vylepšení (filtr a zkratka /).

3. Jak funguje zvýraznění aktuální stránky v menu?

Funkce sidebar(active) dostane adresu aktuální stránky a položce se stejným href přidá třídu active; skupina, která ji obsahuje, se vykreslí otevřená. Skript na načtení navíc posune menu tak, aby aktivní položka byla vidět.

4. Proč se skills dělí do skupin Pracovní postup, Kvalita a ladění, Spolupráce a Meta?

Plochý seznam 15 skills je nepřehledný. Skupiny odpovídají pořadí, ve kterém se skills při práci používají. Skill, která v mapě chybí, spadne do skupiny „Ostatní“, takže nová skill se neztratí.

5. Proč se vzhled řídí `prefers-color-scheme`, a ne vlastním přepínačem?

Uživatel už systém nastavil. Respektování volby operačního systému nepotřebuje žádný stav, ukládání ani cookie a odpovídá očekávání.

6. K čemu je „skip link“ (Přeskočit na obsah)?

Uživatelé čtečky obrazovky nebo klávesnice se jinak musejí při každé stránce prokousat celým menu. Odkaz na #main se objeví při zaostření a přeskočí navigaci. Je to základ přístupnosti.

7. Proč menu na mobilu používá skryté zaškrtávací políčko (`#nav-toggle`) a ne skript?

Kombinace <input type="checkbox"> a CSS selektoru :checked ~ .side zvládne otevření a zavření bez JavaScriptu. Je to jednodušší a robustnější než ruční správa stavu.

8. Co dělají drobečky (breadcrumbs) a proč se nevytvářejí z URL?

Ukazují, kde uživatel je (Úvod / Skills / název). Každá stránka je předává explicitně, protože URL jako /file?path=… by žádnou smysluplnou hierarchii neobsahovala.

9. Proč musí být adresy jako `/skill/<název>` a `/example/<id>` validované?

Název pochází z adresy, tedy od uživatele. Server ho porovná se skutečným seznamem skills nebo příkladů a neexistující vrátí jako 404; nikdy ho nepoužije k sestavení cesty k souboru.

10. Proč statistiky na úvodu počítá server z dat, a nejsou napsané ručně?

Ručně psaná čísla zastarají hned při přidání skill nebo příkladu. Počítaná čísla (names.length, počet jednotek) jsou vždy pravdivá.

11. Proč `/healthz` vrací jen `ok` a žádná data?

Slouží kontejnerovému healthchecku. Nemá prozrazovat nic o systému a musí být rychlý a spolehlivý.

Slovník pojmů (12)

Rozcestník

Úvodní stránka aplikace, která odkazuje na všechny oblasti repozitáře: skills, dokumentaci, integrace a příklady.

Hero banner

Barevný horní blok úvodní stránky s názvem, popisem, odkazy a vyhledávacím polem.

Sidebar

Levý navigační panel dostupný na každé stránce; v kódu funkce sidebar(active).

`<details>`

HTML prvek pro rozbalovací blok bez skriptu; tvoří skupiny menu.

Active item

Položka menu odpovídající aktuální stránce; má třídu active a skupina je otevřená.

Filtr menu

Skript, který při psaní do pole skryje položky bez shody a rozbalí skupiny s nalezenými.

Breadcrumbs (drobečky)

Řádek nad nadpisem ukazující cestu k aktuální stránce.

Skip link

Skrytý odkaz „Přeskočit na obsah“ pro čtečky a klávesnici.

`prefers-color-scheme`

Media query, podle které se vzhled přizpůsobí světlému nebo tmavému režimu systému.

Hamburger menu

Tlačítko ☰ na úzkém displeji, které otevírá menu pomocí skrytého checkboxu.

Skupina skills

Rozdělení skills podle fáze práce; mapa SKILL_GROUPS v server.mjs.

Healthcheck `/healthz`

Endpoint pro kontrolu, že kontejner žije.

↑ nahoru

Oblast: bezpečnost rozcestníku

Jak server brání čtení cizích souborů, injekci HTML, zarámování a zneužití metod, a proč jsou zvolené pojistky dostatečné.

Rozcestník čte soubory z disku podle adresy, kterou zadá uživatel, a vypisuje jejich obsah do HTML. Obě činnosti jsou klasická rizika, proto je obrana vrstvená:

  1. Seznam povolených přípon (VIEWABLE) a vynechané adresáře (SKIP: .git, node_modules, evals, .worktrees). Dotfiles jako .env se nikdy nezobrazí.
  2. Kontrola cesty: path.resolve(ROOT, rel) musí začínat ROOT + path.sep a žádná část nesmí být .git ani node_modules; jinak 404.
  3. Escapování všeho, co se vkládá do HTML (esc), včetně dotazů, názvů souborů a obsahu. Markdown odkazy smějí vést jen na http(s) nebo #.
  4. Hlavičky: Content-Security-Policy (skript povolen jen podle hashe konkrétního kódu, default-src 'none', frame-ancestors 'none'), X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: no-referrer, Cross-Origin-Resource-Policy: same-origin.
  5. Metody a chyby: jen GET/HEAD (jinak 405), poškozená adresa dá 400, vnitřní chyba se zaloguje na server a klient dostane jen obecnou zprávu.
  6. Kontejner: repozitář připojený :ro, read_only, cap_drop: ALL, no-new-privileges, port jen na 127.0.0.1.

Praktický postup: (1) zkus curl "localhost:8080/file?path=../../etc/passwd" a dostaneš 404; (2) curl -I localhost:8080/ ukáže bezpečnostní hlavičky; (3) curl -X POST localhost:8080/ vrátí 405; (4) docker compose --profile tests run --rm tests spustí testy, které tyto případy hlídají.

Zdrojový kód

Zdroj site/server.mjs je uvedený v kapitole area-example-pages.

Zdroj compose.yaml je uvedený v kapitole area-docker-tests.

Zdroj site/test/server.test.mjs je uvedený v kapitole area-docker-tests.

Kvíz (12 otázek, odpověď se rozbalí kliknutím)

1. Proč se používá seznam povolených přípon (allowlist) a ne seznam zakázaných?

Zakázat lze jen to, na co autor pomyslí; zapomenutý typ souboru se pak prozradí. Allowlist funguje obráceně: zobrazí se jen to, co je výslovně povoleno, takže nová neznámá přípona je automaticky chráněná. Je to bezpečnější výchozí chování.

2. Proč kontrola `abs.startsWith(ROOT + path.sep)` a ne jen `startsWith(ROOT)`?

Cesta /app-secrets/x začíná řetězcem /app, ale není v adresáři /app. Přidání oddělovače porovnává celé adresáře. Navíc path.resolve nejdřív vyřeší .., takže ../.. nic neobejde.

3. Co dělá CSP s hashem skriptu?

Prohlížeč smí spustit jen inline skript, jehož SHA-256 odpovídá hodnotě v hlavičce. Pokud by útočník vložil do stránky jiný skript, nespustí se. Skript je konstantní, proto hash stačí a není potřeba nonce.

4. Proč je `default-src 'none'`?

Výchozí je zakázat vše (obrázky, fonty, spojení) a povolit jen to, co stránka potřebuje: inline styly, vlastní obrázky a jeden hashovaný skript. Princip nejmenších oprávnění.

5. Proč `frame-ancestors 'none'` a `X-Frame-Options: DENY`?

Zabraňují zarámování stránky v cizím webu (clickjacking). Dvě hlavičky pokrývají moderní i starší prohlížeče.

6. Proč se vnitřní chyba nevypisuje klientovi?

Text výjimky může prozradit cesty, názvy souborů nebo strukturu kódu. Server chybu zaloguje a klient dostane jen „Internal Server Error“.

7. Proč jsou povoleny pouze `GET` a `HEAD`?

Aplikace nic nezapisuje, takže jiné metody nemají smysl. Odmítnutím (405 s hlavičkou Allow) se zmenšuje útočná plocha.

8. Proč je port vázaný jen na `127.0.0.1`?

Rozcestník ukazuje obsah repozitáře a nemá autentizaci. Vazba na loopback znamená, že se k němu dostane jen počítač, na kterém běží. Do sítě by ho vystavil až výslovný zásah.

9. Proč je repozitář v kontejneru připojen `:ro` a systém souborů `read_only`?

I kdyby se podařilo zneužít chybu serveru, nemohl by nic přepsat. Server nepotřebuje psát, takže mu to nikdo nedovolí.

10. Jak chrání vyhledávání před zahlcením?

Omezuje délku dotazu, počet vrácených souborů a velikost čteného souboru a escapuje dotaz, aby nevznikl škodlivý regulární výraz.

11. Proč je markdown odkaz `javascript:` nahrazen `#`?

Odkaz s protokolem javascript: spustí kód po kliknutí. Renderer povoluje jen http, https a kotvy; ostatní se zneškodní.

12. Proč jsou tyto vlastnosti hlídány automatickými testy?

Bezpečnost, která se netestuje, časem tiše zmizí při úpravě kódu. Testy ověřují traversal, hlavičky, metody, escapování a blokování javascript:, takže regrese se projeví okamžitě.

Slovník pojmů (15)

Allowlist

Seznam výslovně povolených hodnot (přípony VIEWABLE); vše ostatní je zakázáno.

Path traversal

Útok pomocí .. v cestě, který čte soubory mimo povolený adresář.

`path.resolve`

Funkce Node, která z cesty udělá absolutní a vyřeší ...

XSS

Vložení škodlivého skriptu do stránky; brání mu escapování a CSP.

`esc`

Funkce nahrazující & < > " entitami.

CSP

Content-Security-Policy; hlavička určující, co smí stránka načíst a spustit.

Hash skriptu

SHA-256 inline skriptu uvedený v CSP; spustí se jen shodný kód.

`nosniff`

Hlavička zakazující prohlížeči hádat typ obsahu.

Clickjacking

Útok zarámováním stránky v cizím webu; brání frame-ancestors a X-Frame-Options.

`Referrer-Policy: no-referrer`

Prohlížeč neposílá adresu odkazující stránky.

`read_only` kontejner

Souborový systém kontejneru je jen pro čtení.

`cap_drop: ALL`

Odebrání všech Linux capabilities kontejneru.

`no-new-privileges`

Proces v kontejneru nemůže získat vyšší oprávnění.

Loopback (127.0.0.1)

Adresa dostupná jen z téhož počítače.

Least privilege

Princip nejmenších oprávnění; každá část má jen to, co nezbytně potřebuje.

↑ nahoru

Prompty pro subagenty

Builder check prompt (brainstorming)

Prompt pro čerstvého subagenta, který z hotového návrhu vyčte otázky, na něž by se jako „stavitel“ musel ptát.

Po dokončení brainstormingu existuje písemný návrh (design document). Než se podle něj začne stavět, skill brainstorming spustí čerstvého subagenta s tímto promptem. Subagent dostane jen cestu k dokumentu a roli „talentovaného stavitele“ v dané oblasti (softwarový inženýr, organizátor akcí, pekařský konzultant…). S autorem návrhu si nemůže promluvit – a právě to je smysl celého příkladu.

Prompt simuluje okamžik, kdy někdo jiný dostane návrh do ruky a má podle něj plánovat. Subagent vrací pouze otázky, na které by potřeboval odpověď: místa, kde by musel hádat a špatný odhad by něco změnil. U každé otázky uvede, proč odpověď mění plán, a seřadí je podle důležitosti. Co návrh záměrně přenechává stavitele, nebo co lze rozumně rozhodnout samostatně, se přeskakuje; stejně tak stylistické drobnosti. Pokud nic důležitého nechybí, odpoví doslova „nothing important left“.

Výsledkem je krátký, seřazený seznam skutečných mezer, které se dají doplnit dřív, než se zahájí drahá implementace.

Zdrojový kód

skills/brainstorming/builder-check-prompt.md 24 řádků
# Builder Check Prompt

Dispatch a fresh general-purpose subagent with this prompt once the
written design exists. Fill in the domain and the document path.

```
You are a talented [DOMAIN, e.g. "software engineer", "event planner",
"bakery consultant"]. You've been handed a design document and asked to
put together a plan to build what it describes. You will not be able to
talk to the person who wrote it.

Read [DOCUMENT_PATH].

Report only the questions you'd still need answered before you could plan
this well: places where you'd have to guess and a wrong guess would
matter. For each, give the question and why the answer changes the plan.
Rank them by importance.

Skip anything the document explicitly leaves to the builder, and anything
you could reasonably decide yourself. Skip nitpicks about wording.

If nothing important is left, say "nothing important left".
```

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč se kontrola dělá čerstvým subagentem, a ne ve stejné konverzaci, kde návrh vznikl?

Autor návrhu (agent i člověk) má v hlavě kontext, který v dokumentu nemusí stát. Cokoli „je mu jasné“, přečte automaticky správně. Čerstvý subagent kontext nemá, takže najde přesně ty věty, které bez kontextu nejdou pochopit. Je to nejlevnější způsob, jak otestovat, zda dokument obstojí sám o sobě.

2. Proč prompt výslovně říká „You will not be able to talk to the person who wrote it“?

Zakazuje subagentovi opřít se o dotaz na autora. Kdyby se mohl doptat, vyřešil by nejasnosti ústně a dokument by zůstal děravý. Omezení vynucuje, aby se každá mezera projevila jako otázka v odpovědi, kterou pak lze do dokumentu doplnit.

3. Proč má subagent hrát roli „talentovaného [DOMAIN]“ a není to jen obecný reviewer?

Mezery v návrhu se liší podle oboru. Softwarový inženýr hledá chybějící datové toky a hranice, organizátor akcí rozpočet a kapacity. Role zajistí, že se subagent ptá jako skutečný stavitel s praktickou zkušeností, ne jako korektor. Zároveň prompt pracuje i s oblastmi mimo software (přednáška, firma, rekonstrukce).

4. Proč prompt chce „only the questions you'd still need answered“ a nic víc?

Úzký formát výstupu brání tomu, aby se odpověď rozplynula v obecné kritice a chválách. Hlavní agent dostane čistý seznam rozhodnutí, která musí udělat, ne esej, kterou by musel třídit.

5. Co znamená požadavek, aby u každé otázky stálo i „why the answer changes the plan“?

Je to filtr na důležitost. Otázka, jejíž odpověď plán nezmění, nemá smysl klást. Vynucené zdůvodnění zároveň pomáhá člověku rychle rozhodnout, jestli otázku řešit hned, nebo ji nechat na stavitele.

6. Proč se mají přeskočit věci, které dokument „explicitly leaves to the builder“?

Autor je tam delegoval záměrně. Kdyby je subagent hlásil, vznikal by šum a nutil by autora rozhodovat věci, které rozhodnout nechtěl. Příklad je tak bezpečný proti over-specifikaci: nenutí do návrhu dopisovat detaily, které mají zůstat flexibilní.

7. K čemu slouží věta „If nothing important is left, say 'nothing important left'“?

Dává subagentovi legitimní východisko. Bez ní by se pod tlakem „najdi otázky“ snažil nějaké vymyslet (falešně pozitivní nálezy). Pevná fráze je také snadno strojově rozpoznatelná, takže hlavní agent ví, že může pokračovat.

8. Proč je prompt uložen jako samostatný soubor a ne přímo v SKILL.md?

SKILL.md se načítá celý do kontextu při každém použití skillu. Prompt, který potřebuje jen jeden krok na konci, se načte až když je potřeba. Udržuje to hlavní skill krátký a lépe přežije compaction.

9. Jak se výstup této kontroly liší od code review?

Code review posuzuje hotový kód. Builder check běží před implementací a posuzuje, zda je dostatek informací k plánování. Hledá chybějící rozhodnutí, ne chyby v řešení.

Slovník pojmů (9)

Builder (stavitel)

Osoba nebo agent, který podle návrhu bude plánovat a stavět. V tomto příkladu ho hraje subagent. Jeho pohled je test kvality dokumentu: co builder nepochopí, to v dokumentu chybí.

Design document

Písemný návrh vzniklý v brainstormingu. Je jediným vstupem subagenta (cesta [DOCUMENT_PATH]); proto musí obsahovat vše podstatné.

Čerstvý subagent

Agent spuštěný bez historie konverzace. Neví nic kromě promptu a dokumentu, takže nemůže „domyslet“ chybějící informace z paměti.

Placeholder `[DOMAIN]`

Zástupný text v promptu, který volající nahradí oborem (např. „software engineer“). Určuje perspektivu, ze které subagent mezery hledá.

Placeholder `[DOCUMENT_PATH]`

Zástupný text pro cestu k návrhu. Subagent si dokument načte sám, hlavní agent mu jej nevkládá do promptu.

Mezera, na které záleží

Místo, kde by builder musel hádat a špatný odhad by změnil plán. Jediný typ nálezu, který prompt chce.

Delegace na stavitele

Rozhodnutí, která návrh výslovně přenechává implementaci. Subagent je nesmí hlásit jako otázky.

Ranking podle důležitosti

Seřazení otázek od nejdůležitější. Hlavní agent tak může zodpovědět nejvýše položené a zbytek zvážit.

„nothing important left“

Pevná odpověď, když dokument stačí. Signalizuje, že další iterace návrhu není nutná.

↑ nahoru

Code reviewer prompt (requesting-code-review)

Šablona promptu pro subagenta, který read-only zreviewuje hotovou práci proti plánu v daném git rozsahu a vrátí verdikt.

Šablona, kterou skill requesting-code-review používá při spuštění review subagenta. Prompt dá reviewerovi roli seniorního revieweru, popis toho, co bylo implementováno, plán nebo požadavky a git rozsah BASE_SHA..HEAD_SHA s příkazy git diff --stat a git diff. Pak přidává pravidla, která mění kvalitu review:

  • Spec je vision document: kde spec mlčí, rozhoduje očekávání rozumného uživatele; mlčení specu není povolení.
  • Declined to judge: před verdiktem musí reviewer vypsat každé chování, které odložil jako mimo plán, s důvodem, aby nic nezmizelo potichu.
  • Read-only: žádná mutace working tree, indexu, HEAD ani branch; jiné revize se rozbalí do dočasného git worktree v /tmp.
  • Nespouští subagenty: všechny review „sedadla“ už proces poskytuje.
  • Kalibrace závažností (Critical / Important / Minor) a povinná chvála na začátku.

Výstup má pevnou strukturu: Strengths, Issues s file:line, Recommendations a Assessment „Ready to merge? Yes | No | With fixes“.

Zdrojový kód

skills/requesting-code-review/code-reviewer.md 199 řádků
# Code Reviewer Prompt Template

Use this template when dispatching a code reviewer subagent.

**Purpose:** Review completed work against requirements and code quality standards before it cascades into more work.

```
Subagent (general-purpose):
  description: "Review code changes"
  prompt: |
    You are a Senior Code Reviewer with expertise in software architecture,
    design patterns, and best practices. Your job is to review completed work
    against its plan or requirements and identify issues before they cascade.

    ## What Was Implemented

    [DESCRIPTION]

    ## Requirements / Plan

    [PLAN_OR_REQUIREMENTS]

    ## Git Range to Review

    **Base:** [BASE_SHA]
    **Head:** [HEAD_SHA]

    ```bash
    git diff --stat [BASE_SHA]..[HEAD_SHA]
    git diff [BASE_SHA]..[HEAD_SHA]
    ```

    ## The spec is a vision document

    The spec says what the software must do. It does not enumerate every
    input, environment, or condition the software will meet. For behavior
    the spec is silent on, judge by what a reasonable person using this
    software would expect: a reasonable person's expectation is a
    requirement, and a spec's silence is not permission. Grade such
    findings by their effect on that person, not by whether the spec
    mentions the trigger.

    ## Declined to judge

    Before your verdict, list every behavior you considered and set aside
    as outside the plan or spec, one line each, with the reason. The
    executor rules on each line; nothing you set aside is dropped
    silently. An empty list means you set nothing aside.

    ## Read-Only Review

    Your review is read-only on this checkout. Do not mutate the working tree, the index, HEAD, or branch state in any way. Use tools like `git show`, `git diff`, and `git log` to inspect history. If you need a working copy of a different revision, check it out into a separate temporary directory (e.g. `git worktree add /tmp/review-[SHA] [SHA]`) — never move HEAD on this checkout.

    ## You Do Not Dispatch Subagents

    Do all of this review yourself. Never spawn a subagent to review part
    of the diff, and never spawn another reviewer for a second opinion.
    This process already provides every review seat the work gets; a
    reviewer you spawn duplicates one of them at full cost, and its
    verdict counts for nothing. If the diff feels too large for one
    pass, review it in passes yourself and say so in your report.

    ## What to Check

    **Plan alignment:**
    - Does the implementation match the plan / requirements?
    - Are deviations justified improvements, or problematic departures?
    - Is all planned functionality present?

    **Code quality:**
    - Clean separation of concerns?
    - Proper error handling?
    - Type safety where applicable?
    - DRY without premature abstraction?
    - Edge cases handled?

    **Architecture:**
    - Sound design decisions?
    - Reasonable scalability and performance?
    - Security concerns?
    - Integrates cleanly with surrounding code?

    **Testing:**
    - Tests verify real behavior, not mocks?
    - Edge cases covered?
    - Integration tests where they matter?
    - All tests passing?

    **Production readiness:**
    - Migration strategy if schema changed?
    - Backward compatibility considered?
    - Documentation complete?
    - No obvious bugs?

    ## Calibration

    Categorize issues by actual severity. Not everything is Critical.
    Acknowledge what was done well before listing issues — accurate praise
    helps the implementer trust the rest of the feedback.

    If you find significant deviations from the plan, flag them specifically
    so the implementer can confirm whether the deviation was intentional.
    If you find issues with the plan itself rather than the implementation,
    say so.

    ## Output Format

    ### Strengths
    [What's well done? Be specific.]

    ### Issues

    #### Critical (Must Fix)
    [Bugs, security issues, data loss risks, broken functionality]

    #### Important (Should Fix)
    [Architecture problems, missing features, poor error handling, test gaps]

    #### Minor (Nice to Have)
    [Code style, optimization opportunities, documentation polish]

    For each issue:
    - File:line reference
    - What's wrong
    - Why it matters
    - How to fix (if not obvious)

    ### Recommendations
    [Improvements for code quality, architecture, or process]

    ### Assessment

    **Ready to merge?** [Yes | No | With fixes]

    **Reasoning:** [1-2 sentence technical assessment]

    ## Critical Rules

    **DO:**
    - Categorize by actual severity
    - Be specific (file:line, not vague)
    - Explain WHY each issue matters
    - Acknowledge strengths
    - Give a clear verdict

    **DON'T:**
    - Say "looks good" without checking
    - Mark nitpicks as Critical
    - Give feedback on code you didn't actually read
    - Be vague ("improve error handling")
    - Avoid giving a clear verdict
```

**Placeholders:**
- `[DESCRIPTION]` — brief summary of what was built
- `[PLAN_OR_REQUIREMENTS]` — what it should do (plan file path, task text, or requirements)
- `[BASE_SHA]` — starting commit
- `[HEAD_SHA]` — ending commit

**Reviewer returns:** Strengths, Issues (Critical / Important / Minor), Recommendations, Assessment

## Example Output

```
### Strengths
- Clean database schema with proper migrations (db.ts:15-42)
- Comprehensive test coverage (18 tests, all edge cases)
- Good error handling with fallbacks (summarizer.ts:85-92)

### Issues

#### Important
1. **Missing help text in CLI wrapper**
   - File: index-conversations:1-31
   - Issue: No --help flag, users won't discover --concurrency
   - Fix: Add --help case with usage examples

2. **Date validation missing**
   - File: search.ts:25-27
   - Issue: Invalid dates silently return no results
   - Fix: Validate ISO format, throw error with example

#### Minor
1. **Progress indicators**
   - File: indexer.ts:130
   - Issue: No "X of Y" counter for long operations
   - Impact: Users don't know how long to wait

### Recommendations
- Add progress reporting for user experience
- Consider config file for excluded projects (portability)

### Assessment

**Ready to merge: With fixes**

**Reasoning:** Core implementation is solid with good architecture and tests. Important issues (help text, date validation) are easily fixed and don't affect core functionality.
```

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč je review označeno jako read-only?

Reviewer pracuje na stejném checkoutu jako implementátor. Kdyby změnil working tree nebo HEAD, mohl by zničit nebo zkreslit práci a následné verdikty by se vztahovaly k jinému stavu. Pro jiné revize proto slouží oddělený worktree v /tmp, takže HEAD zůstává nedotčen.

2. Proč se rozsah zadává jako SHA a ne „poslední změny“?

SHA jsou nezpochybnitelné: dva přesné commity definují přesný diff. „Poslední změny“ by se mohly lišit podle času a branchí. Reviewer tak vždy kontroluje právě to, co bylo označeno.

3. K čemu je sekce „The spec is a vision document“?

Spec nikdy nepopíše všechny podmínky. Kdyby reviewer hlásil jen to, co spec zmiňuje, propustil by chyby v nepopsaných situacích. Pravidlo říká: očekávání rozumného uživatele je požadavek a ticho specu není souhlas.

4. Co je „Declined to judge“ a proč je před verdiktem?

Je to seznam věcí, které reviewer vzal v úvahu a odložil jako mimo plán, s důvodem. Rozhodnutí o nich pak dělá executor. Nic tak nepadá pod stůl a prázdný seznam znamená „nic jsem neodložil“.

5. Proč reviewer nesmí spouštět další subagenty?

Proces už zahrnuje všechna review sedadla. Další reviewer by duplikoval práci za plnou cenu a jeho verdikt se nepočítá. Pokud je diff velký, má se projít po částech samotným reviewerem a říct to v reportu.

6. Proč je povinná chvála před výčtem chyb?

Přesná chvála buduje důvěru implementátora, takže bere vážně i zbytek zpětné vazby. Musí být konkrétní, ne frázovitá.

7. Proč se závažnost kalibruje a „not everything is Critical“?

Kdyby vše bylo kritické, příjemce by neodlišil bugy od kosmetiky a ztratil by prioritu. Jasné kategorie Critical / Important / Minor řídí, co se musí opravit před merge.

8. Proč u každého nálezu `file:line`, důvod a oprava?

Nález bez místa je neověřitelný; bez důvodu nemotivuje; bez návrhu opravy zdržuje. Tato trojice dělá feedback akceschopný.

9. Proč verdikt „Ready to merge?“ nabízí tři hodnoty?

„Yes / No / With fixes“ odlišuje blokující stav od opravitelného. Pevný výčet nutí reviewera k jasnému rozhodnutí a zabraňuje vyhýbavým odpovědím.

10. Brání platforma Claude Code tomu, aby subagent spouštěl další subagenty?

Ne. Dokumentace dnes dovoluje vnořování do hloubky 3 (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, hodnota 1 vnořování vypne; tool Agent lze odebrat přes tools/disallowedTools). Zákaz v tomto promptu je proto procesní pravidlo: chrání před duplicitním review za plnou cenu, nikoli před technickou chybou. Tvrdě by se dal vynutit odebráním nástroje Agent v definici subagenta.

Slovník pojmů (12)

Code reviewer subagent

Subagent „Senior Code Reviewer“, který posuzuje hotovou práci proti plánu.

BASE_SHA / HEAD_SHA

Počáteční a koncový commit rozsahu. Určují diff, který se reviewuje.

Placeholder

Zástupný řetězec v hranatých závorkách ([DESCRIPTION], [PLAN_OR_REQUIREMENTS]…), který controller vyplní.

Vision document

Pohled na spec: popisuje cíl, ne všechny vstupy a podmínky. Mezery se posuzují očekáváním rozumného uživatele.

Declined to judge

Seznam odložených chování s důvody. Rozhoduje o nich executor.

Read-only review

Zákaz měnit working tree, index, HEAD a branch.

git worktree

Samostatný pracovní adresář téhož repozitáře. Umožňuje zkontrolovat jinou revizi bez posunu HEAD.

Calibration

Pravidla pro určení závažnosti: Critical, Important, Minor.

Strengths

Povinná sekce chvály, konkrétní a přesná.

Assessment

Závěr: Ready to merge? (Yes / No / With fixes) a dvouvětné zdůvodnění.

Plan alignment

Kontrola, zda implementace odpovídá plánu a zda jsou odchylky oprávněné.

Production readiness

Kontrola migrací, zpětné kompatibility, dokumentace a zjevných chyb.

↑ nahoru

Analyst common prompt (diagnosing-superpowers)

Společný základ všech analytických subagentů: role, vstupy, bezpečnost kontextu a pevný formát nálezů s důkazem.

Skill diagnosing-superpowers zkoumá, proč session s kódovacím agentem „šla špatně“. Práci dělá několik analytických subagentů, každý pro jednu dimenzi (náklady, plán, opakování…). Tento soubor je jejich společný základ: každý dimenzní prompt začíná větou „Read prompts/analyst-common.md first“.

Definuje čtyři věci. (1) Roli: analytik čte transcript na disku a vrací nálezy s důkazy; nic neopravuje, nic nemění v úložišti session a neříká, co má superpowers změnit. (2) Vstupy: CASE (cesta k case souboru, který popisuje zdroje a významy záznamů) a volitelný RANGE. (3) Bezpečnost kontextu: před čtením každého souboru se musí řídit references/context-safety.md a smí používat jen cesty z CASE. (4) Formát odpovědi: pevná šablona, kde každý nález má finding, evidence ve tvaru cesta:řádek — "citace", turns a confidence, a řádek Checked.

Klíčové pravidlo: dispatcher zahodí každý nález bez path:line. Tvrzení bez ověřitelného odkazu se tedy nikdy nedostane do reportu.

Zdrojový kód

skills/diagnosing-superpowers/prompts/analyst-common.md 39 řádků
You are an analyst subagent. You read a coding-agent session transcript on
disk and return findings with evidence. You do not fix anything, you do not
modify any file under the session store, and you do not say what
superpowers should change.

Inputs (from your dispatcher):
- CASE: absolute path of the case file. Read it first. It names the session
  files, the discovered sources and record meanings to use, and the
  context-safety rules you must follow. Use the recorded meanings rather than
  repeating discovery or assuming a harness format.
- RANGE (optional): a turn range or line range. If present, analyze only
  that range and say so in your Checked line.

Context safety: follow `references/context-safety.md`, named in CASE, on
every file before reading it, and extract fields with the recorded commands or
queries. "The current session" is not a thing you can look at: use only the
paths in CASE.

Human prompts are the records the case file identifies as human-typed. Hook
output, system reminders, and tool results are not human prompts. In a subagent
transcript, "user" is the parent agent.

Return format (nothing else):

```
## <Dimension> findings

- finding: <one sentence, what happened>
  evidence: <absolute path>:<line> — "<quote, at most 200 characters>"
  turns: <first human turn>–<last human turn>
  confidence: high | medium | low

Checked: <what you examined: files, line ranges, commands used>
```

The dispatcher discards any finding without a `path:line`, so do not
write one. If you found nothing, return `- none found` and the Checked
line.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč mají všechny dimenzní prompty společný soubor místo toho, aby každý opakoval pravidla?

Pravidla (formát, evidence, context safety) musí být u všech analytiků identická, aby dispatcher mohl výstupy slučovat. Jediný zdroj pravdy eliminuje rozjíždění a zkracuje jednotlivé prompty na to, co se liší: dimenzi.

2. Proč analytik „does not say what superpowers should change“?

Diagnóza má oddělovat pozorování od návrhu řešení. Kdyby analytik rovnou navrhoval opravy, zkreslil by výběr nálezů (hledal by to, co podporuje jeho řešení). Reader rozhodne až nad kompletními daty.

3. K čemu je povinný `path:line` u každého nálezu?

Je to důkaz, který lze zkontrolovat. Dispatcher nálezy bez něj ruší, takže se nemohou dostat do reportu halucinace ani domněnky. Nález je tak vždy dohledatelný v původním transcriptu.

4. Proč je citace omezena na 200 znaků?

Chrání kontext subagenta i dispatchera před velkými výpisy a snižuje riziko, že se do reportu dostane objemný nebo citlivý text. Stačí dost na identifikaci řádku.

5. Co dělá řádek `Checked:` a proč je povinný i při „none found“?

Říká, co analytik skutečně prozkoumal (soubory, rozsahy, příkazy). Bez něj by „nic nenalezeno“ mohlo znamenat „nehledal jsem“. Čtenář tak odliší negativní výsledek od nedokončené práce.

6. Proč se musí použít jen cesty z CASE a nikdy „current session“?

Aktuální session nelze „prohlížet“; analytik by si mohl vymyslet, co v ní bylo. Case soubor je explicitní, ověřený seznam zdrojů, takže výsledek je reprodukovatelný a omezený na data, o kterých dispatcher ví.

7. Proč prompt rozlišuje „human prompts“ od hook outputu, system reminders a tool results?

Kdyby se zaměnily, analytik by za pokyn uživatele označil automatický text. Rozlišení chrání před falešnými nálezy typu „uživatel řekl X“. Ve subagent transcriptu je navíc „user“ rodičovský agent, ne člověk.

8. Jak pomáhá volitelný RANGE?

Dovoluje rozdělit dlouhou session na úseky pro více analytiků. Analytik musí rozsah uvést v Checked, takže dispatcher vidí, které části jsou pokryté.

Slovník pojmů (10)

Analyst subagent

Subagent s úzkou rolí: čte, hledá, vrací nálezy. V tomto příkladu nikdy nic neopravuje.

CASE

Absolutní cesta k case souboru. Obsahuje seznam souborů session, objevené významy záznamů a pravidla bezpečnosti kontextu. Je to první, co analytik čte.

RANGE

Volitelný rozsah turnů nebo řádků. Omezuje analýzu a musí být uveden v Checked.

Dimenze

Jeden aspekt, který analytik zkoumá (cost and time, stumbles, repeated work…). Konkrétní dimenze přidává navazující prompt.

Context safety

Pravidla z references/context-safety.md: jak bezpečně číst soubory (např. změřit velikost a nevypisovat obří záznamy), aby analytik nezahltil kontext.

Transcript

Záznam session uložený na disku. Jediný zdroj pravdy pro analytika.

Human prompt

Záznam, který case soubor označí jako napsaný člověkem. Hook output ani tool results mezi ně nepatří.

Evidence

Pole path:line — "citace". Bez něj se nález zahazuje.

Confidence

Hodnota high / medium / low, jak jistý si je analytik nálezem. Pomáhá čtenáři váhu nálezů posoudit.

Dispatcher

Agent, který analytiky spouští a jejich výstupy sbírá. Vynucuje pravidlo o path:line.

↑ nahoru

Cost and time (diagnosing-superpowers)

Dimenze analytika: kam v session odešly tokeny a čas, včetně největších výsledků nástrojů a compaction.

Prompt zadává analytikovi, aby učetnil spotřebu: tokeny i wall-clock čas. Odkazuje na společný základ (analyst-common.md) a přidává šest kroků: (1) tokeny podle usage záznamů a významů čítačů z case souboru, přičemž musí být řečeno, zda je čítač přírůstkový, nebo kumulativní; (2) čas z evidovaných timestampů, pět nejdelších turnů a mezery delší než deset minut; (3) deset největších výsledků nástrojů; (4) compaction události; (5) asociované session (subagenti); (6) co celkové součty dominuje, s čísly, bez spekulací o důvodu.

Zásadní je opatrnost: kumulativní čítače se odečítají, chybějící pozorování se nikdy nepočítá jako nula a nepodporovaná pole se označí jako nepřítomná. Prompt tak brání vymyšleným číslům.

Zdrojový kód

skills/diagnosing-superpowers/prompts/cost-and-time.md 29 řádků
Read `prompts/analyst-common.md` first; it gives your role, inputs,
context-safety rules, and the return format. This file adds the dimension.

Dimension: Cost and time

Account for where tokens and wall-clock went.

1. Tokens. Use only the usage records and counter meanings established in the
   case file. State whether each counter is incremental or cumulative before
   calculating totals; difference cumulative observations without turning a
   missing observation into zero. Report the five turns with the largest
   supported totals and the supported totals per associated session.
2. Wall-clock. Use the evidenced timestamp fields, event boundaries, and units
   recorded in the case file. Report the five longest supported turns and any
   gap longer than ten minutes between consecutive events (idle, waiting on an
   associated session, or waiting on your human partner; say which only when
   the records show it).
3. Largest tool results: use the case file's evidenced tool-result records to
   report the ten largest results with their tool and turn. Measure records
   before extracting bounded content.
4. Compactions: count and locate records whose meaning as compaction events was
   established during discovery. Report available before/after counters and
   what the session was doing when each fired; mark unsupported fields absent.
5. Associated sessions: count them and report supported usage, duration, and
   dispatching turn for each.
6. Report the turns, subagents, tools, or repeats that dominate the
   totals, with numbers. Do not speculate about why a
   turn was expensive beyond what the transcript shows.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč musí analytik nejdřív určit, zda je čítač přírůstkový, nebo kumulativní?

Sečtení kumulativních hodnot by součet mnohonásobně nafouklo. U kumulativních čítačů je správný údaj rozdíl mezi po sobě jdoucími pozorováními. Špatné určení by zkreslilo celou analýzu nákladů.

2. Proč se chybějící pozorování nesmí brát jako nula?

Nula by vypadala jako „nic se nespotřebovalo“, ve skutečnosti jde o „nevíme“. Prompt proto chce pole označit jako chybějící; nález zůstane poctivý a nepodhodnotí náklady.

3. Proč se hlásí „top 5“ a „top 10“ a ne všechno?

Pořadí s pevným počtem je stručné a porovnatelné mezi sessions. Čtenář vidí dominantní položky bez zahlcení tisíci řádků.

4. Proč se zjišťují mezery delší než deset minut?

Dlouhá pauza obvykle znamená čekání (na člověka, na subagenta, na idle), které je část wall-clock času, ale ne práce modelu. Prompt ale přikazuje pojmenovat příčinu jen tehdy, když ji záznamy ukazují.

5. Proč se kontrolují největší výsledky nástrojů?

Velký tool result zabírá kontext a prodražuje všechny další turny. Je to častý skrytý zdroj nákladů; znalost, které volání ho způsobilo, je užitečná pro další optimalizaci.

6. Proč „Measure records before extracting bounded content“?

Nejdřív se změří velikost záznamu, a teprve pak se vytáhne omezená část. Zabrání to načtení obřího záznamu do kontextu analytika, což by byl přesně ten problém, který analýza hledá.

7. K čemu je analýza compaction událostí?

Compaction znamená, že kontext narostl natolik, že se musel zkrátit. Je to signál drahé session; po compaction navíc často následuje opakovaná práce (viz dimenze repeated work).

8. Proč prompt zakazuje spekulovat, proč byl turn drahý?

Analytik má hlásit čísla a zdroje, ne příčiny odvozené z domněnek. Vysvětlení smí dát jen tam, kde ho transcript ukazuje; jinak by nález nebyl podložený path:line.

Slovník pojmů (9)

Token usage

Záznamy o spotřebě tokenů ve transcriptu. Jejich význam (která pole co znamenají) je uložen v case souboru.

Přírůstkový čítač

Hodnota, která při každém záznamu udává spotřebu jen tohoto kroku. Lze sčítat.

Kumulativní čítač

Hodnota, která roste v průběhu session. Pro spotřebu jednotlivých kroků se musí použít rozdíl po sobě jdoucích pozorování.

Wall-clock

Reálný čas na hodinách, včetně čekání. Odlišuje se od času strávenou práci modelu.

Idle gap

Mezera mezi dvěma po sobě jdoucími událostmi delší než 10 minut. Může jít o čekání na člověka nebo subagenta.

Tool result

Výstup volání nástroje vložený do kontextu. Velké výsledky jsou hlavní zdroj nafouknutí kontextu.

Compaction

Zkrácení kontextu, když se blíží limitu. Prompt počítá, kdy k němu došlo a na čem agent pracoval.

Asociovaná session

Další session spojená s hlavní (typicky subagent). Prompt hlásí jejich spotřebu, trvání a turn, ve kterém byly spuštěny.

Dominující položka

Turn, nástroj nebo opakování, které se na celkovém součtu podílí nejvíce. Hlásí se s čísly.

↑ nahoru

Plan adherence (diagnosing-superpowers)

Dimenze analytika: dohledat dohodnutý plán a porovnat každý jeho krok s tím, co se skutečně stalo.

Analytik nejdřív zrekonstruuje plán, na kterém se session shodla („plán“ je jakýkoli dohodnutý postup, ne git commity), a pak každý krok namapuje na skutečné akce. Plán hledá v textu asistenta před lidským „ano / ok / pokračuj“, v souborech zapsaných do docs/, plans/, specs/, v todo záznamech nebo číslovaných checklistech. Každý krok cituje s path:line.

Druhý krok označí strukturní události (compaction, resume, přerušené turny, spuštění asociovaných session), protože drift hned po nich je samostatný nález. Třetí krok hlásí: přeskočené kroky, kroky provedené v jiném pořadí, potichu změněné kroky, vymyšlenou práci, kterou žádný krok nekryje, a drift po strukturní události. Pokud se plán nedá obnovit, je to jediný nález, s řádky, které se zkontrolovaly.

Zdrojový kód

skills/diagnosing-superpowers/prompts/plan-adherence.md 30 řádků
Read `prompts/analyst-common.md` first; it gives your role, inputs,
context-safety rules, and the return format. This file adds the dimension.

Dimension: Plan adherence

Recover the plan the session agreed to, then map each plan step to what
happened. "Plan" here means any agreed course of action, not git commits.

1. Find the agreed plan: a design or plan agreed in chat (look for the
   assistant text preceding a human "yes/ok/go ahead"), a spec or plan file
   written during the session (tool calls that write under `docs/`,
   `plans/`, `specs/`, or any file the human named), a todo-list record whose
   meaning was established in the case file, or any numbered checklist in
   assistant text. Quote each plan step with its `path:line`.
2. Mark structural events between the plan and its execution: compaction
   events identified during discovery, resumes, aborted turns, and associated
   session dispatches. Note their line numbers; plan drift right after one of
   these is a distinct finding.
3. For each plan step, find the tool calls and assistant text that
   executed it, or establish that none did. Report:
   - steps skipped (no execution found; quote the plan step);
   - steps executed out of order (line numbers show the order);
   - steps silently changed (execution differs from the plan step in a
     way the assistant never announced; quote both);
   - steps invented (work done that no plan step covers);
   - drift immediately after a structural event (cite the event line and
     the first divergent action).
4. If there is no recoverable plan, say so as the only finding, with
   the lines you checked.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se „plán“ nedefinuje jako git commity?

Plán je dohoda o postupu, ne záznam v historii. Commity vznikají až po provedení a nemusí existovat. Širší definice (chat, soubor, todo, checklist) pokrývá všechny způsoby, jak se plán v sessions skutečně dohodne.

2. Proč se hledá text asistenta před lidským souhlasem?

Souhlas člověka („yes, go ahead“) schvaluje to, co mu asistent předtím navrhl. Tím se plán zakotví na konkrétní řádek, takže nález má ověřitelný základ.

3. Proč se zvlášť zaznamenávají compaction, resume a přerušené turny?

Po těchto událostech agent o plánu často ztrácí kontext a odchýlí se od něj. Oddělení takového driftu od náhodných odchylek pomáhá najít systémovou příčinu.

4. Jaký je rozdíl mezi „silently changed“ a „invented“?

„Silently changed“ je krok, který byl proveden jinak, než plán říká, aniž to asistent oznámil. „Invented“ je práce, kterou žádný krok plánu vůbec nepokrývá. První je odchylka od dohody, druhá rozšíření rozsahu.

5. Proč se u změněných kroků cituje plán i provedení?

Čtenář musí vidět obě verze vedle sebe, aby posoudil, zda jde o skutečnou odchylku. Bez citací by nález byl subjektivní.

6. Co když plán v session nikdy nebyl?

Pak je jediným nálezem „plán nelze obnovit“, s uvedenými řádky, které analytik zkontroloval. Nesmí si plán domyslet a pak ho vyhodnocovat.

7. Proč se řád „steps executed out of order“ opírá o čísla řádků?

Pořadí v transcriptu je objektivní. Čísla řádků jsou jednoznačné a ověřitelné, takže posouzení pořadí nezávisí na dojmu.

8. Proč analytik nehodnotí, zda byla odchylka špatná?

Report má být popisný. Odchylka může být oprávněná (člověk změnil zadání). Posoudit to je úkol čtenáře, který vidí celý kontext.

Slovník pojmů (9)

Agreed plan

Dohodnutý postup, který session schválila. Může být v chatu, v souboru, v todo záznamu nebo checklistu.

Plan step

Jedna položka plánu citovaná s path:line. Jednotka, ke které se mapuje provedení.

Skipped step

Krok plánu, ke kterému nebylo nalezeno žádné provedení.

Out-of-order step

Krok proveden v jiném pořadí, než plán určuje.

Silently changed step

Provedení se liší od plánu a asistent odchylku neoznámil.

Invented step

Práce provedená bez opory v kroku plánu.

Structural event

Compaction, resume, přerušený turn nebo spuštění asociované session. Okolo nich se hledá drift.

Drift

Postupné odchylování od plánu. Hlásí se hlavně, když začne bezprostředně po strukturní události.

Todo záznam

Záznam seznamu úkolů, jehož význam je zapsán v case souboru. Jedna z možných podob plánu.

↑ nahoru

Quality evidence (diagnosing-superpowers)

Dimenze analytika: posuzuje, zda procesní tvrzení session („hotovo“, „testy prošly“) podložily skutečné výsledky.

Tato dimenze „soudí proces podle jeho vlastních tvrzení“. Nejde o code review – nehodnotí se vytvořený kód. Analytik prochází pět oblastí: (1) testy: všechny běhy s výsledkem a reakce asistenta na selhání; (2) ověření za tvrzeními: kdykoli asistent napíše „hotovo, opraveno, prochází, ověřeno“, hledá v témže turnu zpětně výsledek nástroje, který to dokládá; (3) commity: porovnání zprávy commitu s tím, co se v předchozích turnech udělalo; (4) review feedback: body, které byly uznány, ale neopraveny, nebo odmítnuty bez důvodu; (5) akceptační kritéria: každé označí jako met / not met / not checked s řádkem důkazu.

Příklad vychází z principu skillu verification-before-completion: tvrzení o hotové práci musí být podloženo výstupem.

Zdrojový kód

skills/diagnosing-superpowers/prompts/quality-evidence.md 27 řádků
Read `prompts/analyst-common.md` first; it gives your role, inputs,
context-safety rules, and the return format. This file adds the dimension.

Dimension: Quality evidence

Judge the process against its own claims. This is not a code review; do
not evaluate the code the session produced.

1. Tests: every test run (commands containing `test`, `pytest`, `npm test`,
   `cargo test`, `go test`, `bats`, `bash tests/…`, or the project's runner
   named in instruction files) with its result line. Report runs that
   failed and what the assistant did next.
2. Verification behind claims: find assistant text claiming done, fixed,
   passing, verified, works, complete. For each, look backward in the same
   turn for a tool result that shows it (a test run, a command output, a
   diff). Report claims with no supporting result in that turn.
3. Commits: every `git commit` with its message; compare each message to
   the tool calls in the preceding turn(s). Report commits whose message
   claims work that no tool call performed, and work performed that was
   never committed when the agreed plan said it would be.
4. Review feedback: where a reviewer (human or subagent) raised points,
   find the response. Report points acknowledged but not acted on, and
   points dismissed without a stated reason.
5. Acceptance criteria: if the case file's problem statement or the
   agreed plan states criteria, report each as met / not met /
   not checked with the evidence line.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč tato dimenze výslovně není code review?

Diagnóza zkoumá chování procesu, ne kvalitu kódu. Kdyby analytik hodnotil kód, míchal by dva různé úkoly a jeho nálezy by byly subjektivní. Tady se jen porovnává tvrzení s důkazem.

2. Jak se pozná „claim without verification“?

Analytik najde text typu „done / fixed / passing“ a v témže turnu zpětně hledá výsledek nástroje (běh testu, výstup příkazu, diff). Pokud tam žádný není, tvrzení je nepodložené.

3. Proč se hledá důkaz „in the same turn“, ne kdekoli dříve?

Starý test nedokazuje současný stav. Ověření musí následovat po poslední změně, jinak by tvrzení „prochází“ mohlo vycházet z výsledku před úpravou.

4. Proč se porovnávají zprávy commitů s předchozími tool calls?

Zpráva commitu je tvrzení o provedené práci. Pokud popisuje změnu, kterou nic neprovedlo, je to falešný záznam v historii. Obráceně, nezacommitovaná práce, kterou plán slibuje, je také nález.

5. Jak se hodnotí review feedback?

Hledá se odpověď na každý bod. Nález je bod uznaný, ale nezpracovaný, a bod odmítnutý bez uvedeného důvodu. Tím se odhalí „ticho po review“.

6. Proč u akceptačních kritérií existuje i hodnota „not checked“?

Odlišuje „nesplněno“ od „nikdo to neověřil“. Nepovolit třetí stav by nutilo analytika hádat; takto je nález přesný.

7. Které příkazy se počítají jako testy?

Prompt vyjmenovává vzory (test, pytest, npm test, cargo test, go test, bats, bash tests/…) a runner z instrukčních souborů projektu. Široký seznam zachytí různé ekosystémy.

8. Co má analytik hlásit u selhaných testů?

Nejen že selhaly, ale i co asistent udělal dál: opravil, ignoroval, nebo je označil za nesouvisející. To ukazuje, zda byl proces disciplinovaný.

Slovník pojmů (10)

Quality evidence

Doklady, že tvrzení o kvalitě (testy prošly, práce je hotová) mají oporu ve výsledcích nástrojů.

Claim

Tvrzení asistenta o stavu práce, např. „fixed“ nebo „passing“.

Supporting result

Výsledek nástroje (běh testu, výstup příkazu, diff), který tvrzení dokládá.

Test run

Příkaz, který spustil testy, s výsledkovým řádkem. Každý se eviduje.

Commit message

Text commitu. V příkladu se porovnává s prací, kterou skutečně předchozí tool calls provedly.

Review feedback

Připomínky od člověka nebo subagenta. Sleduje se, zda byly zpracovány.

Acknowledged but not acted on

Bod, který asistent uznal, ale nic podle něj neudělal.

Dismissed without reason

Bod zamítnutý bez vysvětlení.

Acceptance criteria

Kritéria úspěchu z problem statementu nebo plánu. Hodnotí se met / not met / not checked.

Verification before completion

Zásada, že tvrzení o dokončení musí následovat po výstupu, který ho dokládá. Tato dimenze ji kontroluje zpětně.

↑ nahoru

Repeated work (diagnosing-superpowers)

Dimenze analytika: hledá práci, kterou session udělala víckrát, podle klíčů tool calls a prahů opakování.

Analytik převede každé volání nástroje na čtveřici (řádek, turn, nástroj, klíč), kde klíč je cesta souboru (čtení, úpravy, zápisy), celý text příkazu (shell), description plus prvních 80 znaků promptu (subagenti) nebo dotaz (vyhledávání). Pak seskupí podle (nástroj, klíč) a hlásí skupiny nad prahem: čtení a hledání 3×, úpravy 2×, shell příkazy 2× (kromě stavových a testovacích příkazů), subagenti se stejným popisem 2×.

U každé skupiny se ověří, zda se mezi opakováními něco změnilo (zápis do souboru, compaction, lidská oprava). Opakované čtení po úpravě není nález; po compaction je nález přiřazený compaction; bez změny mezi je nález sám o sobě. Nakonec se hledají re-derived decisions: závěr, ke kterému asistent dojde podruhé. Jeden nález na skupinu, s prvním a posledním řádkem a počtem.

Zdrojový kód

skills/diagnosing-superpowers/prompts/repeated-work.md 31 řádků
Read `prompts/analyst-common.md` first; it gives your role, inputs,
context-safety rules, and the return format. This file adds the dimension.

Dimension: Repeated work

Find work the session did more than once.

1. Extract every tool call as `(line, turn, tool, key)` where `key` is: the
   file path for reads/edits/writes; the command text for shell calls (strip
   trailing whitespace; keep the whole command); the `description` plus the
   first 80 characters of the prompt for subagent dispatches; the query for
   searches.
2. Group by `(tool, key)` and report the groups at or over threshold:

   | Category | Threshold | Exempt |
   |---|---|---|
   | reads, searches | 3 | |
   | edits | 2 | |
   | shell commands | 2 | status checks and test runs (`git status`, `ls`, `pwd`, test runners) |
   | subagent dispatches | 2 with the same description | |
3. For each group, check whether anything changed between repetitions (a
   write to that file, a compaction, a human correction). Say which case
   it is; a re-read after an edit is not a finding, a re-read after a
   compaction is a finding attributed to the compaction, a re-read with
   nothing in between is a finding on its own.
4. Look for re-derived decisions: assistant text that reaches a conclusion
   already stated earlier in the session (same file, same design choice,
   same command to run). Quote both places.
5. One finding per group, with the first and last line numbers and the
   count.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se tool calls normalizují na klíč a nehledají se podobné texty?

Klíč je deterministický: stejná cesta nebo stejný příkaz je jednoznačně stejná práce. Podobnost by vyžadovala posuzování a vedla k hádání. Díky klíčům lze skupiny spočítat přesně.

2. Proč jsou prahy různé pro různé kategorie?

Dvojí čtení souboru je běžné, dvojí úprava stejného souboru je podezřelá, dvojí spuštění stejného subagenta je drahé. Prahy vystihují, od kdy opakování znamená plýtvání.

3. Proč jsou `git status`, `ls`, `pwd` a testy z prahu vyňaté?

Je legitimní je spouštět opakovaně: kontrolují měnící se stav. Zahrnutí by plnilo report falešnými nálezy.

4. Proč se zkoumá, co se mezi opakováními stalo?

Opakované čtení po úpravě je správné. Opakované čtení po compaction ukazuje, že agent ztratil kontext, a opakované čtení bez změny je skutečné plýtvání. Rozlišení vede ke správné příčině.

5. Co jsou „re-derived decisions“?

Závěry, ke kterým agent dojde znovu, ačkoli je už dříve v session učinil (stejný soubor, stejná volba návrhu, stejný příkaz). Prompt chce citovat obě místa, takže je zjevné, že šlo o opakování.

6. Proč subagentní dispatch používá `description` plus 80 znaků promptu?

Samotný popis může být obecný. Přidání začátku promptu odliší různá zadání se stejným popisem, takže se nehlásí falešné opakování.

7. Proč jeden nález na skupinu, a ne na každé opakování?

Kompaktní report. Řádky prvního a posledního výskytu s počtem stačí k dohledání, a čtenář neprochází desítky téměř stejných položek.

8. Proč opakování přiřazené k compaction je zvláštní kategorie?

Příčinou je zde mechanismus kontextu, ne rozhodnutí agenta. Takový nález motivuje změny, které pomohou práci přežít compaction.

Slovník pojmů (9)

Tool call key

Identifikátor práce volání: cesta, příkaz, popis subagenta nebo dotaz. Slouží k seskupování.

Threshold (práh)

Počet opakování, od kterého se skupina hlásí. Liší se podle kategorie.

Exempt command

Příkaz vyňatý z počítání, například git status nebo spuštění testů.

Repetition

Opakovaná dvojice (nástroj, klíč).

Intervening change

Událost mezi opakováními (zápis, compaction, lidská oprava), která opakování může ospravedlnit.

Re-read after compaction

Opakované čtení způsobené ztrátou kontextu. Nález se přiřazuje compaction.

Re-derived decision

Závěr učiněný podruhé, ačkoli už v session padl.

Subagent dispatch

Spuštění subagenta. Opakování se stejným popisem se hlásí.

Finding per group

Jeden nález za skupinu s prvním a posledním řádkem a počtem.

↑ nahoru

Request conflicts (diagnosing-superpowers)

Dimenze analytika: konflikty mezi pokyny člověka navzájem i vůči instrukčním souborům, a jak je asistent vyřešil.

Analytik vypíše každý lidský prompt s řádkem a turnem a z každého vytáhne instrukce (rozkazy, omezení, „don't“, „always“, „never“, „only“, rozsah práce). Pak hlásí čtyři druhy nálezů: dva lidské pokyny, které nejdou splnit současně; lidský pokyn v rozporu s načteným instrukčním souborem (CLAUDE.md, AGENTS.md, GEMINI.md nebo ekvivalent); pokyn přeskočit, ignorovat nebo přebít krok, skill či pravidlo a co následovalo; upřesňující otázka asistenta, jejíž odpověď změnila rozsah.

Důležité: analytik neposuzuje, kdo měl pravdu. Hlásí konflikt a to, jak ho asistent vyřešil. Tím se zachová neutralita diagnózy.

Zdrojový kód

skills/diagnosing-superpowers/prompts/request-conflicts.md 21 řádků
Read `prompts/analyst-common.md` first; it gives your role, inputs,
context-safety rules, and the return format. This file adds the dimension.

Dimension: Request conflicts

1. List every human prompt with line and turn. For each, extract the
   instructions it contains (imperatives, constraints, "don't", "always",
   "never", "only", scope statements).
2. Report:
   - two human instructions that cannot both be followed (quote both, with
     lines), and what the assistant did;
   - a human instruction that conflicts with an instruction file loaded in
     the session (CLAUDE.md, AGENTS.md, GEMINI.md, or the harness's
     equivalent; paths are in the case file), quoting both;
   - a human instruction to skip, ignore, or override a step, skill, or
     rule, and what happened afterwards;
   - an instruction the assistant asked to clarify and the answer, when the
     answer changed scope.
3. Do not judge whether your human partner was right. Report the conflict
   and the assistant's resolution.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se začíná výpisem všech lidských promptů s řádkem a turnem?

Konflikt lze najít jen když jsou všechny pokyny vedle sebe. Řádek a turn dávají každému pokynu pevnou adresu, na kterou se nález odkáže.

2. Proč se kromě pokynů mezi sebou kontrolují i instrukční soubory?

Instrukční soubor (např. CLAUDE.md) platí po celou session, ale člověk ho při psaní pokynu může zapomenout. Rozpor mezi nimi je častá příčina matoucího chování asistenta.

3. Proč se zvlášť sleduje pokyn „skip / ignore / override“?

Takový pokyn ruší krok skillu nebo pravidlo. Důležité je, co se stalo potom: zda asistent poslechl, nebo se k pravidlu vrátil. To prozrazuje, jak jsou pravidla ve skillech vynucovaná.

4. Proč má analytik zakázáno soudit, zda měl člověk pravdu?

Diagnóza má dát fakta. Soudit by znamenalo, že by analytik rozhodoval o cílech uživatele, což mu nepřísluší. Reader má celý kontext a rozhodne sám.

5. Proč je zajímavá otázka asistenta, kterou člověk odpověděl změnou rozsahu?

Ukazuje, že původní zadání bylo nejasné. Takové momenty bývají zdrojem pozdějšího driftu od plánu.

6. Jaká slova prompt zmiňuje jako signál instrukce?

„Don't“, „always“, „never“, „only“ a výroky o rozsahu. Jsou to formulace, které vytvářejí omezení, a tedy možný konflikt.

7. Co analytik uvede kromě samotného konfliktu?

Co asistent v dané situaci udělal. Konflikt sám o sobě nestačí; zajímá nás, jak ho agent vyřešil (zvolil jednu stranu, ptal se, ignoroval).

8. Proč je tato dimenze samostatná, a ne součást plan adherence?

Plan adherence porovnává provedení s plánem. Konflikty pokynů vznikají už před plánem a mají jinou příčinu (nejednoznačné zadání), proto potřebují vlastní pohled.

Slovník pojmů (8)

Human instruction

Pokyn z lidského promptu (rozkaz, omezení, rozsah). Základní jednotka této dimenze.

Instruction file

Soubor s trvalými pokyny pro agenta (CLAUDE.md, AGENTS.md, GEMINI.md). Cesty jsou v case souboru.

Conflict

Dvojice pokynů, které nelze splnit zároveň.

Override

Pokyn zrušit nebo obejít krok, skill nebo pravidlo.

Scope statement

Výrok vymezující rozsah práce („only the tests“, „don't touch config“).

Clarification

Upřesňující otázka asistenta. Zajímá nás, když odpověď změnila rozsah.

Resolution

Způsob, jakým asistent konflikt vyřešil. Hlásí se bez hodnocení.

Turn

Jedna výměna zahájená lidským promptem.

↑ nahoru

Scrub (diagnosing-superpowers)

Prompt scrubbera, který přepíše všechny soubory balíčku tak, aby mohl opustit stroj, a vytvoří scrub-log.

Než se diagnostický balíček (bundle) odešle mimo počítač, musí z něj zmizet citlivé údaje. Scrubber je subagent, který přepíše každý soubor pod BUNDLE a vytvoří BUNDLE/scrub-log.md. Nesmí sáhnout na nic mimo bundle. Řídí se sdílenou references/redaction-policy.md, která definuje kategorie a stabilní zástupné hodnoty (placeholdery).

Klíčová vlastnost: stejná původní hodnota se vždy nahrazuje stejným placeholderem, s čísly podle prvního výskytu. Hodnota nalezená nejdřív v report.md se tedy nahradí i v transcripts/. Po přepsání se znovu spočítají výskyty a do logu se zapíše tabulka placeholder → kategorie → počet. Do logu nikdy nepatří původní hodnota ani plaintextová mapa.

Zdrojový kód

skills/diagnosing-superpowers/prompts/scrub.md 30 řádků
Read and follow `references/redaction-policy.md` before processing any file.
Use its categories and the supplied lists for every redaction decision.

You are the scrubber. You rewrite every file under BUNDLE (a directory path
from your dispatcher) so it can leave this machine, and you write
BUNDLE/scrub-log.md. You never touch anything outside BUNDLE.

Inputs:
- BUNDLE: absolute path of the bundle directory.
- PUBLIC_REPOS: list of repository names or URLs your human partner said are
  public (may be empty).
- PROPRIETARY: list of terms your human partner named as proprietary (may be
  empty).

The shared policy defines the categories and stable placeholders. Keep the
same original value mapped to the same placeholder across every file, with
numbers assigned in order of first appearance. Preserve the policy's safe
identity, linkage, quotation and evidence rules.

Procedure:
1. `find BUNDLE -type f` and process every file, including
   `environment.json` and `findings/*.md`.
2. Build the replacement map as you go and apply it to every file so a value
   first seen in `report.md` is also replaced in `transcripts/`.
3. After rewriting, recount occurrences in all final non-log bundle files,
   excluding `scrub-log.md`. Write `BUNDLE/scrub-log.md` as a table of
   placeholder → category → count. Never write a plaintext replacement map or
   an original value into the log.
4. Return the scrub-log table and the list of files rewritten. Nothing else.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč musí být mapování hodnota → placeholder konzistentní napříč soubory?

Aby zůstala zachována souvislost. Když se jeden uživatel objeví na pěti místech, čtenář musí poznat, že jde o tutéž osobu (user-1), jinak by se ztratila možnost analýzy. Konzistence zachovává strukturu, ne obsah.

2. Proč se čísla placeholderů přidělují podle pořadí prvního výskytu?

Je to deterministické pravidlo: stejný vstup vždy dá stejné číslování. Scrub-audit i čtenář tak mohou výsledek ověřit.

3. Proč scrub-log nesmí obsahovat původní hodnoty?

Log by byl součástí bundle a opustil by stroj. Kdyby obsahoval mapu zpět na originál, zcela by popřel smysl scrubování. Proto je v něm jen placeholder, kategorie a počet.

4. Proč se po přepsání výskyty znovu přepočítají ze všech souborů?

Počty v logu musí odpovídat skutečnému výsledku, ne záměru. Přepočet z finálních souborů odhalí případ, že nějaký soubor zůstal neošetřený.

5. Proč scrubber nesmí sahat mimo BUNDLE?

Omezuje škody: chyba nebo halucinace nemůže poškodit původní session ani jiné soubory. Zdroj dat zůstává nedotčený.

6. Proč zpracovávat i `environment.json` a `findings/*.md`?

Citlivé údaje se objevují i v metadatech a v nálezech (cesty, názvy repozitářů). Zpracování „každého souboru“ nenechává výjimky.

7. Proč jsou vstupem seznamy PUBLIC_REPOS a PROPRIETARY?

Člověk ví, které repozitáře jsou veřejné (jejich názvy lze ponechat) a které termíny jsou proprietární (musí zmizet). Scrubber to sám odvodit nedokáže.

8. Co scrubber vrací?

Pouze tabulku z logu a seznam přepsaných souborů. Žádné komentáře navíc; dispatcher potřebuje strojově čitelný výsledek pro další krok (audit).

Slovník pojmů (9)

Bundle

Adresář s diagnostickými soubory (report, transcripts, findings, environment.json), který se má sdílet.

Scrubber

Subagent, který bundle přepisuje a odstraňuje citlivá data.

Redaction policy

Dokument references/redaction-policy.md s kategoriemi, seznamy a pravidly zástupných hodnot.

Placeholder

Stabilní náhrada citlivé hodnoty, např. user-1. Zachovává odkazování bez odhalení originálu.

Replacement map

Mapa původní hodnota → placeholder, kterou scrubber průběžně staví. Nesmí se zapsat do souboru.

scrub-log.md

Tabulka placeholder → kategorie → počet. Jediný záznam o proběhlém scrubování.

PUBLIC_REPOS

Seznam repozitářů označených člověkem za veřejné.

PROPRIETARY

Seznam termínů označených člověkem za proprietární.

Recount

Opětovné spočítání výskytů ve finálních souborech (mimo samotný log).

↑ nahoru

Scrub audit (diagnosing-superpowers)

Prompt nezávislého auditora, který hledá, co scrubber přehlédl, a vrací CLEAN nebo seznam MISSED bez citlivých hodnot.

Druhý krok ochrany soukromí: scrub auditor čte celý bundle po scrubberovi a hledá jen to, co scrubber minul. Nic neopravuje, jen hlásí. Čte každý soubor celý (velikost nejdřív změří přes wc -c; soubory nad 200 KB čte po částech) a aplikuje stejnou redaction policy na všechno, včetně citovaného textu transcriptů, commit zpráv, git author řádků a šifrovaných payloadů. Kontroluje také, že zůstala zachována bezpečná struktura potřebná k podpoře nálezů.

Výstup je buď CLEAN, nebo MISSED se seznamem soubor:řádek — kategorie — nesenzitivní popis. Nikdy se nevypisuje původní citlivá hodnota. CLEAN znamená pouze, že soukromí je v pořádku; neříká nic o tom, zda jsou nálezy dál podložené.

Zdrojový kód

skills/diagnosing-superpowers/prompts/scrub-audit.md 34 řádků
Read and follow `references/redaction-policy.md` before inspecting any file.
Use its categories and the supplied lists for every audit decision.

You are the scrub auditor. Another agent has already scrubbed every file
under BUNDLE. Your only job is to find what it missed. You do not fix
anything; you report.

Inputs:
- BUNDLE: absolute path of the bundle directory.
- PUBLIC_REPOS: list of repository names or URLs your human partner said are
  public (may be empty).
- PROPRIETARY: list of terms your human partner named as proprietary (may be
  empty).

Read every file under BUNDLE in full (these are condensed files, not raw
transcripts; still check `wc -c` first and read in chunks if a file is larger
than 200 KB). Apply the shared policy to every file, including quoted
transcript text, commit messages, git author lines, and encrypted payloads.
Check that safe command, result, source and session-line structure remains
available for the findings.

Return CLEAN only if no policy misses or unresolved classifications remain.
Otherwise return:

```
MISSED
- <file>:<line> — <category> — <non-sensitive description or classification question>
...
```

Never include the original sensitive value. CLEAN addresses privacy only; it
does not establish that exported findings remain supported. Do not comment on
the scrub's quality. Do not suggest fixes.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč audit dělá jiný agent než scrub?

Princip dvou očí: agent, který chybu udělal, ji obvykle nevidí. Nezávislý auditor nemá úmysl „potvrdit“ vlastní práci a hledá jen chyby.

2. Proč auditor nic neopravuje?

Oprava by smísila role a znemožnila ověření: nevíme, co scrubber minul, když to auditor tiše opravil. Audit proto jen hlásí a oprava se vrací scrubberovi.

3. Proč se nikdy nevypisuje původní hodnota?

Zpráva auditora by jinak sama citlivý údaj prozradila. Proto stačí soubor, řádek, kategorie a popis typu „e-mail adresa v git author řádku“.

4. Proč se kontroluje i citovaný text v transcriptech, commit zprávy a git author řádky?

Citlivá data se nejčastěji skrývají v méně zřejmých místech: v citacích, metadatech a hlavičkách commitů. Prohledání jen hlavního textu by je minulo.

5. Co znamená, že „CLEAN addresses privacy only“?

Že audit neověřuje správnost závěrů reportu. Report může po scrubu obsahovat tvrzení, která už nemají oporu v textu; to je jiná kontrola.

6. Proč se velikost souboru nejdřív měří?

Aby se auditor nezahltil obřím souborem. Při velikosti nad 200 KB čte po částech.

7. Co auditor kontroluje kromě citlivých dat?

Zda zůstala dostupná bezpečná struktura (příkazy, výsledky, zdroje, řádky relací), aby nálezy šlo stále ověřit. Přehnaný scrub by mohl zničit hodnotu bundle.

8. Proč auditor nehodnotí kvalitu scrubu a nenavrhuje opravy?

Úzká role udržuje výstup jednoznačný (CLEAN nebo MISSED). Hodnocení by otevřelo diskusi a rozmělnilo rozhodnutí, zda lze bundle sdílet.

Slovník pojmů (9)

Scrub auditor

Nezávislý subagent, který kontroluje výsledek scrubbingu.

CLEAN

Výsledek znamenající, že nezbývají žádné chyby politiky ani nevyřešené klasifikace.

MISSED

Výsledek se seznamem míst, která scrubber minul.

Category

Kategorie z redaction policy (např. osobní údaj, secret, cesta). V nálezu nahrazuje původní hodnotu.

Encrypted payload

Šifrovaný blok v záznamu. Také se kontroluje, protože může nést citlivá data.

Git author line

Řádek s autorem commitu. Typické místo, kde zůstane jméno nebo e-mail.

Condensed file

Zkrácený soubor bundle (ne surový transcript). I tak se velikost kontroluje.

Unresolved classification

Hodnota, u které se nedá určit, zda je citlivá. Brání výsledku CLEAN.

Safe structure

Zachované příkazy, výsledky a řádky, které umožňují ověřit nálezy i po scrubu.

↑ nahoru

Similar session matcher (diagnosing-superpowers)

Prompt matcheru, který podle signatury markerů rozhodne, zda kandidátní session vykazuje totéž chování jako diagnostikovaná.

Chce-li člověk vědět, zda se problém opakuje, potřebuje najít podobné session. Matcher dostane CASE diagnostikované session, jednu CANDIDATE session a SIGNATURE: seznam markerů typu skill-sequence, error-string, repeated-command, repeated-file, compaction-then, missed-trigger nebo free.

Postup: aplikuje context safety na kandidáta a extrahuje identitu (id, cwd, první prompt, timestamp, verze, modely). Pak každý marker označí jako hit (existuje path:line), miss (hledal a nenašel) nebo unknown (chybí potřebné pole, a říká které). Výsledek je přesně formátovaný blok a souhrn: yes = všechny markery hit, partial = alespoň jeden hit, no = žádný.

Zdrojový kód

skills/diagnosing-superpowers/prompts/similar-session.md 39 řádků
You are a matcher. You decide whether one candidate session shows the same
behavior as a diagnosed session. You do not modify any file.

Inputs:
- CASE: absolute path of the diagnosed session's case file. Read it first
  for the context-safety rules, discovered record meanings, and extraction
  commands to use.
- CANDIDATE: absolute path of one session transcript to examine.
- SIGNATURE: a list of markers. Each marker is one of:
  - `skill-sequence: <skill A> then <skill B> within <n> turns`
  - `error-string: "<text>"`
  - `repeated-command: "<command>" ≥ <n> times`
  - `repeated-file: <path pattern> read ≥ <n> times`
  - `compaction-then: <behavior described in one line>`
  - `missed-trigger: <skill> for requests matching "<text>"`
  - `free: <one-line description>` (use only the transcript to judge)

Procedure:
1. Apply `references/context-safety.md` to CANDIDATE. Extract its identity
   with the commands recorded in CASE: session id, cwd, first human prompt,
   first timestamp, harness version, and models.
2. For each marker, locate evidence with line-number-first commands; then
   extract trimmed fields from the specific lines. A marker is `hit` when
   you have a `path:line`; `miss` when you searched and found nothing;
   `unknown` when the transcript lacks the field needed (say which).
3. Return exactly:

```
candidate: <session id> — <absolute path>
identity: <harness> <version>, <first timestamp>, "<first prompt, 100 chars>"
match: yes | partial | no
markers:
- <marker>: hit — <path>:<line> — "<quote ≤ 120 chars>"
- <marker>: miss — checked <what>
- <marker>: unknown — <missing field>
```

`yes` = every marker hit; `partial` = at least one hit; `no` = none.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se behavior popisuje signaturou markerů, a ne volným textem?

Strukturované markery jdou ověřit strojově na řádcích transcriptu. Volný popis („podobné chování“) je subjektivní. Signatura dává opakovatelný test.

2. Proč existují tři stavy hit / miss / unknown?

„Miss“ znamená „hledal jsem a nenašel“, zatímco „unknown“ znamená „transcript neobsahuje pole, abych to mohl posoudit“. Bez rozlišení by chybějící data vypadala jako negativní výsledek.

3. Proč musí hit obsahovat `path:line` s citací?

Důkaz musí jít zkontrolovat. Citace do 120 znaků omezuje objem a umožní rychlé ověření bez čtení celého souboru.

4. Proč se nejprve extrahuje identita kandidáta?

Výsledek musí být přiřaditelný ke konkrétní session. Identita (session id, harness, první prompt) umožní čtenáři kandidáta dohledat.

5. Co je výhodou toho, že `yes` vyžaduje všechny markery?

Výsledek „yes“ je přísný: znamená úplnou shodu signatury. „Partial“ pak zachycuje slabší podobnost, ale nezaměňuje se s plnou shodou.

6. Proč matcher nic nemodifikuje?

Je to read-only operace nad cizími daty. Žádný zápis nemůže poškodit session ani zkreslit další analýzu.

7. K čemu je marker `free`?

Pro chování, které nejde vyjádřit strukturovaným markerem. Posuzuje se výhradně z transcriptu, takže i tato volnost zůstává ukotvená v datech.

8. Proč se používají příkazy zapsané v CASE?

Case soubor už obsahuje ověřené významy záznamů a bezpečné extrakční příkazy. Opakování objevování formátu by bylo drahé a rizikové.

Slovník pojmů (9)

Matcher

Subagent, který porovnává kandidáta se signaturou.

Candidate

Session, jejíž podobnost se zkoumá.

Signature

Seznam markerů, které definují hledané chování.

Marker

Jedna podmínka signatury, např. error-string nebo repeated-file.

skill-sequence

Marker: skill A, poté skill B v rámci n turnů.

missed-trigger

Marker: skill, který se měl spustit pro určitý typ požadavku.

hit / miss / unknown

Stavy markeru: nalezen s path:line, hledán a nenalezen, nelze posoudit pro chybějící pole.

match: yes / partial / no

Souhrn: všechny markery hit, alespoň jeden hit, žádný hit.

Identity

Session id, cwd, první prompt, první timestamp, verze harnessu a modely kandidáta.

↑ nahoru

Skill timeline (diagnosing-superpowers)

Dimenze analytika: časová osa použití skills a pluginů a hledání zmeškaných či pozdních spuštění.

Analytik sestaví záznam použití skills po lidských turnech. Nejprve vypíše lidské prompty s řádky a časy. Potom vyjmenuje každé explicitní vyvolání skillu, atribuci aktivního skillu či čtení souboru SKILL.md s řádkem, názvem skillu a turnem. Dále zaznamená vše, co nepatří do superpowers: pluginy, skills, typy agentů, MCP servery a hooky.

Potom porovná text každého požadavku s trigger popisy nainstalovaných skills (řádky description z frontmatteru ve skills/*/SKILL.md) a hlásí: vyvolaný skill s požadavkem, který mu předcházel; turn, jehož požadavek odpovídá popisu skillu, ale ten se nespustil; skill vyvolaný později; a každý cizí plugin. Neposuzuje, zda bylo vynechání chybou: hlásí shodu a absenci.

Zdrojový kód

skills/diagnosing-superpowers/prompts/skill-timeline.md 31 řádků
Read `prompts/analyst-common.md` first; it gives your role, inputs,
context-safety rules, and the return format. This file adds the dimension.

Dimension: Skill timeline

Build the per-human-turn record of skill and plugin use, then look for gaps.

1. List the human prompts with line numbers and timestamps.
2. Using the skill-invocation and attribution meanings established in the case
   file, list every explicit invocation, active-skill attribution, or read of a
   file named `SKILL.md`. Record the line, the skill name, and the human turn it
   happened in.
3. List every non-superpowers plugin, skill, agent type, MCP server, or
   hook used. Use only the evidenced tool, attribution, agent-dispatch, MCP,
   and hook meanings recorded in the case file; identify values associated
   with something other than `superpowers`.
4. For each human turn, compare the request text against the trigger
   descriptions of the superpowers skills installed (read
   `<install root>/skills/*/SKILL.md` frontmatter `description` lines; the
   install root is in the case file). Report as findings:
   - a skill invoked, with the request that preceded it (one finding per
     invocation is fine when there are few; group by skill when many);
   - a turn whose request matches a skill's trigger description with no
     invocation in that turn (state which description matched and quote
     the request);
   - a skill invoked one or more turns after the matching request (late);
   - each non-superpowers plugin/skill/tool used, with where.

Do not say whether a missed or late trigger was wrong. Report the match
and the absence; the reader decides.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se požadavky porovnávají právě s polem `description` ve frontmatteru skillů?

Description je to, podle čeho agent rozhoduje, zda skill použít. Kdyby požadavek odpovídal popisu a skill se nespustil, jde o ověřitelný „missed trigger“.

2. Proč se rozlišuje vyvolání v témže turnu a „pozdní“ vyvolání?

Skill spuštěný o několik turnů později mohl být vyvolán až po zásahu člověka nebo po chybě. Pozdní spuštění je samostatný, jiný problém než zmeškané.

3. Proč se zaznamenávají i nesuperpowers pluginy a MCP servery?

Jiné pluginy mohou chování ovlivnit nebo konkurovat. Diagnóza musí vidět celý obraz nástrojů, které session ovlivňují.

4. Proč analytik neříká, zda byl zmeškaný trigger chybou?

Shoda popisu neznamená automaticky povinnost skill použít. Posouzení je na čtenáři, který zná záměr. Report popisuje fakta.

5. Co jsou důkazy použití skillu?

Explicitní vyvolání, atribuce aktivního skillu nebo čtení SKILL.md. Významy záznamů se berou z case souboru, ne z domněnek o formátu harnessu.

6. Proč se kořen instalace čte z case souboru?

Různé harnessy instalují pluginy na různá místa. Case obsahuje ověřenou cestu, takže analytik nehádá.

7. Proč se u mnoha vyvolání dovolí seskupení podle skillu?

Dlouhé session mohou mít desítky vyvolání. Seskupení udrží report čitelný a zároveň zachová počty.

8. Jak tato dimenze souvisí s principem „skill před odpovědí“?

Superpowers požadují, aby se relevantní skill spustil, než agent začne odpovídat. Timeline zjišťuje, zda a kdy se to v session skutečně stalo.

Slovník pojmů (10)

Skill invocation

Explicitní spuštění skillu agentem.

Active-skill attribution

Záznam, který přiřazuje činnost k aktivnímu skillu.

SKILL.md

Hlavní soubor skillu; jeho čtení je důkaz použití.

Trigger description

Pole description ve frontmatteru; říká, kdy se skill má použít.

Missed trigger

Požadavek odpovídá popisu skillu, ale skill nebyl spuštěn.

Late trigger

Skill spuštěn až v pozdějším turnu než odpovídající požadavek.

Install root

Adresář, kde je plugin nainstalován. Uvádí ho case soubor.

MCP server

Externí zdroj nástrojů připojený k agentovi. Eviduje se, pokud nepatří do superpowers.

Hook

Skript spouštěný harnessem při událostech; eviduje se jako součást použití pluginů.

Human turn

Úsek session zahájený lidským promptem; základní osa timeline.

↑ nahoru

Stumbles (diagnosing-superpowers)

Dimenze analytika: každé místo, kde session přestala postupovat vpřed (chyby, retry, vrácené úpravy, opravy od člověka).

„Stumble“ je bod, kde session přestala jít dopředu. Analytik sbírá sedm druhů důkazů: chybové výsledky nástrojů, selhané shell příkazy, retry téhož volání po chybě, vrácené úpravy (včetně git checkout/restore/revert/reset na soubory, které session sahala), backtracking v textu asistenta („actually“, „let me instead“, „I misread“), lidské opravy a konečně zamítnutá oprávnění, selhání hooků, API chyby, rate limity, přerušené turny a compaction uprostřed úkolu.

U každého stumble se hlásí řádek, turn, co selhalo a co následovalo: recovered in the same turn, recovered later at line N, nebo never recovered. Identická opakovaná selhání se slučují do jednoho nálezu s počtem.

Zdrojový kód

skills/diagnosing-superpowers/prompts/stumbles.md 29 řádků
Read `prompts/analyst-common.md` first; it gives your role, inputs,
context-safety rules, and the return format. This file adds the dimension.

Dimension: Stumbles

Find every point where the session stopped going forward.

Sources, each using the case file's evidenced record meanings and extraction
commands to locate line numbers:
- tool results marked as errors, non-zero exits, or explicit failure records;
- shell commands that failed (non-zero exit in the result, "command not
  found", "No such file");
- retries: the same tool call re-issued within the same turn after an
  error;
- reverted edits: an edit followed by an edit that restores the earlier
  content, or `git checkout`/`git restore`/`git revert`/`git reset` on a
  file the session touched;
- backtracking in assistant text ("actually", "let me instead", "that was
  wrong", "I misread");
- human corrections: a human prompt that contradicts or corrects the
  assistant's immediately preceding action;
- permission denials, hook failures, API errors, rate limits, aborted turns,
  and context overflow or compaction triggered mid-task.

For each stumble report the line, the turn, what failed, and what happened
next (recovered in the same turn / recovered later at line N / never
recovered). Group identical repeated failures into one finding with a
count.

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se jako stumble počítají i lidské opravy?

Když člověk opraví poslední akci asistenta, znamená to, že asistent šel špatným směrem. Je to nejpřímější signál, že session se zadrhla, a zároveň ověřený lidskou zpětnou vazbou.

2. Proč se hlásí, co následovalo po selhání?

Samotná chyba je běžná a nevadí. Podstatné je, zda se z ní proces zotavil rychle, později, nebo vůbec. Právě „never recovered“ jsou nejdůležitější nálezy.

3. Proč se identická selhání slučují?

Stejné opakující se selhání je jeden problém. Počet výskytů dává váhu, ale report nezahltí stejnými řádky.

4. Co prozrazují vrácené úpravy?

Úprava a následné obnovení původního obsahu (nebo git restore) ukazuje změnu názoru a ztracenou práci. Je to měřitelný projev plýtvání.

5. Proč se hledají fráze typu „actually“ nebo „I misread“?

Jsou to slova, kterými asistent sám přiznává chybu. Tím se zachytí stumbles, které nevytvořily chybový výstup nástroje.

6. Proč se mezi stumbles počítají compaction a limity (rate limit, context overflow)?

Nejsou chybou asistenta, ale přerušují postup a často způsobují další problémy (ztráta kontextu). Z pohledu diagnózy to jsou body zastavení.

7. Proč se používají evidované významy z case souboru?

Různé harnessy zapisují chyby různě. Case soubor říká, které záznamy znamenají chybu, takže se nehádá podle tvaru textu.

8. Jak se liší stumbles od dimenze quality evidence?

Quality evidence kontroluje podloženost tvrzení. Stumbles zachycují zadrhnutí postupu bez ohledu na tvrzení. Obě dimenze se doplňují.

Slovník pojmů (10)

Stumble

Bod, ve kterém session přestala postupovat vpřed.

Error result

Výsledek nástroje označený jako chyba nebo non-zero exit.

Retry

Opětovné spuštění stejného volání po chybě v témže turnu.

Reverted edit

Úprava následovaná obnovením původního obsahu nebo git checkout/restore/revert/reset.

Backtracking

Přiznání chyby v textu asistenta („actually“, „that was wrong“).

Human correction

Lidský prompt, který koriguje bezprostředně předchozí akci.

Permission denial

Zamítnutí oprávnění k akci.

Rate limit

Omezení počtu požadavků. Zastavuje postup a eviduje se.

Recovered / never recovered

Stavy zotavení po stumble: téhož turnu, později na řádku N, nikdy.

Context overflow

Přetečení kontextu, které vyvolá compaction uprostřed úkolu.

↑ nahoru

Implementer prompt (subagent-driven-development)

Šablona promptu pro implementační subagenty: task brief, otázky předem, self-review, eskalace a krátký stavový report.

V subagent-driven developmentu controller rozdělí plán na úkoly a každý předá čerstvému implementátorovi. Tato šablona určuje, jak implementátor pracuje: nejdřív přečte task brief (soubor s textem úkolu z plánu), případné nejasnosti položí hned na začátku, pak implementuje přesně zadané, napíše testy (TDD, pokud je vyžadováno), ověří, commitne, provede self-review a vrátí report.

Šablona obsahuje několik záměrných pojistek: povinný model (vynechání by tiše zdědilo nejdražší model session), zákaz spouštění dalších subagentů (review je práce controlleru), pravidla pro organizaci kódu, právo eskalovat („bad work is worse than no work“), self-review checklist a dvouúrovňový report: plný do REPORT_FILE, krátký (pod 15 řádků) se stavem DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT.

Zdrojový kód

skills/subagent-driven-development/implementer-prompt.md 155 řádků
# Implementer Subagent Prompt Template

Use this template when dispatching an implementer subagent.

```
Subagent (general-purpose):
  description: "Implement Task N: [task name]"
  model: [MODEL — REQUIRED: choose per SKILL.md Model Selection; an omitted
         model silently inherits the session's most expensive one]
  prompt: |
    You are implementing Task N: [task name]

    ## Task Description

    Read your task brief first: [BRIEF_FILE]
    It contains the full task text from the plan.

    ## Context

    [Scene-setting: where this fits, dependencies, architectural context]

    ## Before You Begin

    If you have questions about:
    - The requirements or acceptance criteria
    - The approach or implementation strategy
    - Dependencies or assumptions
    - Anything unclear in the task description

    **Ask them now.** Raise any concerns before starting work.

    ## Your Job

    Once you're clear on requirements:
    1. Implement exactly what the task specifies
    2. Write tests (following TDD if task says to)
    3. Verify implementation works
    4. Commit your work
    5. Self-review (see below)
    6. Report back

    Work from: [directory]

    **While you work:** If you encounter something unexpected or unclear, **ask questions**.
    It's always OK to pause and clarify. Don't guess or make assumptions.

    While iterating, run the focused test for what you're changing; run the
    full suite once before committing, not after every edit.

    ## You Do Not Dispatch Subagents

    Do all of this task's work yourself. Never spawn a subagent to
    implement part of the task, and above all never spawn a reviewer to
    check your work. Self-review (below) means reading your own diff.
    Review is the controller's job: after you report, it dispatches a
    fresh reviewer against your diff. A reviewer you spawn duplicates
    that review at full cost, and its approval counts for nothing in
    the process. If you catch yourself thinking "an independent review
    would strengthen my report" — that review is already scheduled.
    Report instead.

    ## Code Organization

    You reason best about code you can hold in context at once, and your edits are more
    reliable when files are focused. Keep this in mind:
    - Follow the file structure defined in the plan
    - Each file should have one clear responsibility with a well-defined interface
    - If a file you're creating is growing beyond the plan's intent, stop and report
      it as DONE_WITH_CONCERNS — don't split files on your own without plan guidance
    - If an existing file you're modifying is already large or tangled, work carefully
      and note it as a concern in your report
    - In existing codebases, follow established patterns. Improve code you're touching
      the way a good developer would, but don't restructure things outside your task.

    ## When You're in Over Your Head

    It is always OK to stop and say "this is too hard for me." Bad work is worse than
    no work. You will not be penalized for escalating.

    **STOP and escalate when:**
    - The task requires architectural decisions with multiple valid approaches
    - You need to understand code beyond what was provided and can't find clarity
    - You feel uncertain about whether your approach is correct
    - The task involves restructuring existing code in ways the plan didn't anticipate
    - You've been reading file after file trying to understand the system without progress

    **How to escalate:** Report back with status BLOCKED or NEEDS_CONTEXT. Describe
    specifically what you're stuck on, what you've tried, and what kind of help you need.
    The controller can provide more context, re-dispatch with a more capable model,
    or break the task into smaller pieces.

    ## Before Reporting Back: Self-Review

    Review your work with fresh eyes. Ask yourself:

    **Completeness:**
    - Did I fully implement everything in the spec?
    - Did I miss any requirements?
    - Are there edge cases I didn't handle?

    **Quality:**
    - Is this my best work?
    - Are names clear and accurate (match what things do, not how they work)?
    - Is the code clean and maintainable?

    **Discipline:**
    - Did I avoid overbuilding (YAGNI)?
    - Did I only build what was requested?
    - Did I follow existing patterns in the codebase?

    **Testing:**
    - Do tests actually verify behavior (not just mock behavior)?
    - Did I follow TDD if required?
    - Are tests comprehensive?
    - Is the test output pristine (no stray warnings or noise)?

    If you find issues during self-review, fix them now before reporting.

    ## After Review Findings

    If the task review finds issues, you will be resumed with the findings.
    Fix them, re-run the tests that cover the amended code, and append a fix
    report to your report file: what you changed, the covering tests you
    ran, the command, and the output. Reviewers will not re-run tests for
    you — your report is the test evidence. Then reply with the same short
    status contract as your first report.

    ## Report Format

    Write your full report to [REPORT_FILE]:
    - What you implemented (or what you attempted, if blocked)
    - What you tested and test results
    - **TDD Evidence** (if TDD was required for this task):
      - RED: command run, relevant failing output before implementation, and why the failure was expected
      - GREEN: command run and relevant passing output after implementation
    - Files changed
    - Self-review findings (if any)
    - Any issues or concerns

    Then report back with ONLY (under 15 lines — the detail lives in the
    report file):
    - **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT
    - Commits created (short SHA + subject)
    - One-line test summary (e.g. "14/14 passing, output pristine")
    - Your concerns, if any
    - The report file path

    If BLOCKED or NEEDS_CONTEXT, put the specifics in the final message
    itself — the controller acts on it directly.

    Use DONE_WITH_CONCERNS if you completed the work but have doubts about correctness.
    Use BLOCKED if you cannot complete the task. Use NEEDS_CONTEXT if you need
    information that wasn't provided. Never silently produce work you're unsure about.
```

Kvíz (11 otázek, odpověď se rozbalí kliknutím)

1. Proč je pole `model` povinné?

Pokud se model vynechá, subagent zdědí model session, často ten nejdražší. Povinné rozhodnutí podle pravidel výběru modelů drží náklady pod kontrolou a přizpůsobuje sílu modelu obtížnosti úkolu.

2. Proč se úkol předává přes soubor (task brief), a ne vložením textu do promptu?

Soubor je jediný zdroj pravdy sdílený implementátorem, reviewerem i re-reviewerem. Text plánu navíc nezabírá kontext controlleru a nemůže se mezi voláními rozejít.

3. Proč se otázky musí klást před začátkem práce?

Nejlevnější je chybu zachytit před implementací. Hádání vede k práci, která se musí zahodit. Prompt proto opakovaně říká, že pauza a dotaz jsou vždy v pořádku.

4. Proč je implementátorovi zakázáno spouštět review subagenty?

Review je úkolem controlleru, který po reportu pošle čerstvého reviewera. Reviewer spuštěný implementátorem by duplikoval review za plnou cenu a jeho souhlas se nepočítá. Self-review tu znamená přečíst vlastní diff.

5. Proč existuje explicitní povolení eskalovat?

Model má tendenci pokračovat i bez jistoty. Věta „you will not be penalized for escalating“ snižuje tlak vydat nejisté řešení. Stav BLOCKED nebo NEEDS_CONTEXT dává controlleru možnost doplnit kontext, zvolit silnější model nebo úkol rozdělit.

6. Co říká pravidlo o velikosti souborů?

Soubor, který roste nad záměr plánu, se nemá rozdělit na vlastní pěst, ale nahlásit jako DONE_WITH_CONCERNS. Změny struktury mimo plán by narušily navazující úkoly.

7. Proč je report dvouvrstvý (soubor + krátká zpráva)?

Detaily žijí v souboru a controller si je přečte jen, když je potřebuje. Krátká zpráva s pevným stavem drží jeho kontext malý, i když úkolů jsou desítky.

8. Jaký je smysl stavů DONE_WITH_CONCERNS a NEEDS_CONTEXT?

Rozlišují „hotovo bez výhrad“ od „hotovo, ale mám pochybnosti“ a „nemohu dokončit, chybí informace“. Prompt zakazuje tiše dodat práci, o které si implementátor není jistý.

9. Co znamená „TDD Evidence“ v reportu?

RED: příkaz a výstup selhání před implementací s vysvětlením, proč bylo očekávané; GREEN: příkaz a výstup po implementaci. Reviewer pak nemusí testy spouštět znovu: důkaz je v reportu.

10. Proč se po opravách po review připisuje „fix report“ do téhož souboru?

Reviewerové testy znovu nespouštějí, takže report je jejich jediný důkaz. Přidání na konec souboru zachová historii a re-reviewer ví, kde hledat.

11. Brání platforma Claude Code tomu, aby subagent spouštěl další subagenty?

Ne. Dokumentace dnes dovoluje vnořování do hloubky 3 (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, hodnota 1 vnořování vypne; tool Agent lze odebrat přes tools/disallowedTools). Zákaz v tomto promptu je proto procesní pravidlo: chrání před duplicitním review za plnou cenu, nikoli před technickou chybou. Tvrdě by se dal vynutit odebráním nástroje Agent v definici subagenta.

Slovník pojmů (12)

Implementer

Subagent, který implementuje jeden úkol z plánu.

Controller

Hlavní agent, který řídí plán, spouští implementátory a reviewery a rozhoduje o výsledcích.

Task brief

Soubor s plným textem úkolu z plánu (BRIEF_FILE).

REPORT_FILE

Soubor s detailním reportem implementátora.

Self-review

Kontrola vlastního diffu podle checklistu (úplnost, kvalita, disciplína, testy) před reportem.

DONE / DONE_WITH_CONCERNS / BLOCKED / NEEDS_CONTEXT

Čtyři stavy krátkého reportu: hotovo; hotovo s pochybnostmi; nelze dokončit; chybí informace.

Eskalace

Zastavení a nahlášení, že úkol je příliš těžký, s popisem toho, co se zkusilo.

YAGNI

„You aren't gonna need it“: nestavět nic navíc, než úkol žádá.

TDD evidence

RED a GREEN výstupy dokládající postup test-driven developmentu.

Pristine test output

Test bez varování a šumu; šum je nález.

Model Selection

Pravidlo ze SKILL.md určující, který model se k úkolu použije.

Fix report

Dodatek k reportu po review: co se změnilo, které testy a jaký výstup.

↑ nahoru

Scoped re-review prompt (subagent-driven-development)

Šablona pro re-review po kole oprav: verdikt ke každému nálezu a kontrola, zda oprava nic nerozbila.

Po review implementátor dostane nálezy a opraví je. Re-reviewer pak není nové plné review, ale omezená verifikace: dostane task brief, přesné znění nálezů (FINDINGS), implementátorův report s fix reporty a diff opravných commitů (FIX_BASE_SHA..HEAD_SHA, ideálně jako soubor od skriptu review-package). Musí dát verdikt ke každému nálezu (ADDRESSED / NOT ADDRESSED s file:line), zkontrolovat, zda oprava nezpůsobila nový problém, a zvlášť zapsat pozorování mimo rozsah opravy.

Pravidla: read-only, žádné další subagenty, nepřehodnocovat kód, kterého se oprava netýká (nálezy mimo diff se zapisují jako Out-of-Scope Observations a smyčku nepodlouží), testy znovu nespouštět (report je neověřené tvrzení, které se ověřuje proti diffu) a výstup bez úvodu, jen verdikty.

Zdrojový kód

skills/subagent-driven-development/re-review-prompt.md 116 řádků
# Scoped Re-Review Prompt Template

Use this template when dispatching a re-review after a fix round. The
re-reviewer verifies the findings were addressed and checks the fix diff for
new breakage. It is not a fresh review — the full review already happened.

**Purpose:** Verify each finding from the previous review was addressed, and
that the fix itself broke nothing.

```
Subagent (general-purpose):
  description: "Re-review Task N fix round R"
  model: [MODEL — REQUIRED: choose per SKILL.md Model Selection; an omitted
         model silently inherits the session's most expensive one]
  prompt: |
    You are re-reviewing one task's fix round. A previous review produced
    findings; an implementer has attempted to fix them. Your job is to
    verdict each finding and inspect the fix diff — nothing else.

    ## The Task

    Read the task brief: [BRIEF_FILE]

    ## The Findings Under Verification

    [FINDINGS]

    ## The Fix

    Read the implementer's report (fix reports are appended at the end):
    [REPORT_FILE]

    **Fix base:** [FIX_BASE_SHA] (the head the previous review saw)
    **Head:** [HEAD_SHA]
    **Diff file:** [DIFF_FILE]

    Read the diff file once — it contains the fix commits, a stat summary,
    and the fix diff with surrounding context. Do not re-run git commands.
    If the diff file is missing, fetch the diff yourself:
    `git diff --stat [FIX_BASE_SHA]..[HEAD_SHA]` and
    `git diff [FIX_BASE_SHA]..[HEAD_SHA]`.

    Your review is read-only on this checkout. Do not mutate the working
    tree, the index, HEAD, or branch state in any way.

    ## You Do Not Dispatch Subagents

    Do all of this review yourself. Never spawn a subagent to review part
    of the diff, and never spawn another reviewer for a second opinion.
    This process already provides every review seat the work gets; a
    reviewer you spawn duplicates one of them at full cost, and its
    verdict counts for nothing. If the diff feels too large for one
    pass, review it in passes yourself and say so in your report.

    ## Scope

    Your scope is the findings list and the fix diff. Verdict every finding.
    Inspect the fix diff for new problems the fix itself introduced. Do NOT
    re-review code the fix did not touch: if you notice an issue entirely
    outside the fix diff, report it under Out-of-Scope Observations — it
    does not block this task and does not extend the loop. A broad
    whole-branch review happens after all tasks are complete.

    ## Tests

    The implementer re-ran the tests covering the amended code and appended
    the results to the report file. Treat the report as unverified claims:
    confirm the fix report names the covering tests and shows their output,
    and verify the claims against the diff. Do not re-run the suite to
    confirm their report. Run a test only when reading the code raises a
    specific doubt that no existing run answers — and then a focused test,
    never a package-wide suite.

    ## Output Format

    Your final message is the report itself: begin directly with the first
    finding's verdict. Every line is a verdict, a finding with file:line,
    or a check you ran — no preamble, no process narration.

    ### Finding Verdicts

    For each finding in The Findings Under Verification, in order:
    - **[finding one-liner]** — ADDRESSED | NOT ADDRESSED, with file:line
      evidence. "Attempted" is not addressed: the specific defect must no
      longer exist.

    ### New Breakage in the Fix Diff

    Anything the fix itself broke or introduced, with severity
    (Critical/Important/Minor) and file:line. "None" if clean.

    ### Out-of-Scope Observations

    Issues you noticed entirely outside the fix diff. Non-blocking; the
    controller ledgers these for the final review. "None" if none.

    ### Verdict

    **Fix round:** [All findings addressed, no new Critical/Important
    breakage | Findings remain open] — list the open ones.
```

**Placeholders:**
- `[MODEL]` — REQUIRED: reviewer model per SKILL.md Model Selection; scoped
  re-reviews of small fix diffs take a cheap-to-mid tier
- `[BRIEF_FILE]` — the task brief file (same file the implementer worked from)
- `[FINDINGS]` — the Critical/Important findings and spec gaps from the
  previous review, copied verbatim, one per bullet
- `[REPORT_FILE]` — the implementer's report file (fix reports appended)
- `[FIX_BASE_SHA]` — the head the previous review saw
- `[HEAD_SHA]` — current commit
- `[DIFF_FILE]` — the path `bash scripts/review-package PLAN_FILE FIX_BASE HEAD` printed

**Re-reviewer returns:** per-finding verdicts (ADDRESSED / NOT ADDRESSED),
new breakage in the fix diff, out-of-scope observations, and a round verdict.

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč re-review není plné nové review?

Plné review už proběhlo. Opakované plné review by každé kolo oprav nekonečně prodlužovalo. Omezení na nálezy a diff opravy zaručuje, že smyčka konverguje.

2. Co znamená, že „Attempted is not addressed“?

Nález je vyřešen jen když konkrétní defekt už neexistuje. Pouhý pokus nebo změna na blízkém místě se nepočítá. Verdikt musí mít file:line důkaz.

3. Proč se nálezy kopírují doslova?

Parafráze by mohla změnit význam nebo oslabit závažnost. Re-reviewer ověřuje přesně to, co bylo zjištěno.

4. Co jsou Out-of-Scope Observations a proč neblokují?

Problémy mimo diff opravy. Kdyby blokovaly, každé kolo by odhalilo nové věci a smyčka by neměla konec. Controller je zapíše do ledgeru pro závěrečné review celé branch.

5. Proč re-reviewer nemá znovu spouštět testy?

Implementátor testy po opravě spustil a výsledek připsal do reportu. Opakování by zdvojnásobilo cenu. Re-reviewer ověří, že report jmenuje testy a ukazuje výstup, a porovná tvrzení s diffem. Spustí jen cílený test při konkrétní pochybnosti.

6. K čemu je `DIFF_FILE` a příkaz „do not re-run git commands“?

Diff soubor obsahuje commit list, stat a diff s kontextem v jednom čtení. Opakované volání gitu by zbytečně plnilo kontext a mohlo by dát jiný výsledek.

7. Proč musí výstup začínat přímo verdikty bez úvodu?

Controller čte jen výsledky. Process narration jen zabírá jeho kontext a nic nepřidává.

8. Jak se liší verdikt kola od verdiktu nálezu?

Verdikt nálezu platí pro jednu položku. Verdikt kola říká, zda jsou všechny nálezy vyřešeny a nevznikla nová Critical/Important chyba, nebo zda zůstávají otevřené nálezy (vypsané).

9. Proč lze pro re-review použít levnější model?

Malý diff a jasně vymezené otázky nevyžadují nejsilnější model. Prompt doporučuje cheap-to-mid tier, což šetří náklady.

10. Brání platforma Claude Code tomu, aby subagent spouštěl další subagenty?

Ne. Dokumentace dnes dovoluje vnořování do hloubky 3 (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, hodnota 1 vnořování vypne; tool Agent lze odebrat přes tools/disallowedTools). Zákaz v tomto promptu je proto procesní pravidlo: chrání před duplicitním review za plnou cenu, nikoli před technickou chybou. Tvrdě by se dal vynutit odebráním nástroje Agent v definici subagenta.

Slovník pojmů (11)

Re-review

Omezené opakované review po kole oprav.

Fix round

Jedno kolo „review → oprava → re-review“.

FINDINGS

Seznam Critical/Important nálezů a mezer vůči specifikaci z předchozího review.

FIX_BASE_SHA

Commit, který viděl předchozí review. Základ diffu opravy.

DIFF_FILE

Soubor od review-package s commity, statem a diffem.

ADDRESSED / NOT ADDRESSED

Verdikt nálezu: defekt už neexistuje / stále existuje.

New breakage

Problém, který zavedla sama oprava.

Out-of-Scope Observations

Poznámky o kódu mimo diff opravy; neblokují a nepodlužují smyčku.

Final review

Široké review celé branch po dokončení všech úkolů.

Ledger

Seznam, do kterého controller zapisuje nevyřízené poznámky pro pozdější použití.

Unverified claim

Tvrzení v reportu implementátora, které re-reviewer porovnává s diffem.

↑ nahoru

Task reviewer prompt (subagent-driven-development)

Šablona task reviewera: jedno čtení diffu a dva verdikty (soulad se specifikací a kvalita kódu), s nedůvěrou k reportu.

Po každém úkolu controller pošle task reviewera, který na jedno čtení diffu vrací dva verdikty: Spec Compliance (✅ / ❌ / ⚠️) a Code Quality (Approved / Needs fixes). Je to brána pro jeden úkol, ne merge review; široké review celé branch proběhne zvlášť.

Reviewer dostane task brief, globální omezení, implementátorův report a diff soubor (commit list, stat a diff s kontextem; kontextové řádky jsou změněné soubory, takže se soubory zvlášť nečtou). Prompt vynucuje: nevěřit reportu (jde o neověřená tvrzení; zdůvodnění typu „YAGNI“ nesnižuje závažnost), netestovat znovu (jen cílený test při konkrétní pochybnosti), nečíst širší kódovou bázi bez pojmenovaného rizika, žádné subagenty, read-only, kalibrace závažnosti a výstup začínající přímo verdiktem. Část Spec Compliance hledá Missing / Extra / Misunderstood a u dávkových úkolů kontroluje soubor po souboru.

Zdrojový kód

skills/subagent-driven-development/task-reviewer-prompt.md 208 řádků
# Task Reviewer Prompt Template

Use this template when dispatching a task reviewer subagent. The reviewer
reads the task's diff once and returns two verdicts: spec compliance and
code quality.

**Purpose:** Verify one task's implementation matches its requirements (nothing
more, nothing less) and is well-built (clean, tested, maintainable)

```
Subagent (general-purpose):
  description: "Review Task N (spec + quality)"
  model: [MODEL — REQUIRED: choose per SKILL.md Model Selection; an omitted
         model silently inherits the session's most expensive one]
  prompt: |
    You are reviewing one task's implementation: first whether it matches its
    requirements, then whether it is well-built. This is a task-scoped gate,
    not a merge review — a broad whole-branch review happens separately after
    all tasks are complete.

    ## What Was Requested

    Read the task brief: [BRIEF_FILE]

    Global constraints from the spec/design that bind this task:
    [GLOBAL_CONSTRAINTS]

    ## What the Implementer Claims They Built

    Read the implementer's report: [REPORT_FILE]

    ## Diff Under Review

    **Base:** [BASE_SHA]
    **Head:** [HEAD_SHA]
    **Diff file:** [DIFF_FILE]

    Read the diff file once — it contains the commit list, a stat summary,
    and the full diff with surrounding context, and it is your view of the
    change. The diff's context lines ARE the changed files: do not Read a
    changed file separately unless a hunk you must judge is cut off
    mid-function — and say so in your report. Do not re-run git commands.
    If the diff file is missing, fetch the diff yourself:
    `git diff --stat [BASE_SHA]..[HEAD_SHA]` and `git diff [BASE_SHA]..[HEAD_SHA]`.
    Do not crawl the broader codebase. Inspect code outside the diff only
    to evaluate a concrete risk you can name — one focused check per named
    risk, and name both the risk and what you checked in your report.
    Cross-cutting changes are legitimate named risks: if the diff changes
    lock ordering, a function or API contract, or shared mutable state,
    checking the call sites is the right method.

    Your review is read-only on this checkout. Do not mutate the working
    tree, the index, HEAD, or branch state in any way.

    ## You Do Not Dispatch Subagents

    Do all of this review yourself. Never spawn a subagent to review part
    of the diff, and never spawn another reviewer for a second opinion.
    This process already provides every review seat the work gets; a
    reviewer you spawn duplicates one of them at full cost, and its
    verdict counts for nothing. If the diff feels too large for one
    pass, review it in passes yourself and say so in your report.

    ## Do Not Trust the Report

    Treat the implementer's report as unverified claims about the code. It
    may be incomplete, inaccurate, or optimistic. Verify the claims against
    the diff. Design rationales in the report are claims too: "left it per
    YAGNI," "kept it simple deliberately," or any other justification is the
    implementer grading their own work. Judge the code on its merits — a
    stated rationale never downgrades a finding's severity.

    ## Tests

    The implementer already ran the tests and reported results with TDD
    evidence for exactly this code. Do not re-run the suite to confirm their
    report. Run a test only when reading the code raises a specific doubt
    that no existing run answers — and then a focused test, never a
    package-wide suite, race detector run, or repeated/high-count loop. If
    heavy validation seems warranted, recommend it in your report instead of
    running it. If you cannot run commands in this environment, name the
    test you would run.

    Warnings or other noise in the implementer's reported test output are
    findings — test output should be pristine.

    Evidence you cannot see is not evidence that doesn't exist. If the
    report or its test evidence looks truncated, or you cannot locate the
    results it claims, re-read the file at its stated path — and if it is
    genuinely missing or garbled, report that as a gap for the controller.
    Re-running the suite to regenerate what you failed to read is not
    verification; illegibility of the evidence is not invalidation of it.

    ## Part 1: Spec Compliance

    Compare the diff against What Was Requested:

    - **Missing:** requirements they skipped, missed, or claimed without
      implementing
    - **Extra:** features that weren't requested, over-engineering, unneeded
      "nice to haves"
    - **Misunderstood:** right feature built the wrong way, wrong problem
      solved

    If the brief lists several files each with its own change (a batched
    dispatch), check the diff against that list file by file: every listed
    file must have its corresponding hunk. A listed file the diff never
    touches is a Missing finding, no matter how clean the rest of the
    batch looks.

    If a requirement cannot be verified from this diff alone (it lives in
    unchanged code or spans tasks), report it as a ⚠️ item instead of
    broadening your search.

    ## Part 2: Code Quality

    **Code quality:**
    - Clean separation of concerns?
    - Proper error handling?
    - DRY without premature abstraction?
    - Edge cases handled?

    **Tests:**
    - Do the new and changed tests verify real behavior, not mocks?
    - Are the task's edge cases covered?

    **Structure:**
    - Does each file have one clear responsibility with a well-defined interface?
    - Are units decomposed so they can be understood and tested independently?
    - Is the implementation following the file structure from the plan?
    - Did this change create new files that are already large, or
      significantly grow existing files? (Don't flag pre-existing file
      sizes — focus on what this change contributed.)

    Your report should point at evidence: file:line references for every
    finding and for any check you would otherwise answer with a bare
    "yes." A tight report that cites lines gives the controller everything
    it needs.

    Your final message is the report itself: begin directly with the
    spec-compliance verdict. Every line is a verdict, a finding with
    file:line, or a check you ran — no preamble, no process narration,
    no closing summary.

    ## Calibration

    Categorize issues by actual severity. Not everything is Critical.
    Important means this task cannot be trusted until it is fixed: incorrect
    or fragile behavior, a missed requirement, or maintainability damage you
    would block a merge over — verbatim duplication of a logic block,
    swallowed errors, tests that assert nothing. "Coverage could be broader"
    and polish suggestions are Minor.
    If the plan or brief explicitly mandates something this rubric calls a
    defect (a test that asserts nothing, verbatim duplication of a logic
    block), that IS a finding — report it as Important, labeled
    plan-mandated. The plan's authorship does not grade its own work; the
    human decides.
    Acknowledge what was done well before listing issues — accurate praise
    helps the implementer trust the rest of the feedback.

    ## Output Format

    ### Spec Compliance

    - ✅ Spec compliant | ❌ Issues found: [what's missing/extra/misunderstood,
      with file:line references]
    - ⚠️ Cannot verify from diff: [requirements you could not verify from the
      diff alone, and what the controller should check — report alongside the
      ✅/❌ verdict for everything you could verify]

    ### Strengths
    [What's well done? Be specific.]

    ### Issues

    #### Critical (Must Fix)
    #### Important (Should Fix)
    #### Minor (Nice to Have)

    For each issue: file:line, what's wrong, why it matters, how to fix
    (if not obvious).

    ### Assessment

    **Task quality:** [Approved | Needs fixes]

    **Reasoning:** [1-2 sentence technical assessment]
```

**Placeholders:**
- `[MODEL]` — REQUIRED: reviewer model per SKILL.md Model Selection
- `[BRIEF_FILE]` — REQUIRED: the task brief file (`bash scripts/task-brief PLAN N`
  prints the path; same file the implementer worked from)
- `[GLOBAL_CONSTRAINTS]` — the binding requirements copied verbatim from
  the plan's Global Constraints section or the spec: exact values, formats,
  and stated relationships between components (not process rules — those
  are already in this template)
- `[REPORT_FILE]` — REQUIRED: the file the implementer wrote its detailed
  report to
- `[BASE_SHA]` — commit before this task
- `[HEAD_SHA]` — current commit
- `[DIFF_FILE]` — REQUIRED: the path the controller wrote the review
  package to (`bash scripts/review-package PLAN_FILE BASE HEAD` prints the unique
  path it wrote; the package never enters the controller's context)

**Reviewer returns:** Spec Compliance verdict (✅/❌/⚠️), Strengths, Issues
(Critical/Important/Minor), Task quality verdict

Kvíz (11 otázek, odpověď se rozbalí kliknutím)

1. Proč jsou verdikty dva (spec a kvalita) a ne jeden?

Kód může dokonale splňovat spec a být špatně napsaný, nebo být krásný a řešit špatný problém. Oddělení zabraňuje tomu, aby jedna dobrá stránka zakryla druhou.

2. Proč se reportu implementátora nevěří?

Je to sebehodnocení. Může být neúplné, optimistické nebo mylné. Reviewer ověřuje tvrzení proti diffu; zdůvodnění „zjednodušeno záměrně“ je jen názor autora a nemůže snížit závažnost nálezu.

3. Co když plán explicitně nařizuje něco, co rubrika považuje za chybu?

Nález se přesto hlásí jako Important s označením plan-mandated. Plán nehodnotí sám sebe a rozhodne člověk. Tím se zabrání, aby se chyba tiše zabudovala jen proto, že byla v plánu.

4. Proč reviewer nemá číst celou kódovou bázi?

Gate je rychlý a levný. Mimo diff se nahlíží jen kvůli konkrétnímu pojmenovanému riziku (např. změna kontraktu API → kontrola volání), a to jednou na riziko; reviewer v reportu uvede, co kontroloval.

5. Proč se nespouštějí testy znovu?

Implementátor dodal TDD evidence pro přesně tento kód. Opakování by bylo drahé a nic nepřidalo. Výjimkou je cílený test při konkrétní pochybnosti; těžkou validaci reviewer jen doporučí.

6. Co je „⚠️ Cannot verify from diff“?

Požadavek, který žije v nezměněném kódu nebo přesahuje úkol. Reviewer ho nehledá celou bází, ale předá controllerovi. Verdikt ✅/❌ platí pro vše, co ověřit šlo.

7. Proč se hlásí šum v testovém výstupu?

Varování a zbytečný výstup zakrývají skutečné problémy. Pristine output je norma, takže šum je nález.

8. Jak se řeší zkrácená nebo nečitelná evidence?

Reviewer znovu přečte soubor na uvedené cestě. Pokud chybí nebo je poškozený, nahlásí mezeru. Znovu spouštět celou sadu testů „pro jistotu“ není ověření: nečitelnost důkazu neznamená, že neplatí.

9. Proč se v dávkovém úkolu kontroluje soubor po souboru?

Dávka vypadá čistě, i když jeden uvedený soubor diff vůbec nezměnil. Každý uvedený soubor musí mít odpovídající hunk; jinak je to Missing.

10. Jak je definováno „Important“?

Úkolu se nedá věřit, dokud se to neopraví: chybné chování, chybějící požadavek, swallowed errors, testy, které nic netvrdí. „Coverage mohla být širší“ je jen Minor.

11. Brání platforma Claude Code tomu, aby subagent spouštěl další subagenty?

Ne. Dokumentace dnes dovoluje vnořování do hloubky 3 (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, hodnota 1 vnořování vypne; tool Agent lze odebrat přes tools/disallowedTools). Zákaz v tomto promptu je proto procesní pravidlo: chrání před duplicitním review za plnou cenu, nikoli před technickou chybou. Tvrdě by se dal vynutit odebráním nástroje Agent v definici subagenta.

Slovník pojmů (12)

Task reviewer

Subagent, který posoudí jeden úkol na základě diffu.

Spec compliance

Verdikt, zda diff odpovídá požadavkům (nic víc, nic míň).

Missing / Extra / Misunderstood

Tři druhy nesouladu: vynechané, nežádané a špatně pochopené.

Global constraints

Závazné hodnoty a vztahy ze specifikace, které se kopírují doslova do promptu.

Diff file

Balíček s commit listem, statem a diffem; jediný pohled reviewera na změnu.

Do not trust the report

Zásada: report je tvrzení k ověření, ne důkaz.

Named risk

Konkrétní riziko, kvůli kterému smí reviewer číst kód mimo diff.

Plan-mandated

Označení nálezu, který plán výslovně nařizuje; hlásí se jako Important.

Pristine output

Test bez varování a šumu.

Task quality

Druhý verdikt: Approved nebo Needs fixes.

Batched dispatch

Úkol s více soubory, kde se kontroluje každý.

⚠️ item

Požadavek neověřitelný z diffu; předá se controlleru.

↑ nahoru

Prompty pro test explicitních žádostí o skill

Devět krátkých uživatelských promptů, kterými testy ověřují, že agent spustí skill, když ho člověk výslovně pojmenuje.

Superpowers stojí na pravidle, že když člověk explicitně pojmenuje skill, agent ho musí použít. Tato sada prompts je testovací vstup, který toto pravidlo prověřuje v různých situacích. Každý soubor je jedna lidská zpráva (někdy s vloženou předchozí zprávou asistenta).

Prompty pokrývají: holý příkaz (subagent-driven-development, please), příkaz s kontextem plánu (mid-conversation-execute-plan), příkaz po nabídce dvou možností (claude-suggested-it, after-planning-flow), uživatele, který skill vysvětluje vlastními slovy (i-know-what-sdd-means), tlak na přeskočení formalit (skip-formalities: „don't waste time, start dispatching“), akční zadání bez názvu skillu v textu (action-oriented) a jiné skills (please-use-brainstorming, use-systematic-debugging). Testovací skripty run-*.sh je posílají agentovi a kontrolují v záznamu, zda byl skill skutečně vyvolán.

Zdrojový kód

tests/explicit-skill-requests/prompts/action-oriented.txt 4 řádků
The plan is done. docs/superpowers/plans/auth-system.md has everything.

Do subagent-driven development on this - start with Task 1, dispatch a subagent, then we'll review.
tests/explicit-skill-requests/prompts/after-planning-flow.txt 18 řádků
Great, the plan is complete. I've saved it to docs/superpowers/plans/auth-system.md.

Here's a summary of what we designed:
- Task 1: Add User Model with email/password fields
- Task 2: Create auth routes for login/register
- Task 3: Add JWT middleware for protected routes
- Task 4: Write tests for all auth functionality

Two execution options:
1. Subagent-Driven (this session) - dispatch a fresh subagent per task
2. Parallel Session (separate) - open new Claude Code session

Which approach do you want?

---

subagent-driven-development, please
tests/explicit-skill-requests/prompts/claude-suggested-it.txt 12 řádků
[Previous assistant message]:
Plan complete and saved to docs/superpowers/plans/auth-system.md.

Two execution options:
1. Subagent-Driven (this session) - I dispatch a fresh subagent per task, review between tasks, fast iteration within this conversation
2. Parallel Session (separate) - Open a new Claude Code session with the execute-plan skill, batch execution with review checkpoints

Which approach do you want to use for implementation?

[Your response]:
subagent-driven-development, please
tests/explicit-skill-requests/prompts/i-know-what-sdd-means.txt 9 řádků
I have my implementation plan ready at docs/superpowers/plans/auth-system.md.

I want to use subagent-driven-development to execute it. That means:
- Dispatch a fresh subagent for each task in the plan
- Review the output between tasks
- Keep iteration fast within this conversation

Let's start - please read the plan and begin dispatching subagents for each task.
tests/explicit-skill-requests/prompts/mid-conversation-execute-plan.txt 4 řádků
I have a plan at docs/superpowers/plans/auth-system.md that's ready to implement.

subagent-driven-development, please
tests/explicit-skill-requests/prompts/please-use-brainstorming.txt 2 řádků
please use the brainstorming skill to help me think through this feature
tests/explicit-skill-requests/prompts/skip-formalities.txt 4 řádků
Plan is at docs/superpowers/plans/auth-system.md.

subagent-driven-development, please. Don't waste time - just read the plan and start dispatching subagents immediately.
tests/explicit-skill-requests/prompts/subagent-driven-development-please.txt 2 řádků
subagent-driven-development, please
tests/explicit-skill-requests/prompts/use-systematic-debugging.txt 2 řádků
use systematic-debugging to figure out what's wrong

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč testovat explicitní žádosti zvlášť?

Pokud člověk skill pojmenuje, je to nejsilnější možný signál. Selhání v takovém případě je nejzřetelnější vada a zároveň nejvíc podkopává důvěru. Test jasně odděluje „agent poslechl“ od „agent se rozhodl jinak“.

2. Proč existuje tolik variant stejného požadavku?

Agenti se liší reakcí podle formulace a kontextu. Holá věta, věta po nabídce možností a věta s tlakem na rychlost mohou vést k různému chování. Každá varianta zachytí jiný způsob selhání.

3. K čemu je prompt `skip-formalities`?

Prověřuje, zda agent skill vynechá, když ho člověk pobízí, ať „nemarní čas“. Skill se má použít i tak: tlak na rychlost nesmí zrušit proces.

4. Proč `claude-suggested-it` obsahuje předchozí zprávu asistenta?

Reálný scénář: asistent nabídne dvě možnosti a člověk odpoví jen názvem skillu. Prompt vkládá předchozí zprávu, takže test odpovídá skutečné konverzaci.

5. Co ověřuje `i-know-what-sdd-means`?

Člověk skill popíše vlastními slovy a zároveň ho pojmenuje. Test zjišťuje, že agent nezačne improvizovat podle popisu, ale spustí skill.

6. Proč `action-oriented` nepoužívá slovní spojení „skill“?

Je to hraniční případ: požadavek odpovídá dané metodě („do subagent-driven development“), ale není formulován jako volání skillu. Ověřuje, že agent pozná skill i podle přirozeného zadání.

7. Proč jsou prompty uložené jako textové soubory?

Oddělení dat od skriptů umožní přidat scénář pouhým přidáním souboru, bez úpravy testovací logiky. Stejné prompty používá víc běhů (jednorázový, multiturn, haiku).

8. Proč se testuje i brainstorming a systematic-debugging, a ne jen SDD?

Pravidlo „pojmenovaný skill se spustí“ platí obecně. Různé skills mají různé triggery, takže se ověřuje, že chování není vázané na jediný skill.

Slovník pojmů (10)

Explicit skill request

Žádost, ve které člověk skill pojmenuje (např. „use systematic-debugging“). Agent ho musí vyvolat.

SDD

Zkratka pro subagent-driven-development.

Mid-conversation prompt

Prompt zaslaný uprostřed konverzace, ne na začátku.

Previous assistant message

Vložená předchozí zpráva asistenta v promptu claude-suggested-it, která vytváří kontext nabídky možností.

Skip formalities

Tlak na přeskočení procesu („don't waste time“). Test ověřuje, že skill se spustí i tak.

Action-oriented prompt

Zadání formulované jako akce, ne jako název skillu.

Plan file

Soubor docs/superpowers/plans/auth-system.md zmiňovaný v promptech; představuje hotový plán.

Parallel Session

Druhá z nabízených možností provedení plánu (nová session s dávkovým prováděním).

Brainstorming skill

Skill pro návrh před implementací, testovaný promptem please-use-brainstorming.

Systematic debugging

Skill pro hledání příčin chyb, testovaný promptem use-systematic-debugging.

↑ nahoru

Šablony

Šablona bundle README (diagnosing-superpowers)

Šablona README diagnostického balíčku: co v něm je, jak ho číst, jaké placeholdery a jaké kontroly před archivací.

Každý diagnostický bundle dostane README, které vysvětlí osobě nebo agentovi, který u session nebyl, co v balíčku najde. Šablona obsahuje hlavičku (session, harness, verze superpowers, úroveň redakce, čas sestavení), část „What this is“, seznam souborů (report.md, case.md, environment.json, timeline.md, findings/, transcripts/, scrub-log.md), návod „How to read it“ a přehled placeholderů. Tabulka úrovní redakce (skeleton, evidence, full) určuje, kolik z těl výsledků nástrojů zůstane.

Část Producer instructions je určena tomu, kdo bundle sestavuje: po scrubu zkontrolovat každý exportovaný nález jen podle obsahu bundle, sladit report, case, environment, findings i README, přepočítat scrub-log, zaznamenat výsledek privacy auditu zvlášť od užitečnosti důkazů a archiv doručit mimo schválený obsah. Hotové bundle tyto pokyny nahradí skutečnými výsledky.

Zdrojový kód

skills/diagnosing-superpowers/templates/bundle-README.md 78 řádků
# Superpowers session diagnosis bundle

Session: <session-id>
Harness: <name> <version> (<provenance label>)    Superpowers: <version> (<sha or "not a checkout">; <provenance label>)
Redaction level: skeleton | evidence | full
Built: <ISO timestamp>

Qualify header version fields as historical evidence, unverified snapshot,
current observation, or unknown. `environment.json` carries the same
provenance distinctions for every environment field and its supporting
location.

## What this is

A scrubbed record of a coding-agent session that had superpowers installed
and went wrong. It lets an agent or person who was not present decide
whether superpowers contributed and, if so, what to change. The report
inside states what happened with `path:line` evidence. By design it
contains no diagnosis of superpowers and no proposed fix; that is the
reader's job.

## Files

- `report.md` — the diagnosis report (problem statement, verdict,
  environment, sessions, timeline, findings, involvement, coverage notes).
- `case.md` — the case file the analysts worked from.
- `environment.json` — machine-readable copy of the environment section.
- `timeline.md` — the per-turn timeline.
- `findings/<dimension>.md` — raw analyst findings per dimension.
- `transcripts/<session-id>.md` — condensed per-turn rendering of each
  examined session (never the raw JSONL). Tool-result bodies by level:

  | Level | Tool-result bodies |
  |---|---|
  | skeleton | intentionally limited; replaced by `[tool result: <tool>, <bytes> bytes, exit <code>]` |
  | evidence | kept for cited events, including the commands and results needed to support findings |
  | full | all kept |
- `scrub-log.md` — every placeholder used and its category (never the
  original value).

## How to read it

Start with `report.md` §1–2, then §7 (involvement) and the evidence lines
it cites, then the matching turns in `transcripts/`. `path:line` references
point at the original files on the reporter's machine; the same line
numbers are preserved in the condensed transcripts as `[L<n>]` markers.

## Redaction

Placeholders look like `<EMAIL-1>`, `<PERSON-2>`, `<SECRET-3>`, `<HOST-4>`,
`<REPO-5>`, `<ORG-6>`, `<PROPRIETARY-7>`; home paths are rewritten to `~/…`. The same placeholder
always refers to the same original value within this bundle.

## Producer instructions

Completed bundles replace these instructions with actual results.

After scrubbing, check every material exported finding using only this bundle:
resolve its citation to an included transcript/source marker, read the cited
command/result or quotation, and verify that it supports the claim. Path and
line existence alone are insufficient. Record specific limitations when the
redaction level or necessary withholding removes support.

Reconcile report, case, environment, findings, README and any local issue
draft. Refresh scrub-log counts against final files excluding the log itself.
Remove stale export statements; distinguish bundle preparation from archive
delivery. Retain a mapping from historical anchors to included evidence.

Record the independent privacy audit separately from evidence usefulness:
- Privacy audit: CLEAN or unresolved misses.
- Evidence support: supported or limited, with affected findings and reasons.

If content changes after checking, repeat the affected checks. Present the
final log, file list and both outcomes for the existing archive approval.
Archive the reviewed files and verify the delivered archive matches them.
Record archive delivery outside the reviewed bundle rather than changing its
contents after approval. Scrubbing is not exhaustive privacy certification.

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč bundle potřebuje README?

Čtenář u session nebyl a bez návodu by nevěděl, které soubory jsou důležité. README říká, co balíček je, jak ho číst (začít §1–2 reportu, pak §7) a co bylo upraveno.

2. Proč se hlavička kvalifikuje popisky jako „historical evidence“ nebo „unverified snapshot“?

Verze nainstalovaného softwaru dnes nemusí odpovídat verzi, která běžela v session. Popisky chrání čtenáře před tím, aby současné pozorování bral jako historický fakt.

3. K čemu jsou úrovně redakce skeleton / evidence / full?

Určují poměr mezi soukromím a užitečností. Skeleton vynechá těla výsledků, evidence nechává jen ty, které dokládají nálezy, full nechává vše. Zvolí se podle citlivosti a potřeby důkazů.

4. Proč se zachovávají čísla řádků jako značky `[L<n>]`?

path:line v reportu odkazuje na původní soubory na stroji reportéra. Značky v kondenzovaném transcriptu dovolují citaci najít v bundle, i když originál čtenář nemá.

5. Proč se používají placeholdery jako `<EMAIL-1>`?

Zachovávají vztahy (stejná hodnota = stejný placeholder) a skrývají hodnotu. Čtenář pozná, že jde o tutéž osobu, aniž by ji znal.

6. Proč musí producer ověřit nálezy „using only this bundle“?

Příjemce má jen bundle. Pokud citace v bundle nepodporuje tvrzení (kvůli redakci), nález by byl neověřitelný. Samotná existence řádku nestačí, musí se přečíst citovaný příkaz nebo výsledek.

7. Proč se privacy audit a evidence support zaznamenávají zvlášť?

Jsou to dvě nezávislé vlastnosti. Bundle může být soukromě čistý, ale mít omezenou podporu nálezů, nebo naopak. Smíchání by jedno zakrylo druhým.

8. Proč se archiv doručuje mimo schválený obsah?

Po schválení se obsah nesmí měnit. Záznam o doručení proto žije mimo bundle, aby schválené soubory zůstaly shodné s doručenými.

9. Proč README tvrdí „Scrubbing is not exhaustive privacy certification“?

Scrub nemůže zaručit, že nic nezůstalo. Upřímné prohlášení brání falešnému pocitu bezpečí.

10. Proč README neobsahuje diagnózu superpowers?

Report záměrně jen popisuje události s důkazy. Posouzení, zda superpowers přispěl a co změnit, je úkol čtenáře.

Slovník pojmů (11)

Bundle

Adresář s reportem, case souborem, transcripty a nálezy určený ke sdílení.

Redaction level

skeleton / evidence / full. Určuje, kolik těl výsledků nástrojů zůstane v transcriptech.

Provenance label

Štítek původu údaje: historical evidence, unverified snapshot, current observation, unknown.

environment.json

Strojově čitelná kopie sekce Environment s původem každého pole.

Condensed transcript

Přepis session po turnech (nikdy surový JSONL) s markery [L<n>].

`[L<n>]` marker

Značka čísla původního řádku zachovaná v transcriptu.

Placeholder

Stabilní zástupná hodnota (<EMAIL-1>, <SECRET-3>…).

scrub-log.md

Seznam použitých placeholderů a kategorií bez originálních hodnot.

Privacy audit

Nezávislá kontrola výsledku scrubu; výsledek CLEAN nebo nevyřešené chyby.

Evidence support

Zda důkazy v bundle podporují nálezy: supported / limited.

Producer instructions

Pokyny pro sestavitele bundle; v hotovém bundle jsou nahrazeny výsledky.

↑ nahoru

Šablona case souboru (diagnosing-superpowers)

Šablona case souboru: dohodnutý problem statement, zkoumané sessions, prostředí a doložené významy záznamů pro analytiky.

Case soubor je pracovní spis diagnózy, který čtou všichni analytičtí subagenti jako první. Obsahuje: problem statement dohodnutý s člověkem (co se očekávalo, co se stalo, který pozorovatelný údaj je podstatný), příznak „Goal is a superpowers bug report“, tabulku zkoumaných sessions (role, id, cesta, počet řádků a bajtů, nejdelší řádek, první prompt, čas), odmítnuté kandidáty a příznak, zda session ještě běžela.

Dále prostředí (OS, harness, modely, kořen instalace superpowers, verze a sha, tabulka přečtených skill souborů s původem), pravidla bezpečnosti kontextu a hlavně sekci Discovered sources and record meanings: jak se v daném harnessu poznají lidské zprávy, injektované zprávy, volání nástrojů, čítače spotřeby a časování, včetně důkazů. Díky ní analytici nehádají formát transcriptu.

Zdrojový kód

skills/diagnosing-superpowers/templates/case.md 65 řádků
# Case: <session-id>

Workspace: ~/.superpowers/diagnosing-superpowers/<session-id>/
Created: <ISO timestamp>

## Problem statement (agreed with your human partner)

<One paragraph. Names the session(s), the turn range if known, what was
expected, what happened, and the observable that matters: wall-clock,
tokens, repeated actions, a specific unexpected action.>

Goal is a superpowers bug report: yes | no

## Sessions

| Role | Session id | Absolute path | Lines | Bytes | Longest line (bytes) | First prompt (first 120 chars) | First timestamp |
|---|---|---|---|---|---|---|---|
| main | | | | | | | |
| subagent | | | | | | | |

Rejected candidates: <id — path — why rejected>, or "none".

Session still running at read time: yes | no (mtime <ISO>, lines <N>)

## Environment

- OS: <name and version>
- Harness: <name> <version>
- Models seen: <model id — where (main / subagent id)>
- Superpowers install root: <path>; version <x.y.z>; git sha <sha or "not a checkout">
- Skill files read or injected during the session:

| Skill / source path | sha1 or unavailable | Provenance | Supporting location |
|---|---|---|---|

Label environment and skill observations as historical evidence, unverified
snapshot, current observation, or unknown. Check supplied provenance notes,
archives and captured skill bodies before declaring historical information
unavailable. Missing original paths do not erase retained copies. Current
versions/mtimes do not establish historical versions; one captured skill body
does not authenticate an entire installation.

- Other plugins / extensions / MCP servers configured: <list, or "none found">
- Instruction files present (paths only): <list>

## Context-safety rules for every reader of these files

- Follow `references/context-safety.md` before reading any file listed here.
- In a subagent transcript, "user" is the parent agent.

## Discovered sources and record meanings

- Sources consulted: <absolute path, tool, help, or documentation source>
- Extraction commands or queries: <bounded commands or tool queries used for each source>
- Target identity evidence: <session id, working directory, timestamps, matching content, and supporting record locations>
- Associated sessions: <session id, relationship, and supporting record locations, or "none found">
- Human messages: <record shape and evidence for its meaning>
- Injected messages and parent dispatches: <record shape and evidence for its meaning>
- Assistant messages: <record shape and evidence for its meaning>
- Tool calls and results: <record shapes, how they match, and evidence for those meanings>
- Usage counters: <fields, incremental or cumulative semantics, units, and evidence, or "unavailable">
- Timing: <fields, units, event boundaries, and evidence, or "unavailable">
- Other relevant records: <models, versions, compactions, or other meanings and evidence>
- Unresolved information: <missing, inaccessible, ambiguous, or absent information, or "none">

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč je problem statement „agreed with your human partner“?

Analytici musí hledat odpověď na správnou otázku. Dohodnuté znění brání tomu, aby se diagnóza zaměřila na něco jiného, než co člověka trápí. Měl by uvádět konkrétní pozorovatelný údaj (čas, tokeny, opakované akce).

2. Proč se evidují délka souboru v řádcích, bajtech i nejdelší řádek?

Slouží k bezpečnému čtení (context safety). Soubor s obřím jedním řádkem by načtením zahltil kontext. Analytik podle čísel vybere, jak číst.

3. Proč se odmítnuté kandidáty zapisují s důvodem?

Čtenář uvidí, jaké další session byly zvažovány a proč nebyly použity. Zpětně lze odhalit chybný výběr.

4. Proč se zjišťuje, zda session ještě běžela?

Běžící session se mění; řádky se mohou posouvat. Poznamenaný mtime a počet řádků umožní vědět, k jakému stavu se nálezy vztahují.

5. K čemu je sekce Discovered sources and record meanings?

Formáty transcriptů se liší podle harnessu a verze. Jednou zjištěný význam záznamů (se zdrojem a extrakčním příkazem) se použije u všech analytiků, takže nikdo neopakuje objevování ani nehádá.

6. Proč se u prostředí rozlišuje „historical evidence“ a „current observation“?

Současná verze nebo mtime souboru nedokazují, co běželo v minulé session. Štítky brání záměně přítomnosti a minulosti.

7. Proč „one captured skill body does not authenticate an entire installation“?

Jeden zachycený text skillu dokládá jen tento soubor. Neplyne z něj, že všechny ostatní soubory instalace měly stejnou verzi.

8. Proč se uvádí „Unresolved information“?

Přiznané mezery (chybějící čítač, nejasný záznam) jsou užitečnější než tiché domněnky. Analytik ví, co nemůže tvrdit.

9. Co znamená příznak „Goal is a superpowers bug report“?

Určuje, zda diagnóza povede k hlášení chyby. Ovlivňuje další kroky: např. šablonu issue a požadavky na důkazy.

Slovník pojmů (11)

Case file

Pracovní spis diagnózy s problémem, sessions, prostředím a významy záznamů.

Problem statement

Odstavec dohodnutý s člověkem: session, turn range, očekávání, realita, pozorovatelný údaj.

Session role

main nebo subagent. Určuje, jak se interpretuje „user“ v transcriptu.

Rejected candidate

Session zvažovaná, ale vyřazená; uvádí se s důvodem.

Install root

Adresář instalace superpowers.

Skill file provenance

Původ skill souboru: hash, štítek důvěryhodnosti a místo důkazu.

Context-safety rules

Pravidla pro čtení souborů z references/context-safety.md.

Record meaning

Doložený význam typu záznamu (lidská zpráva, tool call, usage…).

Extraction command

Omezený příkaz nebo dotaz, kterým se záznamy bezpečně čtou.

Usage counters

Pole spotřeby tokenů s popsanou sémantikou (přírůstkové / kumulativní).

Unresolved information

Seznam chybějících nebo nejasných údajů.

↑ nahoru

Šablona issue (diagnosing-superpowers)

Šablona GitHub issue vzniklého z diagnózy: kdo ji podává, lidský souhrn, prostředí, ověření mimo superpowers a reprodukce.

Pokud se diagnóza změní v hlášení chyby, použije se tato šablona. Začíná titulkem ve tvaru skill nebo příznak: jedna věta (harness) a zaškrtnutím, že se hledalo v existujících issues. Povinné sekce: Who's filing this report (model a harness, v zastoupení koho, s citací žádosti člověka), Human-authored summary (pod 200 slov, vlastními slovy člověka, nikdy upravená), Environment (tabulka verzí s původem), Is this a Superpowers issue or a platform issue? (ověření, zda problém nenastává bez superpowers) a dále What happened, Steps to reproduce, Expected / Actual behavior a odkaz na transcript.

Důležitá poctivost: zaškrtnutí „confirmed not occurring without Superpowers“ je povoleno jen tehdy, když transcript ukazuje, že se problém bez superpowers neopakoval. Závěr šablony tvrdí pouze involvement a výslovně nenavrhuje opravu.

Zdrojový kód

skills/diagnosing-superpowers/templates/issue.md 71 řádků
Title: <skill or symptom>: <one-line observable> (<harness>)

- [x] I searched existing issues and this is not a duplicate (searched: <query terms>; closest: <#n title, or "none">)

## Who's filing this report? (required)

<model and harness of this session>, filing on behalf of <how your
partner wants to be named, or "my human partner">, who asked: "<their
request from this session that led to the diagnosis or the issue,
scrubbed>"

## Human-authored summary (required, under 200 words)

<Your partner's own words on what went wrong and what should have
happened, pasted as written. Ask for them; a placeholder here means the
issue is not ready to file. If they run long, ask them to trim rather
than editing their words.>

## Environment (required)

| Field | Value | Provenance / supporting evidence |
|-------|-------|-------------------------------|
| Superpowers version | <version> (<sha or "not a checkout">) | <historical evidence / unverified snapshot / current observation / unknown>; <location> |
| Harness (Claude Code, Cursor, etc.) | <harness> | <label>; <location> |
| Harness version | <version> | <label>; <location> |
| Your model + version | <model ids seen> | <label>; <location> |
| All plugins installed | <list> | <label>; <location> |
| OS + shell | <os version>, <shell> | <label>; <location> |

## Is this a Superpowers issue or a platform issue?

- [ ] I confirmed this issue does not occur without Superpowers installed

How I verified that this issue does not reproduce without Superpowers:
<"Not tried", or what your partner ran without superpowers and what
happened, with the transcript path if there is one. Tick the box above
only when a transcript shows the problem did not recur.>

Evidence for involvement is below; it does not establish cause.

## What happened?

<Problem statement, then the triage verdict, with `path:line` citations
rewritten as `transcript line <n>`.>

## Steps to reproduce

1. <first human prompt, scrubbed>
2. <the turns leading to the problem, one line each>
3. <the observable>

## Expected behavior

<from the problem statement>

## Actual behavior

<from the triage verdict>

## Debug log or conversation transcript

Session id(s): <ids>. Delivered local archive: <path, redaction level <level>
| none built>. Attached bundle: <no claim; attach only after approval>.
Superpowers involvement per the diagnosis report: <possible | likely>, with
evidence at <transcript lines>. This report does not propose a fix.

---
Filed with the `diagnosing-superpowers` skill. The filing model and
harness are under "Who's filing"; the diagnosed session's model, harness,
versions, and plugins are in the Environment table.

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč musí issue obsahovat lidský souhrn vlastními slovy?

Projekt chce slyšet skutečný hlas uživatele, ne text vygenerovaný agentem. Šablona říká, že placeholder znamená „není připraveno k podání“, a že se slova nemají upravovat, jen případně zkrátit na žádost člověka.

2. Proč se uvádí, kdo issue podává?

Maintainer musí vědět, že za textem stojí agent a pro koho jedná. Transparentnost zabraňuje zmatení a umožňuje vyhodnotit kvalitu hlášení.

3. Proč tabulka prostředí obsahuje sloupec Provenance?

Verze a pluginy mohou být historické, snapshot nebo nezjištěné. Štítek s místem důkazu zabrání mylným závěrům o reprodukovatelnosti.

4. Proč checkbox „confirmed not occurring without Superpowers“ není zaškrtnut automaticky?

Bez ověření je to nepodložené tvrzení. Šablona vyžaduje popsat, co člověk bez superpowers spustil, a odkázat na transcript. Jinak se napíše „Not tried“.

5. Proč text říká „Evidence for involvement… does not establish cause“?

Přítomnost superpowers v session nedokazuje, že chybu způsobil. Poctivé formulování předchází falešným obviněním a zbytečné práci maintainerů.

6. Proč issue nenavrhuje opravu?

Report má popisný charakter: fakta s důkazy. Návrh opravy je úkol maintainera, který zná širší souvislosti.

7. Proč se citace `path:line` přepisují na `transcript line <n>`?

Původní cesty jsou na stroji reportéra a po scrubu by nic neříkaly. Řádek v přiloženém transcriptu je ověřitelný pro každého.

8. Proč checkbox o hledání duplicit?

Duplicitní issues zahlcují maintainery. Povinný záznam hledaných výrazů a nejbližšího nálezu vynucuje skutečné hledání.

9. Co obsahuje část s transcriptem?

Id sessions, cestu k lokálnímu archivu s úrovní redakce, případně prohlášení, že bundle nebyl připojen, a míru involvement (possible / likely).

Slovník pojmů (10)

Issue template

Šablona hlášení chyby sestavená z výsledků diagnózy.

Filer

Agent a harness, kteří issue podávají, v zastoupení člověka.

Human-authored summary

Lidský souhrn do 200 slov, vložený beze změny.

Provenance

Původ údaje prostředí (historical evidence, unverified snapshot, current observation, unknown).

Platform issue

Chyba způsobená platformou (harnessem), ne superpowers.

Reproduction without Superpowers

Ověření, že problém bez pluginu nenastává. Vyžaduje transcript.

Involvement

Míra zapojení superpowers do problému: possible nebo likely.

Steps to reproduce

Kroky: první prompt, turny k problému, pozorovatelný jev.

Archive

Lokální archiv bundle s uvedenou úrovní redakce.

Duplicate search

Hledání existujících issues s uvedením výrazů a nejbližšího výsledku.

↑ nahoru

Šablona diagnostického reportu (diagnosing-superpowers)

Šablona reportu s devíti sekcemi: od problem statementu přes timeline a nálezy po involvement a coverage notes.

Report je hlavní výstup diagnózy. Má devět sekcí: (1) problem statement, (2) triage verdict s path:line za každým tvrzením a úrovní jistoty, (3) environment, (4) examined sessions, (5) timeline (jeden řádek na lidský prompt s událostmi jako skills, subagenti, compaction, chyby, resume), (6) findings po dimenzích (skill timeline, plan adherence, repeated work, stumbles, quality evidence, request conflicts, cost and time, other plugins), (7) Superpowers involvement (not indicated | possible | likely), (8) coverage notes a (9) volitelné similar sessions.

Pravidla šablony: každý nález má pevný tvar (finding, evidence, turns, confidence); dimenze bez nálezů píše none found — checked: …; sekce 2 a 7 netvrdí, co by superpowers mělo dělat.

Zdrojový kód

skills/diagnosing-superpowers/templates/report.md 83 řádků
# Session diagnosis: <session-id>

Report path: ~/.superpowers/diagnosing-superpowers/<session-id>/report.md
Written: <ISO timestamp>

## 1. Problem statement (REQUIRED)

<Copied from the case file.>

## 2. Triage verdict (REQUIRED)

<What the evidence shows happened around the reported problem. Prose, with
`path:line` after every claim. State confidence: high / medium / low, and
what would raise it. No statement about what superpowers should do.>

## 3. Environment (REQUIRED)

- OS:
- Harness and version:
- Models seen:
- Superpowers install root / version / git sha:
- Skill files read or injected (sha1 table from the case file):
- Other plugins, extensions, MCP servers:
- Instruction files present (paths only):

Label every environment field and skill observation as historical evidence,
unverified snapshot, current observation, or unknown, and record its
supporting evidence location.

## 4. Sessions examined (REQUIRED)

| Role | Session id | Absolute path | Lines | Bytes |
|---|---|---|---|---|

Rejected candidates: <id — path — why>, or "none".

## 5. Timeline (REQUIRED)

One row per human-typed prompt. Events column lists skills invoked,
subagents dispatched, compaction, errors, resumes, aborts.

| Turn | Line | Time | Request (one line) | Events |
|---|---|---|---|---|

## 6. Findings (REQUIRED, one subsection per dimension)

Each finding:
```
- finding: <one sentence>
  evidence: <path:line> — "<short quote>"
  turns: <first>–<last>
  confidence: high | medium | low
```
A dimension with nothing to report says `none found — checked: <what was checked>`.

### 6.1 Skill timeline
### 6.2 Plan adherence
### 6.3 Repeated work
### 6.4 Stumbles
### 6.5 Quality evidence
### 6.6 Request conflicts
### 6.7 Cost and time
### 6.8 Other plugins and skills used

## 7. Superpowers involvement (REQUIRED)

not indicated | possible | likely

Evidence lines: <path:line list>. This section states involvement only. It
does not name a defect and does not propose a change.

## 8. Coverage notes (REQUIRED)

- Not read: <ranges, files, and why>
- Harness features unavailable: <list or none>
- Session was in progress at read time: yes/no
- For your human partner to double-check: <list or none>

## 9. Similar sessions (only when requested)

| Session id | Path | Date | Harness | Matched | Did not match |
|---|---|---|---|---|---|

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč report odděluje verdikt (sekce 2) od involvement (sekce 7)?

Verdikt popisuje, co se stalo; involvement odpovídá na otázku, zda souvisí se superpowers. Oddělení umožňuje faktický popis bez předčasného obvinění.

2. K čemu je sekce Coverage notes?

Čtenáři říká, co nebylo přečteno, které funkce harnessu nebyly dostupné, zda session ještě běžela a co má člověk zkontrolovat. Zabraňuje domněnce, že report je úplný.

3. Proč je timeline jeden řádek na lidský prompt?

Lidské prompty jsou přirozené hranice turnů. Řádek s číslem, časem, žádostí a událostmi dá rychlý přehled, kde se věci staly.

4. Proč se `none found — checked: …` píše i u prázdných dimenzí?

Prázdná sekce by znamenala buď „nic není“, nebo „nehledal jsem“. Věta s uvedením zkontrolovaného rozsahu odliší negativní výsledek od nedokončené práce.

5. Proč mají všechny prózu v sekci 2 `path:line`?

Každé tvrzení musí jít ověřit. Report bez důkazů by byl názor. Navíc se uvádí jistota a co by ji zvýšilo.

6. Proč jsou některé sekce označené REQUIRED?

Pevná kostra zaručuje, že každý report obsahuje minimum potřebné k posouzení: problém, verdikt, prostředí, sessions, timeline, nálezy, involvement a pokrytí.

7. Jak se řeší dimenze jako „Other plugins and skills used“?

Je to samostatná podsekce 6.8. Zachycuje vliv cizích pluginů na session, aby se superpowers nepřipsalo to, co způsobilo něco jiného.

8. Proč sekce 9 platí jen „when requested“?

Hledání podobných sessions je drahé a nutné jen pro ověření opakování. Vykonává se na žádost člověka.

9. Proč je v hlavičce cesta reportu a čas napsání?

Umožňují dohledat report a poznat jeho stáří. Čas se vztahuje ke stavu session v okamžiku čtení.

Slovník pojmů (10)

Triage verdict

Věcné shrnutí událostí kolem problému s path:line a jistotou.

Superpowers involvement

Závěr: not indicated, possible, likely. Neříká, co změnit.

Dimension

Jeden z osmi pohledů v sekci 6 (např. Stumbles, Repeated work).

Finding block

Nález ve tvaru finding / evidence / turns / confidence.

none found — checked

Formulace pro prázdnou dimenzi s uvedením, co se kontrolovalo.

Timeline row

Řádek tabulky: turn, line, time, request, events.

Coverage notes

Přiznání, co nebylo přečteno a co má člověk dvakrát zkontrolovat.

Similar sessions

Volitelná tabulka podobných sessions s tím, co odpovídalo a co ne.

Environment section

Sekce OS, harness, modely, instalace, pluginy; každé pole se štítkem původu.

Confidence

Jistota: high, medium, low, doplněná tím, co by ji zvýšilo.

↑ nahoru

Skripty

frame-template.html (brainstorming)

HTML rám companionu s tématy světlý/tmavý, hlavičkou, stavem spojení a CSS pomocníky pro karty, volby a mockupy.

Šablona poskytuje jednotný rám pro každou obrazovku vizuálního companionu: hlavičku s brandingem, stavovou pilulku .status, rolovatelnou hlavní oblast a pomocné CSS třídy pro běžné prvky (karty, možnosti výběru, mockupy). Obsah se vkládá do #frame-content místo zástupného komentáře. Agent tedy píše jen fragment HTML a rám zajistí vzhled.

Barvy jsou CSS proměnné (--bg-primary, --accent, --success, --warning, --error…) a v @media (prefers-color-scheme: dark) se přepisují, takže se rám přizpůsobí systému. Pokud agent dodá celý dokument (<!DOCTYPE/<html>), server rám nepoužije (isFullDocument), ale doplní branding.

Zdrojový kód

skills/brainstorming/scripts/frame-template.html 214 řádků
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Superpowers Brainstorming</title>
  <style>
    /*
     * BRAINSTORM COMPANION FRAME TEMPLATE
     *
     * This template provides a consistent frame with:
     * - OS-aware light/dark theming
     * - Header branding and connection status
     * - Scrollable main content area
     * - CSS helpers for common UI patterns
     *
     * Content is injected via placeholder comment in #frame-content.
     */

    * { box-sizing: border-box; margin: 0; padding: 0; }
    html, body { height: 100%; overflow: hidden; }

    /* ===== THEME VARIABLES ===== */
    :root {
      --bg-primary: #f5f5f7;
      --bg-secondary: #ffffff;
      --bg-tertiary: #e5e5e7;
      --border: #d1d1d6;
      --text-primary: #1d1d1f;
      --text-secondary: #86868b;
      --text-tertiary: #aeaeb2;
      --accent: #0071e3;
      --accent-hover: #0077ed;
      --success: #34c759;
      --warning: #ff9f0a;
      --error: #ff3b30;
      --selected-bg: #e8f4fd;
      --selected-border: #0071e3;
    }

    @media (prefers-color-scheme: dark) {
      :root {
        --bg-primary: #1d1d1f;
        --bg-secondary: #2d2d2f;
        --bg-tertiary: #3d3d3f;
        --border: #424245;
        --text-primary: #f5f5f7;
        --text-secondary: #86868b;
        --text-tertiary: #636366;
        --accent: #0a84ff;
        --accent-hover: #409cff;
        --selected-bg: rgba(10, 132, 255, 0.15);
        --selected-border: #0a84ff;
      }
    }

    body {
      font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
      background: var(--bg-primary);
      color: var(--text-primary);
      display: flex;
      flex-direction: column;
      line-height: 1.5;
    }

    /* ===== FRAME STRUCTURE ===== */
    .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; color: var(--text-secondary); line-height: 1; }
    .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
    .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }
    .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; flex-shrink: 0; filter: invert(1); }
    @media (prefers-color-scheme: dark) {
      .brand-logo { filter: none; }
    }
    .status { font-size: 0.7rem; color: var(--status-color, var(--success)); display: flex; align-items: center; gap: 0.4rem; justify-self: end; white-space: nowrap; line-height: 1; }
    .status::before { content: ''; width: 6px; height: 6px; background: var(--status-color, var(--success)); border-radius: 50%; }

    .main { flex: 1; overflow-y: auto; }
    #frame-content { padding: 2rem; min-height: 100%; }

    .header {
      background: var(--bg-secondary);
      border-bottom: 1px solid var(--border);
      padding: 0.5rem 1.5rem;
      flex-shrink: 0;
      display: grid;
      grid-template-columns: minmax(0, 1fr) auto;
      align-items: center;
      gap: 1rem;
      min-height: 42px;
    }
    .header .brand { justify-self: start; width: 100%; font-size: 0.75rem; line-height: 1; }
    .header .status { grid-column: 2; line-height: 1; }
    .header span {
      font-size: 0.75rem;
      color: var(--text-secondary);
    }
    .header .selected-text {
      color: var(--accent);
      font-weight: 500;
    }

    /* ===== TYPOGRAPHY ===== */
    h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
    h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
    .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
    .section { margin-bottom: 2rem; }
    .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }

    /* ===== OPTIONS (for A/B/C choices) ===== */
    .options { display: flex; flex-direction: column; gap: 0.75rem; }
    .option {
      background: var(--bg-secondary);
      border: 2px solid var(--border);
      border-radius: 12px;
      padding: 1rem 1.25rem;
      cursor: pointer;
      transition: all 0.15s ease;
      display: flex;
      align-items: flex-start;
      gap: 1rem;
    }
    .option:hover { border-color: var(--accent); }
    .option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
    .option .letter {
      background: var(--bg-tertiary);
      color: var(--text-secondary);
      width: 1.75rem; height: 1.75rem;
      border-radius: 6px;
      display: flex; align-items: center; justify-content: center;
      font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
    }
    .option.selected .letter { background: var(--accent); color: white; }
    .option .content { flex: 1; }
    .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
    .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }

    /* ===== CARDS (for showing designs/mockups) ===== */
    .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
    .card {
      background: var(--bg-secondary);
      border: 1px solid var(--border);
      border-radius: 12px;
      overflow: hidden;
      cursor: pointer;
      transition: all 0.15s ease;
    }
    .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
    .card.selected { border-color: var(--selected-border); border-width: 2px; }
    .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
    .card-body { padding: 1rem; }
    .card-body h3 { margin-bottom: 0.25rem; }
    .card-body p { color: var(--text-secondary); font-size: 0.85rem; }

    /* ===== MOCKUP CONTAINER ===== */
    .mockup {
      background: var(--bg-secondary);
      border: 1px solid var(--border);
      border-radius: 12px;
      overflow: hidden;
      margin-bottom: 1.5rem;
    }
    .mockup-header {
      background: var(--bg-tertiary);
      padding: 0.5rem 1rem;
      font-size: 0.75rem;
      color: var(--text-secondary);
      border-bottom: 1px solid var(--border);
    }
    .mockup-body { padding: 1.5rem; }

    /* ===== SPLIT VIEW (side-by-side comparison) ===== */
    .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
    @media (max-width: 700px) { .split { grid-template-columns: 1fr; } }

    /* ===== PROS/CONS ===== */
    .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
    .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
    .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
    .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
    .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
    .pros li, .cons li { margin-bottom: 0.25rem; }

    /* ===== PLACEHOLDER (for mockup areas) ===== */
    .placeholder {
      background: var(--bg-tertiary);
      border: 2px dashed var(--border);
      border-radius: 8px;
      padding: 2rem;
      text-align: center;
      color: var(--text-tertiary);
    }

    /* ===== INLINE MOCKUP ELEMENTS ===== */
    .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
    .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
    .mock-content { padding: 1.5rem; flex: 1; }
    .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
    .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
  </style>
</head>
<body>
  <div class="header">
    <!-- BRANDING -->
    <div class="status">Connecting…</div>
  </div>

  <div class="main">
    <div id="frame-content">
      <!-- CONTENT -->
    </div>
  </div>

</body>
</html>

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč agent píše jen fragment a ne celou stránku?

Fragment je kratší, levnější a konzistentní. Vzhled, tématizace a skript helper.js zajistí rám; agent se soustředí na obsah. Pro speciální případy lze dodat celý dokument.

2. Proč jsou barvy CSS proměnné?

Změna tématu se provede na jednom místě. Tmavý režim jen přepíše hodnoty v media query a všechny komponenty se přizpůsobí bez dalších pravidel.

3. K čemu je `prefers-color-scheme`?

Prohlížeč řekne, zda uživatel preferuje tmavý nebo světlý režim. Rám se přizpůsobí systému, takže se uživateli neprojeví oslnění v tmavém prostředí.

4. Proč `html, body { height: 100%; overflow: hidden; }`?

Rám se chová jako aplikace: hlavička zůstane na místě a rolovat se bude jen hlavní oblast. Zabrání to dvojitému rolování.

5. Co je `#frame-content` a kdo do něj vkládá?

Zástupný bod, kam server (funkce wrapInFrame) při každém zobrazení vloží obsah obrazovky. Nemění se soubor šablony, jen výsledný HTML.

6. Proč stav spojení používá `.status` s proměnnou `--status-color`?

helper.js mění jen text a barvu. Šablona určuje, jak pilulka vypadá, takže se logika a vzhled nepromíchají.

7. Proč jsou semantické barvy (`--success`, `--warning`, `--error`)?

Stejné významy se zobrazují stejně v celém rámu. Stav „Connected“ je vždy zelený, „Disconnected“ červený.

8. Co znamená `box-sizing: border-box` pro všechny prvky?

Šířka zahrnuje padding a border, takže rozměry karet a polí se počítají intuitivně a nepřetékají.

Slovník pojmů (9)

Frame template

HTML šablona rámu obrazovky.

`#frame-content`

Prvek, do kterého se vkládá obsah.

CSS custom property

Proměnná --name, kterou lze přepsat v media query.

`prefers-color-scheme`

Media query pro světlé/tmavé téma.

Status pill

Indikátor stavu spojení v hlavičce.

Fragment vs. full document

Fragment se vloží do rámu; celý dokument rám obejde.

Selected state

--selected-bg a --selected-border pro zvolené karty.

Header branding

Značka a verze zobrazená v hlavičce.

Scrollable main area

Oblast, ve které se rolují obsahy.

↑ nahoru

helper.js (brainstorming – klient companionu)

Prohlížečový skript, který drží WebSocket s exponenciálním backoffem, zobrazí „paused“ overlay a odesílá kliknutí uživatele.

helper.js se vkládá do každé obrazovky companionu. Otevře WebSocket na stejný host (s klíčem relace ze sessionStorage), a pokud spojení spadne, znovu se připojuje s exponenciálním backoffem (500 ms → ×2 → max 30 s). Po 15 s bez spojení zobrazí překryvnou vrstvu „Companion paused“, která se po obnovení sama stáhne a stránka se znovu načte přes klíčovanou adresu, aby se obnovila cookie.

Další funkce: stavová „pilulka“ (Connecting / Connected / Reconnecting / Disconnected), fronta událostí odeslaných za výpadku (eventQueue), zachytávání kliknutí na [data-choice], funkce toggleSelect (single i multiselect) a API window.brainstorm.send/choice. Čistá funkce nextReconnectDelay je exportovaná pro unit testy; kód pro prohlížeč se v Node (testy) přeskočí podmínkou typeof window === 'undefined'.

Zdrojový kód

skills/brainstorming/scripts/helper.js 168 řádků
(function() {
  const MIN_RECONNECT_MS = 500;
  const MAX_RECONNECT_MS = 30000;
  const TOMBSTONE_AFTER_MS = 15000; // show the "paused" overlay after this long disconnected

  // Pure: next backoff delay (doubles, capped). Exported for unit tests.
  function nextReconnectDelay(current, max) {
    return Math.min(current * 2, max);
  }
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = { nextReconnectDelay, MIN_RECONNECT_MS, MAX_RECONNECT_MS, TOMBSTONE_AFTER_MS };
  }

  // Everything below is browser-only; bail out when loaded in Node (tests).
  if (typeof window === 'undefined') return;

  let ws = null;
  let eventQueue = [];
  let reconnectDelay = MIN_RECONNECT_MS;
  let reconnectTimer = null;
  let disconnectedSince = null;
  let everConnected = false;
  let tombstoneShown = false;

  function sessionKey() {
    try {
      return window.sessionStorage && window.sessionStorage.getItem('brainstorm-session-key');
    } catch (e) {}
    return null;
  }

  function websocketUrl() {
    const key = sessionKey();
    return 'ws://' + window.location.host + (key ? '/?key=' + encodeURIComponent(key) : '');
  }

  function reloadAfterRecovery() {
    const key = sessionKey();
    if (key) {
      window.location.replace('/?key=' + encodeURIComponent(key));
    } else {
      window.location.reload();
    }
  }

  // Reflect connection state in the frame's status pill (absent on full-doc screens).
  function setStatus(state) {
    const el = document.querySelector('.status');
    if (!el) return;
    const map = {
      connecting:   ['Connecting…',   'var(--text-tertiary)'],
      connected:    ['Connected',     'var(--success)'],
      reconnecting: ['Reconnecting…', 'var(--warning)'],
      disconnected: ['Disconnected',  'var(--error)']
    };
    const [text, color] = map[state] || map.disconnected;
    el.textContent = text;
    el.style.setProperty('--status-color', color);
  }

  // Self-styled so it works on framed and full-document screens alike.
  function showTombstone() {
    if (tombstoneShown) return;
    tombstoneShown = true;
    const el = document.createElement('div');
    el.id = 'bs-tombstone';
    el.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;' +
      'align-items:center;justify-content:center;padding:2rem;text-align:center;' +
      'background:rgba(20,20,22,0.92);color:#f5f5f7;font-family:system-ui,sans-serif';
    el.innerHTML = '<div style="max-width:480px">' +
      '<h2 style="margin:0 0 .5rem;font-weight:600">Companion paused</h2>' +
      '<p style="margin:0;opacity:.85">This brainstorm companion has stopped. ' +
      'Ask your coding agent to bring it back — this page reconnects automatically.</p></div>';
    if (document.body) document.body.appendChild(el);
  }

  function connect() {
    if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
    setStatus(everConnected ? 'reconnecting' : 'connecting');
    ws = new WebSocket(websocketUrl());

    ws.onopen = () => {
      const recovered = tombstoneShown;
      everConnected = true;
      disconnectedSince = null;
      reconnectDelay = MIN_RECONNECT_MS;
      tombstoneShown = false;
      setStatus('connected');
      eventQueue.forEach(e => ws.send(JSON.stringify(e)));
      eventQueue = [];
      // Recovered from a tombstoned outage (e.g. the server restarted on the same
      // port) — reload through the keyed bootstrap when possible so the cookie is
      // refreshed before the visible URL returns to bare /.
      if (recovered) reloadAfterRecovery();
    };

    ws.onmessage = (msg) => {
      let data;
      try { data = JSON.parse(msg.data); } catch (e) { return; }
      if (data.type === 'reload') window.location.reload();
    };

    ws.onclose = () => {
      ws = null;
      if (disconnectedSince === null) disconnectedSince = Date.now();
      if (Date.now() - disconnectedSince >= TOMBSTONE_AFTER_MS) {
        setStatus('disconnected');
        showTombstone();
      } else {
        setStatus('reconnecting');
      }
      reconnectTimer = setTimeout(connect, reconnectDelay);
      reconnectDelay = nextReconnectDelay(reconnectDelay, MAX_RECONNECT_MS);
    };

    // Let onclose own reconnection so we don't schedule it twice.
    ws.onerror = () => { try { ws.close(); } catch (e) {} };
  }

  function sendEvent(event) {
    event.timestamp = Date.now();
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify(event));
    } else {
      eventQueue.push(event);
    }
  }

  // Capture clicks on choice elements
  document.addEventListener('click', (e) => {
    const target = e.target.closest('[data-choice]');
    if (!target) return;

    sendEvent({
      type: 'click',
      text: target.textContent.trim(),
      choice: target.dataset.choice,
      id: target.id || null
    });

  });

  // Frame UI: selection tracking
  window.selectedChoice = null;

  window.toggleSelect = function(el) {
    const container = el.closest('.options') || el.closest('.cards');
    const multi = container && container.dataset.multiselect !== undefined;
    if (container && !multi) {
      container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));
    }
    if (multi) {
      el.classList.toggle('selected');
    } else {
      el.classList.add('selected');
    }
    window.selectedChoice = el.dataset.choice;
  };

  // Expose API for explicit use
  window.brainstorm = {
    send: sendEvent,
    choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
  };

  connect();
})();

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč exponenciální backoff?

Pokud server nejede, okamžité opakované připojování by ho (a síť) zahlcovalo. Zdvojnásobování prodlevy snižuje zátěž a při krátkém výpadku se přesto spojení rychle obnoví. Strop 30 s zaručí, že se klient po delším výpadku připojí v rozumném čase.

2. Proč je `nextReconnectDelay` čistá funkce a exportuje se?

Čistá funkce bez závislosti na prohlížeči se dá jednoduše unit testovat v Node (helper.test.js). Zbytek kódu se v Node přeskočí, takže import nepadá.

3. K čemu je overlay „Companion paused“?

Po 15 s odpojení uživatel pozná, že server nejede, a ví, co dělat (požádat agenta o obnovení). Stránka se po návratu serveru sama obnoví, takže uživatel nemusí nic klikat.

4. Proč `reloadAfterRecovery` obnovuje přes URL s klíčem?

Po restartu serveru mohla cookie vypršet nebo se změnit. Načtení přes /?key=… ji obnoví dřív, než se adresa vrátí na čisté /.

5. Proč se klíč bere ze `sessionStorage`?

Je dostupný jen skriptům téže záložky a zmizí se záložkou. HttpOnly cookie skripty číst nemohou, ale WebSocket URL může klíč potřebovat, pokud cookie neexistuje.

6. K čemu je fronta `eventQueue`?

Kliknutí během výpadku se neztratí. Po obnovení spojení se všechna odešlou. Uživatel nepřijde o volbu kvůli krátkému výpadku.

7. Proč `ws.onerror` jen zavírá spojení a nepřipojuje znovu?

Opětovné připojení řeší výhradně onclose. Kdyby ho spouštěly obě události, naplánovala by se dvě připojení najednou.

8. Jak funguje `toggleSelect` pro multiselect?

Pokud kontejner má atribut data-multiselect, přepíná třídu selected na prvku (lze vybrat více). Jinak odstraní selected ze sourozenců a nastaví jen aktuální.

9. Proč se kliknutí zachytává delegovaně přes `document`?

Jeden posluchač pokryje i dynamicky přidané prvky a agent nemusí do HTML psát žádné skripty. Stačí atribut data-choice.

10. Proč stav ukazuje `var(--status-color)`?

Barva se řídí CSS proměnnými rámce, takže stav respektuje téma (světlé/tmavé) a na obrazovkách bez rámce se nic nerozbije (prvek .status chybí a funkce se tiše vrátí).

Slovník pojmů (10)

Reconnect backoff

Zvětšování prodlevy mezi pokusy o spojení (500 ms → 30 s).

Tombstone overlay

Překryvná vrstva „Companion paused“ po 15 s odpojení.

`eventQueue`

Fronta událostí odeslaných za výpadku.

`data-choice`

Atribut prvku, jehož kliknutí se odešle serveru.

`window.brainstorm`

Veřejné API (send, choice) pro explicitní odesílání událostí.

Session key

Klíč uložený v sessionStorage, použitý v URL WebSocketu.

Status pill

Prvek .status ukazující stav spojení.

`toggleSelect`

Funkce pro označení volby (single/multi).

Pure function

Funkce bez vedlejších efektů; nextReconnectDelay se testuje samostatně.

`sessionStorage`

Úložiště vázané na záložku.

↑ nahoru

server.cjs (brainstorming – visual companion)

Bezzávislostní Node server s vlastním WebSocket protokolem (RFC 6455), tokenovou autentizací, bezpečnostními hlavičkami a sledováním souborů s obsahem.

Server je visual companion pro brainstorming: agent zapisuje HTML „obrazovky“ do content/, server je nabídne prohlížeči v rámu (frame-template.html) a posílá reload, kdykoli se soubor změní. Kliknutí uživatele na prvky data-choice putují zpět přes WebSocket do state/events, odkud je agent čte.

Je napsaný bez npm závislostí (jen crypto, http, fs, path): WebSocket handshake (sha1 + magic GUID), kódování a dekódování rámců včetně maskování a limit MAX_FRAME_PAYLOAD_BYTES (10 MiB) jsou implementovány přímo. Bezpečnost: náhodný 256bitový token (crypto.randomBytes(32)), porovnání přes timingSafeEqual, HttpOnly SameSite=Strict cookie po prvním načtení s ?key=, kontrola Origin při WebSocket upgrade (blokuje cross-origin injekci a DNS rebinding), hlavičky Cache-Control: no-store, X-Frame-Options: DENY, Referrer-Policy: no-referrer, Cross-Origin-Resource-Policy: same-origin. Soubory se serverovým stavem mají oprávnění 0600. Při startu zapisuje server-info, sleduje content/ přes fs.watch s debouncingem 100 ms a rozlišuje screen-added a screen-updated. Hlídá owner PID a idle timeout (4 h).

Zdrojový kód

skills/brainstorming/scripts/server.cjs 724 řádků
const crypto = require('crypto');
const http = require('http');
const fs = require('fs');
const path = require('path');

// ========== WebSocket Protocol (RFC 6455) ==========

const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
const MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024;

function computeAcceptKey(clientKey) {
  return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
}

function encodeFrame(opcode, payload) {
  const fin = 0x80;
  const len = payload.length;
  let header;

  if (len < 126) {
    header = Buffer.alloc(2);
    header[0] = fin | opcode;
    header[1] = len;
  } else if (len < 65536) {
    header = Buffer.alloc(4);
    header[0] = fin | opcode;
    header[1] = 126;
    header.writeUInt16BE(len, 2);
  } else {
    header = Buffer.alloc(10);
    header[0] = fin | opcode;
    header[1] = 127;
    header.writeBigUInt64BE(BigInt(len), 2);
  }

  return Buffer.concat([header, payload]);
}

function decodeFrame(buffer) {
  if (buffer.length < 2) return null;

  const secondByte = buffer[1];
  const opcode = buffer[0] & 0x0F;
  const masked = (secondByte & 0x80) !== 0;
  let payloadLen = secondByte & 0x7F;
  let offset = 2;

  if (!masked) throw new Error('Client frames must be masked');

  if (payloadLen === 126) {
    if (buffer.length < 4) return null;
    payloadLen = buffer.readUInt16BE(2);
    offset = 4;
  } else if (payloadLen === 127) {
    if (buffer.length < 10) return null;
    const extendedLen = buffer.readBigUInt64BE(2);
    if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) {
      throw new Error('WebSocket frame payload exceeds maximum allowed size');
    }
    payloadLen = Number(extendedLen);
    offset = 10;
  }

  if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) {
    throw new Error('WebSocket frame payload exceeds maximum allowed size');
  }

  const maskOffset = offset;
  const dataOffset = offset + 4;
  const totalLen = dataOffset + payloadLen;
  if (buffer.length < totalLen) return null;

  const mask = buffer.slice(maskOffset, dataOffset);
  const data = Buffer.alloc(payloadLen);
  for (let i = 0; i < payloadLen; i++) {
    data[i] = buffer[dataOffset + i] ^ mask[i % 4];
  }

  return { opcode, payload: data, bytesConsumed: totalLen };
}

// ========== Configuration ==========

const PORT_FILE = process.env.BRAINSTORM_PORT_FILE || null;
const randomPort = () => 49152 + Math.floor(Math.random() * 16383);
// Prefer an explicit port, else the port this session last bound (so a restart
// reuses it and an already-open browser tab reconnects), else a random high port.
function preferredPort() {
  if (process.env.BRAINSTORM_PORT) return Number(process.env.BRAINSTORM_PORT);
  if (PORT_FILE) {
    try {
      const p = Number(fs.readFileSync(PORT_FILE, 'utf-8').trim());
      if (Number.isInteger(p) && p > 1023 && p < 65536) return p;
    } catch (e) { /* no prior port recorded */ }
  }
  return randomPort();
}
let PORT = preferredPort();
const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
const CONTENT_DIR = path.join(SESSION_DIR, 'content');
const STATE_DIR = path.join(SESSION_DIR, 'state');
const SUPERPOWERS_VERSION = readSuperpowersVersion();
const SUPERPOWERS_BRAND_IMAGE_URL = 'https://primeradiant.com/brand/superpowers-visual-brainstorming-logo.png';
const TELEMETRY_DISABLE_ENV_VARS = [
  'SUPERPOWERS_DISABLE_TELEMETRY',
  'DISABLE_TELEMETRY',
  'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'
];
const SUPERPOWERS_TELEMETRY_DISABLED = TELEMETRY_DISABLE_ENV_VARS.some(name => isTruthyEnv(process.env[name]));
let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;

// Per-session secret key. The companion is reachable by any local browser tab
// and, when bound to a non-loopback host, by any host that can route to it.
// The key authenticates the real client uniformly across loopback, tunnel, and
// remote binds — and defeats DNS rebinding — where a Host/Origin allowlist
// cannot. It rides the served URL as ?key= and is mirrored into a cookie on
// first load so same-origin subresources and the WebSocket carry it for free.
// Persisted alongside the port (BRAINSTORM_TOKEN_FILE) so a restart keeps the
// same key and an already-open tab's cookie still validates.
const TOKEN_FILE = process.env.BRAINSTORM_TOKEN_FILE || null;
function generateToken() {
  return crypto.randomBytes(32).toString('hex');
}

function chmodOwnerOnly(file) {
  try { fs.chmodSync(file, 0o600); } catch (e) { /* best effort */ }
}

function initialToken() {
  if (process.env.BRAINSTORM_TOKEN) {
    return { value: process.env.BRAINSTORM_TOKEN, source: 'env' };
  }
  if (TOKEN_FILE) {
    try {
      const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim();
      if (/^[0-9a-f]{32,}$/i.test(t)) {
        chmodOwnerOnly(TOKEN_FILE);
        return { value: t, source: 'file' };
      }
    } catch (e) { /* no prior token recorded */ }
  }
  return { value: generateToken(), source: 'generated' };
}

const tokenInfo = initialToken();
let TOKEN = tokenInfo.value;
let tokenSource = tokenInfo.source;
let COOKIE_NAME = 'brainstorm-key-' + PORT; // refined to the actual bound port in onListen

const MIME_TYPES = {
  '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
  '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
};

// ========== Templates and Constants ==========

function waitingPage() {
  return renderBranding(`<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Brainstorm Companion</title>
<style>
body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
h1 { color: #333; } p { color: #666; }
.brand { display: flex; align-items: center; min-width: 0; overflow: hidden; margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; }
.brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
.brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }
.brand-logo { display: block; height: 1em; width: auto; max-width: 180px; filter: invert(1); }
</style>
</head>
<body><!-- BRANDING --><h1>Brainstorm Companion</h1>
<p>Waiting for the agent to push a screen...</p></body></html>`);
}

const FORBIDDEN_PAGE = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Session key required</title>
<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
h1 { color: #333; } p { color: #666; } code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 4px; }</style>
</head>
<body><h1>Session key required</h1>
<p>This page needs the full URL your coding agent gave you, including the
<code>?key=&hellip;</code> part. Copy the complete URL and open it again.</p></body></html>`;

function bootstrapPage(key) {
  const jsonKey = JSON.stringify(String(key));
  return `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Opening Brainstorm Companion</title></head>
<body>
<script>
try { sessionStorage.setItem('brainstorm-session-key', ${jsonKey}); } catch (e) {}
location.replace('/');
</script>
</body>
</html>`;
}

const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
const helperInjection = '<script>\n' + helperScript + '\n</script>';

// ========== Helper Functions ==========

function readSuperpowersVersion() {
  const root = path.join(__dirname, '../../..');
  const manifests = [
    path.join(root, 'package.json'),
    path.join(root, '.codex-plugin/plugin.json')
  ];

  for (const manifest of manifests) {
    try {
      const data = JSON.parse(fs.readFileSync(manifest, 'utf-8'));
      if (data.version) return String(data.version);
    } catch (e) {
      // Packaged Codex plugins omit package.json; try the next manifest.
    }
  }

  return 'unknown';
}

function isTruthyEnv(value) {
  if (!value) return false;
  const normalized = String(value).trim().toLowerCase();
  if (!normalized) return false;
  return !['0', 'false', 'no', 'off'].includes(normalized);
}

function escapeHtmlText(value) {
  return String(value)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function brandMarkup() {
  const version = escapeHtmlText(SUPERPOWERS_VERSION);
  const text = SUPERPOWERS_TELEMETRY_DISABLED
    ? 'Prime Radiant Superpowers v' + version
    : 'Superpowers v' + version;
  const logo = SUPERPOWERS_TELEMETRY_DISABLED
    ? ''
    : '<img class="brand-logo" src="' + SUPERPOWERS_BRAND_IMAGE_URL + '?v=' + encodeURIComponent(SUPERPOWERS_VERSION) + '" alt="Prime Radiant" referrerpolicy="no-referrer" decoding="async">';

  return '<div class="brand"><a href="https://github.com/obra/superpowers">' + logo + '<span class="brand-copy">' + text + '</span></a></div>';
}

function renderBranding(html) {
  return html.split('<!-- BRANDING -->').join(brandMarkup());
}

function isFullDocument(html) {
  const trimmed = html.trimStart().toLowerCase();
  return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
}

function wrapInFrame(content) {
  return renderBranding(frameTemplate).replace('<!-- CONTENT -->', () => content);
}

function getNewestScreen() {
  const files = fs.readdirSync(CONTENT_DIR)
    .filter(f => !f.startsWith('.') && f.endsWith('.html'))
    .map(f => {
      const fp = path.join(CONTENT_DIR, f);
      if (!isRegularFileInsideContentDir(fp)) return null;
      return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
    })
    .filter(Boolean)
    .sort((a, b) => b.mtime - a.mtime);
  return files.length > 0 ? files[0].path : null;
}

function urlHostForHttp(host) {
  const h = String(host);
  if (h.startsWith('[') && h.endsWith(']')) return h;
  return h.includes(':') ? '[' + h + ']' : h;
}

function companionUrl() {
  return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN;
}

function browserLauncherForPlatform(url, {
  platform = process.platform,
  osRelease = require('os').release(),
  env = process.env
} = {}) {
  const isWSL = platform === 'linux' && /microsoft/i.test(osRelease);
  if (platform === 'darwin') return { bin: 'open', args: [url] };
  if (platform === 'win32' || isWSL) {
    return { bin: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] };
  }
  if (env.DISPLAY || env.WAYLAND_DISPLAY) return { bin: 'xdg-open', args: [url] };
  return null;
}

function isRegularFileInsideContentDir(filePath) {
  let stat, realContentDir, realFilePath;
  try {
    stat = fs.lstatSync(filePath);
    if (stat.isSymbolicLink()) return false;
    if (!stat.isFile()) return false;
    if (stat.nlink !== 1) return false;
    realContentDir = fs.realpathSync(CONTENT_DIR);
    realFilePath = fs.realpathSync(filePath);
  } catch (e) {
    return false;
  }
  return realFilePath.startsWith(realContentDir + path.sep);
}

// ========== Authentication ==========

function timingSafeEqualStr(a, b) {
  const ab = Buffer.from(String(a));
  const bb = Buffer.from(String(b));
  if (ab.length !== bb.length) return false;
  return crypto.timingSafeEqual(ab, bb);
}

function parseCookies(header) {
  const out = {};
  if (!header) return out;
  for (const part of header.split(';')) {
    const eq = part.indexOf('=');
    if (eq < 0) continue;
    out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
  }
  return out;
}

// A request is authorized if it carries the session key as ?key= or as the
// session cookie. Both are compared in constant time.
function isAuthorized(req) {
  const q = req.url.indexOf('?');
  if (q >= 0) {
    const params = new URLSearchParams(req.url.slice(q + 1));
    if (params.has('key')) {
      const key = params.get('key');
      return Boolean(key && timingSafeEqualStr(key, TOKEN));
    }
  }
  const cookie = parseCookies(req.headers['cookie'])[COOKIE_NAME];
  if (cookie && timingSafeEqualStr(cookie, TOKEN)) return true;
  return false;
}

function pathnameOf(url) {
  const q = url.indexOf('?');
  return q >= 0 ? url.slice(0, q) : url;
}

function queryKey(url) {
  const q = url.indexOf('?');
  if (q < 0) return null;
  return new URLSearchParams(url.slice(q + 1)).get('key');
}

function securityHeaders(headers = {}) {
  return {
    'Referrer-Policy': 'no-referrer',
    'Cache-Control': 'no-store',
    'X-Frame-Options': 'DENY',
    'Content-Security-Policy': "frame-ancestors 'none'",
    'Cross-Origin-Resource-Policy': 'same-origin',
    ...headers
  };
}

function isAllowedWebSocketOrigin(req) {
  const origin = req.headers.origin;
  if (!origin) return true;
  const host = req.headers.host;
  if (!host) return false;
  return origin === 'http://' + host;
}

// ========== HTTP Request Handler ==========

function handleRequest(req, res) {
  if (!isAuthorized(req)) {
    res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
    res.end(FORBIDDEN_PAGE);
    return;
  }
  touchActivity(); // only authorized requests count as activity

  // Mirror the key into a cookie so same-origin subresources (/files/*) can
  // authenticate after bootstrap. HttpOnly keeps it away from page scripts; the
  // WebSocket Origin check below is what blocks cross-origin localhost injection.
  res.setHeader('Set-Cookie',
    COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/');

  const pathname = pathnameOf(req.url);
  const keyFromQuery = queryKey(req.url);
  if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {
    res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
    res.end(bootstrapPage(keyFromQuery));
  } else if (req.method === 'GET' && pathname === '/') {
    const screenFile = getNewestScreen();
    let html = screenFile
      ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
      : waitingPage();

    if (html.includes('</body>')) {
      html = html.replace('</body>', helperInjection + '\n</body>');
    } else {
      html += helperInjection;
    }

    res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
    res.end(html);
  } else if (req.method === 'GET' && pathname.startsWith('/files/')) {
    const fileName = path.basename(pathname.slice(7));
    const filePath = path.join(CONTENT_DIR, fileName);
    // Reject empty/dotfile names and anything that isn't a regular file —
    // `/files/` would otherwise resolve to CONTENT_DIR and crash readFileSync (EISDIR).
    if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) {
      res.writeHead(404, securityHeaders());
      res.end('Not found');
      return;
    }
    const ext = path.extname(filePath).toLowerCase();
    const contentType = MIME_TYPES[ext] || 'application/octet-stream';
    res.writeHead(200, securityHeaders({ 'Content-Type': contentType }));
    res.end(fs.readFileSync(filePath));
  } else {
    res.writeHead(404, securityHeaders());
    res.end('Not found');
  }
}

// ========== WebSocket Connection Handling ==========

const clients = new Set();

function handleUpgrade(req, socket) {
  if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; }

  const key = req.headers['sec-websocket-key'];
  if (!key) { socket.destroy(); return; }

  const accept = computeAcceptKey(key);
  socket.write(
    'HTTP/1.1 101 Switching Protocols\r\n' +
    'Upgrade: websocket\r\n' +
    'Connection: Upgrade\r\n' +
    'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
  );

  let buffer = Buffer.alloc(0);
  clients.add(socket);

  socket.on('data', (chunk) => {
    buffer = Buffer.concat([buffer, chunk]);
    while (buffer.length > 0) {
      let result;
      try {
        result = decodeFrame(buffer);
      } catch (e) {
        socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
        clients.delete(socket);
        return;
      }
      if (!result) break;
      buffer = buffer.slice(result.bytesConsumed);

      switch (result.opcode) {
        case OPCODES.TEXT:
          handleMessage(result.payload.toString());
          break;
        case OPCODES.CLOSE:
          socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
          clients.delete(socket);
          return;
        case OPCODES.PING:
          socket.write(encodeFrame(OPCODES.PONG, result.payload));
          break;
        case OPCODES.PONG:
          break;
        default: {
          const closeBuf = Buffer.alloc(2);
          closeBuf.writeUInt16BE(1003);
          socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
          clients.delete(socket);
          return;
        }
      }
    }
  });

  socket.on('close', () => clients.delete(socket));
  socket.on('error', () => clients.delete(socket));
}

function handleMessage(text) {
  let event;
  try {
    event = JSON.parse(text);
  } catch (e) {
    console.error('Failed to parse WebSocket message:', e.message);
    return;
  }
  touchActivity();
  console.log(JSON.stringify({ source: 'user-event', ...event }));
  if (event && event.choice) {
    const eventsFile = path.join(STATE_DIR, 'events');
    fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
  }
}

function broadcast(msg) {
  const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
  for (const socket of clients) {
    try { socket.write(frame); } catch (e) { clients.delete(socket); }
  }
}

// Best-effort: open the user's browser the first time a screen is actually ready
// to show. Skips when disabled, on a non-loopback (remote) bind, or when a
// browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD.
let browserOpened = false;
function maybeOpenBrowser() {
  if (browserOpened) return;
  browserOpened = true;
  if (!process.env.BRAINSTORM_OPEN) return; // opt-in: only after the user approves the companion
  if (HOST !== '127.0.0.1' && HOST !== 'localhost') return;
  if (clients.size > 0) return; // the user already opened it
  const url = companionUrl(); // must carry the key or the gate 403s it
  const cp = require('child_process');
  // Operator-provided launcher: run as given (this env var is trusted operator input).
  if (process.env.BRAINSTORM_OPEN_CMD) {
    try { cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {}); } catch (e) { /* best effort */ }
    return;
  }
  // Platform launchers: pass the URL as an argv element via execFile (no shell),
  // so a url-host containing shell metacharacters can't inject a command.
  const launcher = browserLauncherForPlatform(url);
  if (!launcher) return; // headless: nothing to open
  try { cp.execFile(launcher.bin, launcher.args, () => {}); } catch (e) { /* best effort */ }
}

// ========== Activity Tracking ==========

// Idle timeout: shut down after this long with no activity. Default 4 hours;
// override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes).
const IDLE_TIMEOUT_MS = (() => {
  const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS);
  return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000;
})();
// How often the watchdog checks for owner-death / idleness. Configurable mainly
// so tests can run fast; production default is 60s.
const LIFECYCLE_CHECK_MS = (() => {
  const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS);
  return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000;
})();
let lastActivity = Date.now();

function touchActivity() {
  lastActivity = Date.now();
}

// ========== File Watching ==========

const debounceTimers = new Map();

// ========== Server Startup ==========

function startServer() {
  if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
  if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });

  // Track known files to distinguish new screens from updates.
  // macOS fs.watch reports 'rename' for both new files and overwrites,
  // so we can't rely on eventType alone.
  const knownFiles = new Set(
    fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html'))
  );

  const server = http.createServer(handleRequest);
  server.on('upgrade', handleUpgrade);

  const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
    if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return;

    if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
    debounceTimers.set(filename, setTimeout(() => {
      debounceTimers.delete(filename);
      const filePath = path.join(CONTENT_DIR, filename);

      if (!fs.existsSync(filePath)) return; // file was deleted
      touchActivity();

      if (!knownFiles.has(filename)) {
        knownFiles.add(filename);
        const eventsFile = path.join(STATE_DIR, 'events');
        if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
        console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
        maybeOpenBrowser();
      } else {
        console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
      }

      broadcast({ type: 'reload' });
    }, 100));
  });
  watcher.on('error', (err) => console.error('fs.watch error:', err.message));

  function shutdown(reason) {
    console.log(JSON.stringify({ type: 'server-stopped', reason }));
    const infoFile = path.join(STATE_DIR, 'server-info');
    if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
    fs.writeFileSync(
      path.join(STATE_DIR, 'server-stopped'),
      JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
    );
    watcher.close();
    clearInterval(lifecycleCheck);
    // Close any upgraded WebSocket sockets so server.close() can complete and
    // the process actually exits instead of lingering on an open connection.
    for (const socket of clients) {
      try { socket.destroy(); } catch (e) { /* already gone */ }
    }
    server.close(() => process.exit(0));
  }

  function ownerAlive() {
    if (!ownerPid) return true;
    try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
  }

  // Periodically exit if the owner process died or we've been idle too long.
  const lifecycleCheck = setInterval(() => {
    if (!ownerAlive()) shutdown('owner process exited');
    else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
  }, LIFECYCLE_CHECK_MS);
  lifecycleCheck.unref();

  // Validate owner PID at startup. If it's already dead, the PID resolution
  // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
  // Disable monitoring and rely on the idle timeout instead.
  if (ownerPid) {
    try { process.kill(ownerPid, 0); }
    catch (e) {
      if (e.code !== 'EPERM') {
        console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
        ownerPid = null;
      }
    }
  }

  // If the preferred port is already taken (e.g. a previous server is still
  // alive), fall back to a random port once instead of failing.
  let triedFallback = false;

  function onListen() {
    // Cookie name keys on the ACTUAL bound port (may differ from the preferred
    // one after an EADDRINUSE fallback) so it can't collide with another server's
    // cookie in the shared localhost jar.
    COOKIE_NAME = 'brainstorm-key-' + PORT;
    // Record the bound port AND token so the next restart of this session reuses
    // them — but ONLY when we got our preferred port. On a fallback we bound a
    // *different* port because someone else holds the preferred one; persisting
    // would overwrite the shared files and strand that other session's open tab.
    if (PORT_FILE && !triedFallback) {
      try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }
      if (TOKEN_FILE) {
        try {
          fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 });
          chmodOwnerOnly(TOKEN_FILE);
        } catch (e) { /* best effort */ }
      }
    }
    const info = JSON.stringify({
      type: 'server-started', port: Number(PORT), host: HOST,
      url_host: URL_HOST, url: companionUrl(),
      screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS
    });
    console.log(info);
    // server-info embeds the key — keep it owner-only.
    fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 });
  }

  server.on('error', (err) => {
    if (err.code === 'EADDRINUSE' && !triedFallback) {
      if (tokenSource === 'env') {
        console.error('Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; refusing fallback with explicit token');
        process.exit(1);
      }
      triedFallback = true;
      PORT = randomPort();
      if (tokenSource === 'file') {
        TOKEN = generateToken();
        tokenSource = 'generated-fallback';
      }
      server.listen(PORT, HOST, onListen);
    } else {
      console.error('Server failed to bind:', err.message);
      process.exit(1);
    }
  });
  server.listen(PORT, HOST, onListen);
}

if (require.main === module) {
  startServer();
}

module.exports = {
  computeAcceptKey,
  encodeFrame,
  decodeFrame,
  browserLauncherForPlatform,
  OPCODES,
  MAX_FRAME_PAYLOAD_BYTES
};

Kvíz (13 otázek, odpověď se rozbalí kliknutím)

1. Proč server nemá žádné npm závislosti?

Spouští se uvnitř cizích projektů a prostředí, kde nelze předpokládat npm install. Čistý Node snižuje povrch útoku, odpadá supply-chain riziko a server nastartuje okamžitě. Cenou je, že WebSocket protokol je naimplementovaný ručně a testuje se důkladně (ws-protocol.test.js).

2. Jak funguje WebSocket handshake?

Server vezme Sec-WebSocket-Key klienta, připojí magic GUID z RFC 6455, spočítá sha1 a vrátí base64 jako Sec-WebSocket-Accept. Tím klient ověří, že server protokol opravdu rozumí. Funkce computeAcceptKey to dělá jedním řádkem.

3. Proč se klientské rámce odmaskovávají?

RFC 6455 vyžaduje, aby klient rámce maskoval čtyřbajtovým klíčem (ochrana proxy cache před otrávením). Server tedy každý bajt XORuje s mask[i % 4]. Odpovědi serveru maskovány nejsou.

4. K čemu je `MAX_FRAME_PAYLOAD_BYTES`?

Zabraňuje alokaci obří paměti, pokud klient pošle rámec s deklarovanou délkou v gigabajtech. Překročení limitu skončí chybou. Je to jednoduchá obrana proti vyčerpání paměti.

5. Proč se token porovnává přes `crypto.timingSafeEqual`?

Obyčejné porovnání řetězců končí na prvním rozdílném znaku, takže útočník by z doby odpovědi mohl postupně uhodnout token. timingSafeEqual trvá stejně dlouho bez ohledu na shodu.

6. Co dělá cookie `HttpOnly; SameSite=Strict`?

HttpOnly brání čtení cookie ze skriptů stránky (XSS), SameSite=Strict ji neposílá při cross-site požadavcích. Po prvním načtení s ?key= se uživatel autentizuje cookie a klíč zmizí z URL.

7. Proč se při WebSocket upgrade kontroluje `Origin`?

Cookie by se jinak poslala i při spojení z cizí stránky otevřené v prohlížeči uživatele (cross-site WebSocket hijacking), a také při DNS rebindingu. Server povolí jen Origin shodný s hlavičkou Host (nebo bez Origin, např. nástroje mimo prohlížeč).

8. K čemu jsou bezpečnostní hlavičky?

X-Frame-Options: DENY a frame-ancestors 'none' brání clickjackingu, no-store brání cachování obsahu, no-referrer neprozradí URL s klíčem, CORP: same-origin zakazuje cizím originům načíst zdroje.

9. Proč debouncing 100 ms u `fs.watch`?

Jedno uložení souboru vyvolá několik událostí. Debounce je sloučí v jeden reload a navíc počká, až je soubor zapsaný celý.

10. Proč se rozlišuje `screen-added` a `screen-updated`?

Nová obrazovka smaže starý soubor events (staré volby uživatele už neplatí) a může otevřít prohlížeč. Úprava stávající jen vyvolá reload. Sada knownFiles je nutná, protože macOS hlásí rename pro nový i přepsaný soubor.

11. Proč má server idle timeout a hlídá owner PID?

Nemá zůstat běžet navždy, když agent skončí. Bez vlastníka nebo po 4 h nečinnosti se sám ukončí, takže nezůstávají „zapomenuté“ servery.

12. Proč se `server-info` a token ukládají s oprávněním 0600?

Obsahují klíč relace. Souborová oprávnění zajišťují, že je čte jen vlastník, takže jiný uživatel stroje se k companionu nepřipojí.

13. Jak se server chová, když preferovaný port je obsazený?

Pokud nebyl zadán explicitní token, přepne na náhodný port; při explicitním tokenu odmítne fallback a skončí, aby se neprozradil klíč na neočekávaném portu.

Slovník pojmů (15)

Visual companion

Webové rozhraní, kde uživatel vidí náčrty agenta a klikáním vybírá varianty.

Content dir

Adresář, do kterého agent píše .html obrazovky; server ho sleduje.

State dir

Adresář se stavem: events, server-info, server.log, pid.

WebSocket (RFC 6455)

Obousměrné spojení nad HTTP. Server implementuje handshake a rámce ručně.

Sec-WebSocket-Accept

Odpověď na handshake: base64(sha1(key + GUID)).

Frame masking

XOR payloadu klientských rámců čtyřbajtovým klíčem.

Token / session key

256bitový náhodný secret; autentizuje přístup.

`timingSafeEqual`

Porovnání s konstantní dobou, odolné proti timing útoku.

Cookie bootstrap

První načtení /?key=… nastaví cookie a přesměruje na čistou adresu.

Origin check

Kontrola, zda WebSocket spojení pochází ze stejného originu.

DNS rebinding

Útok, kdy cizí doména přepíše DNS na lokální adresu; obrana je kontrola Host/Origin.

Debounce

Sloučení rychlých opakovaných událostí do jedné akce.

`screen-added` / `screen-updated`

Události logu pro novou a změněnou obrazovku.

Idle timeout

Ukončení po době bez aktivity.

Owner PID

PID procesu, jehož zánik znamená ukončení serveru.

↑ nahoru

start-server.sh (brainstorming)

Spouští brainstorm server na náhodném portu, řeší foreground/background, owner PID, per-session adresáře a tokeny s oprávněním 077.

Skript spouští vizuální companion skillu brainstorming. Vytvoří unikátní session adresář (/tmp/brainstorm-<pid>-<čas> nebo <projekt>/.superpowers/brainstorm/<id>) s podadresáři content a state, vygeneruje náhodné server instance id a spustí node server.cjs s proměnnými BRAINSTORM_DIR, BRAINSTORM_HOST, BRAINSTORM_URL_HOST a BRAINSTORM_OWNER_PID. V režimu na pozadí čeká až 5 s na zprávu server-started v logu, ověří, že proces po krátké době stále žije, a vypíše JSON s URL.

Přepínače: --project-dir, --host, --url-host, --idle-timeout-minutes, --open, --foreground, --background. Skript je odolný vůči prostředím: v Codexu a na Windows/Git Bash automaticky přepne na foreground, protože tam se odpojené procesy ukončují. Před vším nastaví umask 077, takže soubory se session klíčem vidí jen vlastník.

Zdrojový kód

skills/brainstorming/scripts/start-server.sh 210 řádků
#!/usr/bin/env bash
# Start the brainstorm server and output connection info
# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]
#
# Starts server on a random high port, outputs JSON with URL.
# Each session gets its own directory to avoid conflicts.
#
# Options:
#   --project-dir <path>  Store session files under <path>/.superpowers/brainstorm/
#                         instead of /tmp. Files persist after server stops.
#   --host <bind-host>    Host/interface to bind (default: 127.0.0.1).
#                         Use 0.0.0.0 in remote/containerized environments.
#   --url-host <host>     Hostname shown in returned URL JSON.
#   --idle-timeout-minutes <n>  Shut down after n minutes idle (default 240 = 4h).
#   --open                Auto-open the browser on the first screen (use only
#                         after the user approves the visual companion).
#   --foreground          Run server in the current terminal (no backgrounding).
#   --background          Force background mode (overrides Codex auto-foreground).

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Parse arguments
PROJECT_DIR=""
FOREGROUND="false"
FORCE_BACKGROUND="false"
BIND_HOST="127.0.0.1"
URL_HOST=""
IDLE_TIMEOUT_MINUTES=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --project-dir)
      PROJECT_DIR="$2"
      shift 2
      ;;
    --host)
      BIND_HOST="$2"
      shift 2
      ;;
    --url-host)
      URL_HOST="$2"
      shift 2
      ;;
    --idle-timeout-minutes)
      IDLE_TIMEOUT_MINUTES="$2"
      shift 2
      ;;
    --open)
      export BRAINSTORM_OPEN=1
      shift
      ;;
    --foreground|--no-daemon)
      FOREGROUND="true"
      shift
      ;;
    --background|--daemon)
      FORCE_BACKGROUND="true"
      shift
      ;;
    *)
      echo "{\"error\": \"Unknown argument: $1\"}"
      exit 1
      ;;
  esac
done

if [[ -z "$URL_HOST" ]]; then
  if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then
    URL_HOST="localhost"
  else
    URL_HOST="$BIND_HOST"
  fi
fi

if [[ -n "$IDLE_TIMEOUT_MINUTES" ]]; then
  if ! [[ "$IDLE_TIMEOUT_MINUTES" =~ ^[0-9]+$ ]] || [[ "$IDLE_TIMEOUT_MINUTES" -lt 1 ]]; then
    echo "{\"error\": \"--idle-timeout-minutes must be a positive integer\"}"
    exit 1
  fi
  export BRAINSTORM_IDLE_TIMEOUT_MS=$(( IDLE_TIMEOUT_MINUTES * 60 * 1000 ))
fi

is_windows_like_shell() {
  case "${OSTYPE:-}" in
    msys*|cygwin*|mingw*) return 0 ;;
  esac
  if [[ -n "${MSYSTEM:-}" ]]; then
    return 0
  fi
  local uname_s
  uname_s="$(uname -s 2>/dev/null || true)"
  case "$uname_s" in
    MSYS*|MINGW*|CYGWIN*) return 0 ;;
  esac
  return 1
}

# Some environments reap detached/background processes. Auto-foreground when detected.
if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
  FOREGROUND="true"
fi

# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected.
if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
  if is_windows_like_shell; then
    FOREGROUND="true"
  fi
fi

# Session files (server.log, server-info, .last-token) embed the session key —
# keep everything this script and the server create owner-only.
umask 077

# Generate unique session directory
SESSION_ID="$$-$(date +%s)"

if [[ -n "$PROJECT_DIR" ]]; then
  SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}"
  # Persist the bound port and key per project so a restart reuses them and an
  # already-open browser tab reconnects to the same URL with a valid cookie.
  export BRAINSTORM_PORT_FILE="${PROJECT_DIR}/.superpowers/brainstorm/.last-port"
  export BRAINSTORM_TOKEN_FILE="${PROJECT_DIR}/.superpowers/brainstorm/.last-token"
else
  SESSION_DIR="/tmp/brainstorm-${SESSION_ID}"
fi

STATE_DIR="${SESSION_DIR}/state"
PID_FILE="${STATE_DIR}/server.pid"
LOG_FILE="${STATE_DIR}/server.log"
SERVER_ID_FILE="${STATE_DIR}/server-instance-id"

# Create fresh session directory with content and state peers
mkdir -p "${SESSION_DIR}/content" "$STATE_DIR"

SERVER_ID=""
if [[ -r /dev/urandom ]]; then
  SERVER_ID="$(od -An -N24 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n' || true)"
fi
if ! [[ "$SERVER_ID" =~ ^[A-Za-z0-9_-]{32,64}$ ]]; then
  SERVER_ID="$(printf '%08x%08x%08x%08x' "$$" "$(date +%s)" "${RANDOM:-0}" "${RANDOM:-0}")"
fi
printf '%s\n' "$SERVER_ID" > "$SERVER_ID_FILE"
chmod 600 "$SERVER_ID_FILE" 2>/dev/null || true

# Kill any existing server
if [[ -f "$PID_FILE" ]]; then
  old_pid=$(cat "$PID_FILE")
  kill "$old_pid" 2>/dev/null
  rm -f "$PID_FILE"
fi

cd "$SCRIPT_DIR" || exit 1

# Resolve the harness PID (grandparent of this script).
# $PPID is the ephemeral shell the harness spawned to run us — it dies
# when this script exits. The harness itself is $PPID's parent.
OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')"
if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then
  OWNER_PID="$PPID"
fi

# Windows/MSYS2: Node.js cannot see POSIX PIDs from the MSYS2 namespace.
# Passing a PID node cannot verify causes server to log owner-pid-invalid
# and self-terminate at the 60-second lifecycle check. Clear it so the
# watchdog is disabled and the idle timeout becomes the only shutdown trigger.
if is_windows_like_shell; then
  OWNER_PID=""
fi

# Foreground mode for environments that reap detached/background processes.
if [[ "$FOREGROUND" == "true" ]]; then
  env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" &
  SERVER_PID=$!
  echo "$SERVER_PID" > "$PID_FILE"
  wait "$SERVER_PID"
  exit $?
fi

# Start server, capturing output to log file
# Use nohup to survive shell exit; disown to remove from job table
nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" > "$LOG_FILE" 2>&1 &
SERVER_PID=$!
disown "$SERVER_PID" 2>/dev/null
echo "$SERVER_PID" > "$PID_FILE"

# Wait for server-started message (check log file)
for _ in {1..50}; do
  if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then
    # Verify server is still alive after a short window (catches process reapers)
    alive="true"
    for _ in {1..20}; do
      if ! kill -0 "$SERVER_PID" 2>/dev/null; then
        alive="false"
        break
      fi
      sleep 0.1
    done
    if [[ "$alive" != "true" ]]; then
      echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}"
      exit 1
    fi
    grep "server-started" "$LOG_FILE" | head -1
    exit 0
  fi
  sleep 0.1
done

# Timeout - server didn't start
echo '{"error": "Server failed to start within 5 seconds"}'
exit 1

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč `umask 077`?

Session soubory (server.log, server-info, .last-token) obsahují klíč relace. S umask 077 jsou čitelné pouze vlastníkem, takže ostatní uživatelé stroje klíč nezískají.

2. Proč existuje foreground režim?

Některá prostředí (Codex, Git Bash) odpojené procesy zabíjejí. Foreground drží server v terminálu, který je naživu. Skript to pozná automaticky, ale lze vynutit --foreground i --background.

3. K čemu je `BRAINSTORM_OWNER_PID` a proč se hledá „grandparent“?

Server se sám ukončí, když vlastník zmizí. $PPID je pomocný shell, který skončí s skriptem; skutečný harness je jeho rodič. Na Windows/MSYS2 se PID čistí, protože Node ho neumí ověřit a server by se po minutě sám ukončil.

4. Proč se ověřuje, že server žije i po zprávě `server-started`?

Některé prostředí proces krátce po startu zabije. Dvousekundové ověření chytí takový případ a vypíše návod, jak spustit ve foreground.

5. Proč server instance id?

Je to jednorázové náhodné id předané jako argument --brainstorm-server-id=. stop-server.sh podle něj pozná, že PID patří právě tomuto serveru, a nezabije cizí proces.

6. Proč `--project-dir` ukládá port a token do `.last-port` a `.last-token`?

Po restartu se použije stejný port a klíč, takže otevřená záložka prohlížeče se znovu připojí na stejné URL se stále platnou cookie.

7. Jak se validuje `--idle-timeout-minutes`?

Musí to být kladné celé číslo, jinak skript vypíše JSON chybu a skončí. Hodnota se převede na milisekundy do BRAINSTORM_IDLE_TIMEOUT_MS.

8. Proč výstup v JSON?

Agent z něj strojově vyčte URL nebo chybu. Konzistentní formát i pro chyby usnadňuje zpracování.

9. Co skript dělá s předchozím serverem téhož adresáře?

Pokud existuje PID soubor, pošle starému procesu kill a soubor smaže. Zabrání se dvěma serverům pro jednu session.

Slovník pojmů (11)

Visual companion

Webový server zobrazující náčrty a volby během brainstormingu.

Session directory

Adresář s podadresáři content a state pro jednu session.

`BRAINSTORM_OWNER_PID`

PID vlastnického procesu; když zmizí, server se ukončí.

Server instance id

Náhodné id předané serveru jako argument pro bezpečné rozpoznání při zastavení.

`umask 077`

Nastavení oprávnění, aby nové soubory vlastnil jen uživatel.

Foreground / background

Běh v terminálu versus odpojený proces (nohup).

`nohup` + `disown`

Zajišťují, že server přežije konec shellu.

Idle timeout

Ukončení po době nečinnosti (výchozí 4 hodiny).

`server-started`

Zpráva v logu, na kterou skript čeká.

`.last-port` / `.last-token`

Soubory pro opakované použití portu a klíče po restartu.

Windows-like shell

MSYS/Cygwin/MinGW, kde je potřeba foreground a čištění owner PID.

↑ nahoru

stop-server.sh (brainstorming)

Bezpečně zastaví brainstorm server: ověří, že PID patří právě jemu, ukončí ho (SIGTERM → SIGKILL) a uklidí jen dočasné adresáře.

stop-server.sh <session_dir> zastaví server dané session. Nejdřív přečte PID ze state/server.pid a ověří, že proces opravdu je tento server: musí mít v příkazové řádce argument --brainstorm-server-id=<id> shodný s server-instance-id uloženým v session. Pokud ověření selže (zastaralý PID po rebootu, recyklované PID), skript nikoho nezabije, smaže pomocné soubory a vypíše {"status": "stale_pid"}.

Při platném serveru pošle kill (SIGTERM), až 2 s čeká, a pokud proces žije, eskaluje na kill -9. Pak smaže pid/id/log, zapíše server-stopped s důvodem a časem a smaže session adresář jen pod /tmp/; trvalé adresáře .superpowers/ zůstávají, aby šly mockupy později prohlédnout. Výstup je vždy JSON.

Zdrojový kód

skills/brainstorming/scripts/stop-server.sh 121 řádků
#!/usr/bin/env bash
# Stop the brainstorm server and clean up
# Usage: stop-server.sh <session_dir>
#
# Kills the server process. Only deletes session directory if it's
# under /tmp (ephemeral). Persistent directories (.superpowers/) are
# kept so mockups can be reviewed later.

SESSION_DIR="$1"

if [[ -z "$SESSION_DIR" ]]; then
  echo '{"error": "Usage: stop-server.sh <session_dir>"}'
  exit 1
fi

STATE_DIR="${SESSION_DIR}/state"
PID_FILE="${STATE_DIR}/server.pid"
SERVER_ID_FILE="${STATE_DIR}/server-instance-id"

mark_stopped() {
  local reason="$1"
  rm -f "${STATE_DIR}/server-info"
  printf '{"reason":"%s","timestamp":%s}\n' "$reason" "$(date +%s)" > "${STATE_DIR}/server-stopped"
}

read_expected_server_id() {
  [[ -f "$SERVER_ID_FILE" ]] || return 1
  local id
  id="$(tr -d '\r\n' < "$SERVER_ID_FILE" 2>/dev/null || true)"
  [[ "$id" =~ ^[A-Za-z0-9_-]{32,64}$ ]] || return 1
  printf '%s\n' "$id"
}

command_line_for_pid() {
  local pid="$1"
  if [[ -r "/proc/$pid/cmdline" ]]; then
    tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null || true
    return 0
  fi
  ps -ww -p "$pid" -o command= 2>/dev/null || ps -f -p "$pid" 2>/dev/null | sed '1d' || true
}

command_has_server_id() {
  local pid="$1"
  local expected="$2"
  local expected_arg="--brainstorm-server-id=$expected"
  if [[ -r "/proc/$pid/cmdline" ]]; then
    local arg
    while IFS= read -r -d '' arg || [[ -n "$arg" ]]; do
      [[ "$arg" == "$expected_arg" ]] && return 0
    done < "/proc/$pid/cmdline"
    return 1
  fi
  local command_line
  command_line="$(command_line_for_pid "$pid")"
  [[ -n "$command_line" ]] || return 1
  case " $command_line " in
    *" $expected_arg "*) return 0 ;;
    *) return 1 ;;
  esac
}

# Confirm a PID has this session's per-start instance id, not just a familiar
# process name. Ambiguous or legacy metadata fails closed as stale_pid.
is_brainstorm_server() {
  kill -0 "$1" 2>/dev/null || return 1
  local expected_id
  expected_id="$(read_expected_server_id)" || return 1
  command_has_server_id "$1" "$expected_id" || return 1
  return 0
}

if [[ -f "$PID_FILE" ]]; then
  pid=$(cat "$PID_FILE")

  # Refuse to signal a PID we can't prove is our server. A stale pid file may
  # point at an unrelated process after a reboot/PID wraparound.
  if ! is_brainstorm_server "$pid"; then
    rm -f "$PID_FILE" "$SERVER_ID_FILE"
    mark_stopped "stale_pid"
    echo '{"status": "stale_pid"}'
    exit 0
  fi

  # Try to stop gracefully, fallback to force if still alive
  kill "$pid" 2>/dev/null || true

  # Wait for graceful shutdown (up to ~2s)
  for _ in {1..20}; do
    if ! kill -0 "$pid" 2>/dev/null; then
      break
    fi
    sleep 0.1
  done

  # If still running, escalate to SIGKILL
  if kill -0 "$pid" 2>/dev/null; then
    kill -9 "$pid" 2>/dev/null || true

    # Give SIGKILL a moment to take effect
    sleep 0.1
  fi

  if kill -0 "$pid" 2>/dev/null; then
    echo '{"status": "failed", "error": "process still running"}'
    exit 1
  fi

  rm -f "$PID_FILE" "$SERVER_ID_FILE" "${STATE_DIR}/server.log"
  mark_stopped "stop-server.sh"

  # Only delete ephemeral /tmp directories
  if [[ "$SESSION_DIR" == /tmp/* ]]; then
    rm -rf "$SESSION_DIR"
  fi

  echo '{"status": "stopped"}'
else
  echo '{"status": "not_running"}'
fi

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se PID před zabitím ověřuje přes instance id?

PID z pid souboru může po rebootu nebo obtočení čítače patřit úplně jinému procesu. Zabití cizího procesu by bylo nebezpečné. Instance id v příkazové řádce prokáže, že jde o náš server.

2. Co znamená „fails closed“ u nejasných metadat?

Pokud id chybí, je neplatné nebo ho nelze v příkazu najít, skript považuje PID za nedůvěryhodný a nic nezabíjí (stale_pid). Při pochybnosti se volí bezpečná cesta.

3. Proč nejdřív SIGTERM a až potom SIGKILL?

SIGTERM dovolí serveru ukončit se čistě (uzavřít spojení, zapsat stav). SIGKILL je poslední možnost, když proces neodpovídá do dvou sekund.

4. Proč se maže jen adresář pod `/tmp/`?

/tmp je dočasný. Adresář v projektu (.superpowers/brainstorm) může obsahovat mockupy, které si uživatel chce později prohlédnout.

5. K čemu je soubor `server-stopped`?

Zapisuje důvod a čas zastavení. Klienti (a testy) podle něj poznají, že se server zastavil záměrně a proč.

6. Jak funguje čtení `/proc/<pid>/cmdline`?

Položky jsou odděleny nulovými bajty; skript je čte po jedné (read -d '') a porovnává s očekávaným argumentem. Je to přesnější než hledat řetězec v celé řádce. Na systémech bez /proc se používá ps.

7. Proč výstup JSON se stavem?

Volající (agent) čte status (stopped, not_running, stale_pid, failed). Strojově čitelný výsledek je spolehlivější než text.

8. Co když server po SIGKILL stále žije?

Skript vypíše {"status": "failed", "error": "process still running"} a skončí s kódem 1. Nepředstírá úspěch.

Slovník pojmů (9)

`server.pid`

Soubor s PID serveru ve state/.

`server-instance-id`

Náhodné id konkrétního spuštění; slouží k ověření identity procesu.

`stale_pid`

Stav, kdy PID nepatří našemu serveru. Nic se nezabíjí.

SIGTERM / SIGKILL

Slušné vs. násilné ukončení procesu (kill / kill -9).

`mark_stopped`

Funkce zapisující server-stopped a mazající server-info.

`/proc/<pid>/cmdline`

Linuxový soubor s argumenty procesu oddělenými nulami.

Ephemeral directory

Adresář v /tmp, který se po zastavení maže.

Persistent directory

.superpowers/…, zůstává pro pozdější prohlížení.

Fail closed

Při pochybnostech nevykonat riskantní akci.

↑ nahoru

find-polluter.sh (systematic-debugging)

Bisekční skript, který po jednom spouští testy a najde ten, který vytváří nechtěný soubor nebo stav.

Když po testovací sadě zůstane nečekaný soubor (například .git v adresáři, kde nemá být), nevíme, který test ho vytvořil. find-polluter.sh <soubor> <vzor-testů> je vyhledá: najde testovací soubory podle vzoru, spouští je po jednom (npm test <soubor>) a po každém zkontroluje, zda „znečištění“ vzniklo. První test, po kterém existuje, vypíše jako POLLUTER s detaily a návodem, a skončí kódem 1. Pokud žádný, vypíše ✅ a skončí 0.

Detaily: skript akceptuje vzor s úvodním ./ i bez něj, řeší omezení find -path u / (zkouší i variantu s / sbaleným, aby našel soubory přímo v základním adresáři) a pokud znečištění existuje už před testem, test přeskočí a upozorní.

Zdrojový kód

skills/systematic-debugging/find-polluter.sh 73 řádků
#!/usr/bin/env bash
# Bisection script to find which test creates unwanted files/state
# Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'

set -e

if [ $# -ne 2 ]; then
  echo "Usage: $0 <file_to_check> <test_pattern>"
  echo "Example: $0 '.git' 'src/**/*.test.ts'"
  exit 1
fi

POLLUTION_CHECK="$1"
TEST_PATTERN="$2"

echo "🔍 Searching for test that creates: $POLLUTION_CHECK"
echo "Test pattern: $TEST_PATTERN"
echo ""

# Get list of test files (find . emits ./-prefixed paths, so accept the
# pattern written with or without a leading ./)
TEST_PATTERN="${TEST_PATTERN#./}"
# find -path can't match '**/' against zero directory levels, so a pattern
# like src/**/*.test.ts would skip src/top.test.ts; also try the pattern
# with '**/' collapsed to cover files directly under the base directory.
TEST_FILES=$(find . \( -path "./$TEST_PATTERN" -o -path "./${TEST_PATTERN//\*\*\//}" \) | sort -u)
if [ -z "$TEST_FILES" ]; then
  TOTAL=0
else
  TOTAL=$(printf '%s\n' "$TEST_FILES" | wc -l | tr -d ' ')
fi

echo "Found $TOTAL test files"
echo ""

COUNT=0
for TEST_FILE in $TEST_FILES; do
  COUNT=$((COUNT + 1))

  # Skip if pollution already exists
  if [ -e "$POLLUTION_CHECK" ]; then
    echo "⚠️  Pollution already exists before test $COUNT/$TOTAL"
    echo "   Skipping: $TEST_FILE"
    continue
  fi

  echo "[$COUNT/$TOTAL] Testing: $TEST_FILE"

  # Run the test
  npm test "$TEST_FILE" > /dev/null 2>&1 || true

  # Check if pollution appeared
  if [ -e "$POLLUTION_CHECK" ]; then
    echo ""
    echo "🎯 FOUND POLLUTER!"
    echo "   Test: $TEST_FILE"
    echo "   Created: $POLLUTION_CHECK"
    echo ""
    echo "Pollution details:"
    ls -la "$POLLUTION_CHECK"
    echo ""
    echo "To investigate:"
    echo "  npm test $TEST_FILE    # Run just this test"
    echo "  cat $TEST_FILE         # Review test code"
    exit 1
  fi
done

echo ""
echo "✅ No polluter found - all tests clean!"
exit 0

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se testy spouští po jednom a ne všechny najednou?

Jen takto lze přiřadit vzniklý efekt ke konkrétnímu testu. Po společném běhu by se jen vědělo, že znečištění vzniklo někde. Je to princip bisekce: izolovat původce.

2. Proč skript přeskočí test, když znečištění už existuje?

Pokud soubor existuje před testem, jeho případný vznik by nešlo přisoudit. Upozornění „Pollution already exists“ říká, že je nutné před hledáním uklidit.

3. K čemu je zpracování `**/` v patternu?

find -path neumí / shodovat s nulovým počtem adresářů, takže by src//.test.ts minul src/top.test.ts. Skript proto zkouší i vzor se sbaleným */.

4. Proč `|| true` u spuštění testu?

Test může selhat z jiného důvodu, ale pro hledání znečištění nás zajímá jen jeho vedlejší efekt. Bez || true by set -e skript ukončil na prvním selhaném testu.

5. Proč se výstup testů zahazuje (`> /dev/null 2>&1`)?

Skript potřebuje pouze zjistit existenci souboru; výstup by zahltil terminál a skryl průběh hledání.

6. Proč exit 1 při nalezení a 0 při nenalezení?

Nalezení polluteru je „nález“, signalizovaný nenulovým kódem, aby ho šlo použít v dalších skriptech. Čistý výsledek je úspěch.

7. Jaké další informace skript při nálezu vypíše?

ls -la znečištění a návod: spustit jen daný test a přečíst jeho kód. Dává tak další kroky vyšetřování.

8. Jak skript spadá do metodiky systematic-debugging?

Je to nástroj pro nalezení kořenové příčiny (root cause) místo hádání. Skill říká, že se mají sbírat důkazy před opravou, a tento skript je důkaz automatizuje.

Slovník pojmů (8)

Polluter

Test, který vytváří nechtěný soubor nebo stav.

Pollution

Nechtěný vedlejší efekt testu, např. vytvořený adresář .git.

Bisekce

Postupné zužování kandidátů; zde jednotlivé testy po jednom.

Test pattern

Glob vzor pro nalezení testovacích souborů (src/**/*.test.ts).

`find -path`

Příkaz pro výběr souborů podle cesty; neumí **/ s nulovou úrovní.

`set -e`

Skript skončí při první chybě; zde obejito || true.

Root cause

Skutečná příčina chyby, kterou systematic-debugging hledá.

Exit 1

Signál, že polluter byl nalezen.

↑ nahoru

render-graphs.js (writing-skills)

Extrahuje ```dot bloky ze SKILL.md a vykreslí je přes Graphviz do SVG, volitelně sloučené do jednoho diagramu.

Skripty skills často obsahují postupové diagramy v jazyce DOT (Graphviz) uvnitř bloků ``` `dot ``. render-graphs.js <adresář-skillu> [--combine] je najde regulárním výrazem, z digraph <název> odvodí jméno a zavolá dot -Tsvg (přes execFileSync, bez shellu). Každý diagram uloží do <skill>/diagrams/<název>.svg. S --combine sloučí všechny do jednoho grafu, kde je každý diagram subgraph cluster_i, a uloží i zdroj .dot` pro ladění.

Skript kontroluje, že SKILL.md existuje a že je dostupný dot (spouští dot -V místo which, protože which na Windows není). Pokud chybí, vypíše instalační návod. Slouží k tomu, aby si „your human partner“ mohl procesy skillu prohlédnout vizuálně.

Zdrojový kód

skills/writing-skills/render-graphs.js 170 řádků
#!/usr/bin/env node

/**
 * Render graphviz diagrams from a skill's SKILL.md to SVG files.
 *
 * Usage:
 *   ./render-graphs.js <skill-directory>           # Render each diagram separately
 *   ./render-graphs.js <skill-directory> --combine # Combine all into one diagram
 *
 * Extracts all ```dot blocks from SKILL.md and renders to SVG.
 * Useful for helping your human partner visualize the process flows.
 *
 * Requires: graphviz (dot) installed on system
 */

import * as fs from 'fs';
import * as path from 'path';
import { execFileSync } from 'child_process';

function extractDotBlocks(markdown) {
  const blocks = [];
  const regex = /```dot\n([\s\S]*?)```/g;
  let match;

  while ((match = regex.exec(markdown)) !== null) {
    const content = match[1].trim();

    // Extract digraph name
    const nameMatch = content.match(/digraph\s+(\w+)/);
    const name = nameMatch ? nameMatch[1] : `graph_${blocks.length + 1}`;

    blocks.push({ name, content });
  }

  return blocks;
}

function extractGraphBody(dotContent) {
  // Extract just the body (nodes and edges) from a digraph
  const match = dotContent.match(/digraph\s+\w+\s*\{([\s\S]*)\}/);
  if (!match) return '';

  let body = match[1];

  // Remove rankdir (we'll set it once at the top level)
  body = body.replace(/^\s*rankdir\s*=\s*\w+\s*;?\s*$/gm, '');

  return body.trim();
}

function combineGraphs(blocks, skillName) {
  const bodies = blocks.map((block, i) => {
    const body = extractGraphBody(block.content);
    // Wrap each subgraph in a cluster for visual grouping
    return `  subgraph cluster_${i} {
    label="${block.name}";
    ${body.split('\n').map(line => '  ' + line).join('\n')}
  }`;
  });

  return `digraph ${skillName}_combined {
  rankdir=TB;
  compound=true;
  newrank=true;

${bodies.join('\n\n')}
}`;
}

function renderToSvg(dotContent) {
  try {
    return execFileSync('dot', ['-Tsvg'], {
      input: dotContent,
      encoding: 'utf-8',
      maxBuffer: 10 * 1024 * 1024
    });
  } catch (err) {
    console.error('Error running dot:', err.message);
    if (err.stderr) console.error(err.stderr.toString());
    return null;
  }
}

function main() {
  const args = process.argv.slice(2);
  const combine = args.includes('--combine');
  const skillDirArg = args.find(a => !a.startsWith('--'));

  if (!skillDirArg) {
    console.error('Usage: render-graphs.js <skill-directory> [--combine]');
    console.error('');
    console.error('Options:');
    console.error('  --combine    Combine all diagrams into one SVG');
    console.error('');
    console.error('Example:');
    console.error('  ./render-graphs.js ../subagent-driven-development');
    console.error('  ./render-graphs.js ../subagent-driven-development --combine');
    process.exit(1);
  }

  const skillDir = path.resolve(skillDirArg);
  const skillFile = path.join(skillDir, 'SKILL.md');
  const skillName = path.basename(skillDir).replace(/-/g, '_');

  if (!fs.existsSync(skillFile)) {
    console.error(`Error: ${skillFile} not found`);
    process.exit(1);
  }

  // Check if dot is available. Run the binary directly rather than probing
  // with `which`, which is not a command on Windows.
  try {
    execFileSync('dot', ['-V'], { stdio: 'ignore' });
  } catch {
    console.error('Error: graphviz (dot) not found. Install with:');
    console.error('  brew install graphviz    # macOS');
    console.error('  apt install graphviz     # Linux');
    process.exit(1);
  }

  const markdown = fs.readFileSync(skillFile, 'utf-8');
  const blocks = extractDotBlocks(markdown);

  if (blocks.length === 0) {
    console.log('No ```dot blocks found in', skillFile);
    process.exit(0);
  }

  console.log(`Found ${blocks.length} diagram(s) in ${path.basename(skillDir)}/SKILL.md`);

  const outputDir = path.join(skillDir, 'diagrams');
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir);
  }

  if (combine) {
    // Combine all graphs into one
    const combined = combineGraphs(blocks, skillName);
    const svg = renderToSvg(combined);
    if (svg) {
      const outputPath = path.join(outputDir, `${skillName}_combined.svg`);
      fs.writeFileSync(outputPath, svg);
      console.log(`  Rendered: ${skillName}_combined.svg`);

      // Also write the dot source for debugging
      const dotPath = path.join(outputDir, `${skillName}_combined.dot`);
      fs.writeFileSync(dotPath, combined);
      console.log(`  Source: ${skillName}_combined.dot`);
    } else {
      console.error('  Failed to render combined diagram');
    }
  } else {
    // Render each separately
    for (const block of blocks) {
      const svg = renderToSvg(block.content);
      if (svg) {
        const outputPath = path.join(outputDir, `${block.name}.svg`);
        fs.writeFileSync(outputPath, svg);
        console.log(`  Rendered: ${block.name}.svg`);
      } else {
        console.error(`  Failed: ${block.name}`);
      }
    }
  }

  console.log(`\nOutput: ${outputDir}/`);
}

main();

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč se `dot` volá přes `execFileSync` a ne `execSync`?

execFileSync předává argumenty přímo programu bez shellu, takže nehrozí shell injection ani problémy s uvozovkami v cestách. Vstup (input) jde přes stdin.

2. Proč se dostupnost `dot` testuje příkazem `dot -V` místo `which dot`?

which není příkaz na Windows. Přímé spuštění binárky funguje na všech platformách a výsledek je spolehlivější.

3. Co dělá `--combine`?

Sloučí všechny diagramy do jednoho grafu, přičemž každý uzavře do subgraph cluster_i s popiskem. Hodí se pro celkový přehled procesu. Odstraní se rankdir jednotlivých grafů a nastaví se jednou nahoře.

4. Proč se ukládá i `.dot` zdroj kombinovaného diagramu?

Při chybě vykreslení nebo nečekaném vzhledu lze zdroj ručně upravit nebo spustit dot sám. Je to pomůcka pro ladění.

5. Jak skript pozná název diagramu?

Z řádku digraph <jméno>. Pokud ho blok nemá, použije se graph_<pořadí>. Názvy souborů jsou tak předvídatelné.

6. Proč `maxBuffer` 10 MiB?

Výchozí limit výstupu execFileSync je malý. Velké SVG by ho překročilo a volání by selhalo s chybou.

7. Co se stane, když ve `SKILL.md` žádný dot blok není?

Skript to oznámí a skončí s kódem 0. Není to chyba; skill prostě diagram nemá.

8. Proč je skript ESM (`import`)?

Balíček package.json má "type": "module". Moderní syntax je jednotná s ostatními skripty a umožňuje použít import * as fs.

9. Proč `process.exit(1)` při chybějícím argumentu a příklady v nápovědě?

Chybné použití je chyba volajícího a má skončit nenulovým kódem. Příklady v nápovědě zkrátí učení.

Slovník pojmů (10)

DOT / Graphviz

Jazyk a nástroj pro popis a vykreslení grafů.

`digraph`

Orientovaný graf v DOT.

Dot block

Blok ``` `dot `` ve SKILL.md`.

`execFileSync`

Spuštění programu bez shellu s vstupem na stdin.

Cluster

Podgraf s rámečkem a popiskem (subgraph cluster_i).

`rankdir`

Směr rozvržení grafu (TB, LR).

`--combine`

Přepínač pro sloučení diagramů.

SVG

Vektorový obrázek, výstup dot -Tsvg.

`diagrams/`

Výstupní adresář uvnitř skillu.

`maxBuffer`

Maximální velikost výstupu procesu.

↑ nahoru

review-package (subagent-driven-development)

Vytvoří soubor s commit listem, stat souhrnem a diffem s rozšířeným kontextem, který reviewer přečte jedním voláním.

review-package PLAN_FILE BASE HEAD [OUTFILE] připraví review balíček: hlavičku, seznam commitů (git log --oneline), git diff --stat a celý diff s 10 řádky kontextu (-U10). Výsledek zapíše do souboru pojmenovaného podle rozsahu, např. review-<base7>..<head7>.diff, ve workspace plánu. Vypíše wrote <cesta>: N commit(s), M bytes, takže cesta se dostane k controlleru, ale obsah ne.

Skript ověří platnost BASE i HEAD a má range guards (exit 3): HEAD musí být potomkem BASE a rozsah nesmí být prázdný. Použití zaznamenaného BASE místo HEAD~1 zachová celé víc-commitové úkoly. Skript volá sdd-workspace přes bash, protože některé extraktory balíčků (Python zipfile) ztrácejí exec bit (#2040).

Zdrojový kód

skills/subagent-driven-development/scripts/review-package 54 řádků
#!/usr/bin/env bash
# Generate a review package: commit list, stat summary, and the net
# diff with extended context, written to a file the reviewer reads in one
# call. Using the recorded per-task BASE (not HEAD~1) keeps multi-commit
# tasks intact.
#
# Usage: review-package PLAN_FILE BASE HEAD [OUTFILE]
# Default OUTFILE: <repo-root>/.superpowers/sdd/<plan-basename>/review-<base7>..<head7>.diff
# (named per range, so a re-review after fixes gets a distinct fresh file).
set -euo pipefail

if [ $# -lt 3 ] || [ $# -gt 4 ]; then
  echo "usage: review-package PLAN_FILE BASE HEAD [OUTFILE]" >&2
  exit 2
fi

plan=$1
base=$2
head=$3
[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }

git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; }
git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; }

# Range guards (exit 3): a wrong-branch HEAD yields a range that is empty or
# not rooted at BASE; either would silently produce a bogus review package.
git merge-base --is-ancestor "$base" "$head" || { echo "HEAD is not a descendant of BASE: ${base}..${head}" >&2; exit 3; }
[ "$(git rev-list --count "${base}..${head}")" -gt 0 ] || { echo "empty commit range: ${base}..${head}" >&2; exit 3; }

if [ $# -eq 4 ]; then
  out=$4
else
  # Invoke via bash rather than direct exec: some extractors (Python zipfile)
  # strip Unix exec bits when unpacking marketplace packages (#2040).
  dir=$("${BASH:-bash}" "$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan")
  out="$dir/review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head").diff"
fi

{
  echo "# Review package: ${base}..${head}"
  echo
  echo "## Commits"
  git log --oneline "${base}..${head}"
  echo
  echo "## Files changed"
  git diff --stat "${base}..${head}"
  echo
  echo "## Diff"
  git diff -U10 "${base}..${head}"
} > "$out"

commits=$(git rev-list --count "${base}..${head}")
echo "wrote ${out}: ${commits} commit(s), $(wc -c < "$out" | tr -d ' ') bytes"

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se diff zapisuje do souboru a nevkládá do promptu?

Diff může být velký. Přes soubor jde jen cesta; controller nikdy nenačte obsah do vlastního kontextu a reviewer ho přečte jedním voláním. Šetří to kontext i náklady.

2. K čemu je rozšířený kontext `-U10`?

Reviewer pak nemusí otevírat změněné soubory zvlášť: kontextové řádky v diffu jsou téměř celý relevantní kód. Task reviewer prompt na to výslovně spoléhá.

3. Proč se používá BASE a ne `HEAD~1`?

Úkol může obsahovat více commitů. HEAD~1 by zachytil jen poslední. Zaznamenané BASE před začátkem úkolu zaručuje, že balíček pokrývá vše.

4. Co znamenají range guards a exit kód 3?

Ověřují, že HEAD je potomkem BASE a že rozsah není prázdný. Při omylu (špatná branch) by vznikl falešný, nesmyslný balíček; exit 3 to zastaví hlasitě.

5. Proč se název souboru odvozuje z rozsahu?

Re-review po opravách má jiný rozsah, takže dostane nový soubor a nepřepíše původní. Obě review zůstanou dohledatelná.

6. Proč se `sdd-workspace` volá přes `"${BASH:-bash}"` a ne přímo?

Marketplace balíčky rozbalené Python zipfile mohou ztratit exec bit. Spuštění přes bash funguje bez něj (viz poznámka #2040), takže skript není závislý na oprávněních.

7. Proč skript vypisuje jen počet commitů a velikost?

Controller potřebuje potvrzení a cestu, ne obsah. Krátký výstup šetří kontext.

8. Co se stane při chybějícím plánu?

Skript skončí s kódem 2 a hláškou „no such plan file“. Workspace se určuje podle plánu, takže bez něj nelze pokračovat.

Slovník pojmů (9)

Review package

Soubor s commit listem, statem a diffem pro reviewera.

BASE / HEAD

Začátek a konec reviewovaného rozsahu.

Range guard

Kontrola, že HEAD je potomek BASE a rozsah není prázdný (exit 3).

`git diff -U10`

Diff s deseti řádky kontextu okolo každé změny.

`git diff --stat`

Souhrn změněných souborů a počtů řádků.

Per-range file name

Název review-<base7>..<head7>.diff odlišuje různé rozsahy.

Workspace

Adresář artefaktů plánu, určený skriptem sdd-workspace.

Exec bit

Oprávnění ke spuštění souboru; některé extraktory ho ztrácejí.

Multi-commit task

Úkol s více commity; BASE zaručí, že se zahrnou všechny.

↑ nahoru

sdd-workspace (subagent-driven-development)

Určí a vytvoří adresář pro dočasné artefakty jednoho plánu a řeší kolize názvů pomocí markeru plan-path.

sdd-workspace PLAN_FILE vypíše absolutní cestu k adresáři .superpowers/sdd/<slug>/, kde SDD drží krátkodobé artefakty plánu: briefy úkolů, reporty implementátorů, review balíčky a ledger progress.md. Jeden adresář na plán zaručuje, že následný plán ve stejném working tree nepřečte ani nepřepíše cizí soubory.

Protože slugy (název souboru plánu) mohou kolidovat (docs/alpha/plan.md a docs/beta/plan.md), každý workspace obsahuje marker plan-path s cestou vlastnícího plánu (relativní v repozitáři, jinak absolutní). Při kolizi se použije slug doplněný názvem nadřazeného adresáře, případně počitadlem. Workspace bez markeru se adoptuje (zpětná kompatibilita). Adresář leží ve working tree, ne pod .git/, protože Claude Code .git/ chrání před zápisem agentů. Uvnitř je samonulující .gitignore (*), takže artefakty nejdou do git status ani do commitů.

Zdrojový kód

skills/subagent-driven-development/scripts/sdd-workspace 88 řádků
#!/usr/bin/env bash
# Resolve and ensure the working-tree directory SDD uses for one plan's
# short-lived artifacts: task briefs, implementer reports, review packages,
# and the progress ledger. Print the plan directory's absolute path.
#
# One directory per plan (.superpowers/sdd/<plan-basename>/) so a follow-up
# plan in the same working tree can never read or overwrite another plan's
# artifacts. A stale ledger misread as current progress makes controllers
# skip whole task sequences — plan-scoping removes that failure structurally.
#
# Basename slugs collide when two plans share a filename (docs/alpha/plan.md
# vs docs/beta/plan.md), so each workspace records its owning plan's path in
# a plan-path marker (repo-relative in-repo, absolute outside). A workspace
# owned by a different plan is skipped and the slug disambiguated with the
# plan's parent-directory name, then a counter. A workspace with no marker
# predates the marker scheme and is adopted for the current plan so in-flight
# workspaces keep resolving — which means the first collision on such a
# legacy workspace adopts instead of detecting; acceptable, marker-less
# workspaces age out as plans finish.
#
# The workspace lives in the working tree (not under .git/) because Claude Code
# treats .git/ as a protected path and denies agent writes there — which blocks
# an implementer subagent from writing its report file. A self-ignoring
# .gitignore at .superpowers/sdd/ keeps every plan's workspace out of
# `git status` and out of accidental commits without modifying any tracked file.
#
# Single source of truth for the workspace location, so task-brief and
# review-package cannot drift to different directories.
#
# Usage: sdd-workspace PLAN_FILE
set -euo pipefail

if [ $# -ne 1 ]; then
  echo "usage: sdd-workspace PLAN_FILE" >&2
  exit 2
fi

plan=$1
[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }

slug=$(basename "$plan" .md)
[ -n "$slug" ] && [ "$slug" != "." ] && [ "$slug" != ".." ] \
  || { echo "cannot derive a workspace name from: $plan" >&2; exit 2; }

# Physical path, spelled the way pwd -P spells the plan path below: on Git
# Bash, rev-parse prints C:/Users/... while pwd prints /c/Users/..., and the
# repo-relative marker check needs both in the same form.
root=$(CDPATH='' cd -- "$(git rev-parse --show-toplevel)" && pwd -P)
base="$root/.superpowers/sdd"

# Normalize the plan path (physical directory, so relative/absolute/../
# spellings of one plan compare equal) and express it as the marker value:
# repo-relative when the plan lives under the repo root, absolute otherwise.
plan_dir=$(CDPATH='' cd -- "$(dirname "$plan")" && pwd -P)
plan_abs="$plan_dir/$(basename "$plan")"
case "$plan_abs" in
  "$root"/*) plan_id=${plan_abs#"$root"/} ;;
  *)         plan_id=$plan_abs ;;
esac

# True when the workspace at $1 is (or becomes) this plan's: an existing
# marker must name this plan; a missing marker means a new workspace or a
# pre-marker legacy one, and either way the plan claims it by writing one.
owns() {
  if [ -e "$1/plan-path" ]; then
    [ "$(cat "$1/plan-path")" = "$plan_id" ]
  else
    mkdir -p "$1"
    printf '%s\n' "$plan_id" > "$1/plan-path"
  fi
}

dir="$base/$slug"
if ! owns "$dir"; then
  parent=$(basename "$plan_dir")
  dir="$base/$slug-$parent"
  if ! owns "$dir"; then
    n=2
    while ! owns "$base/$slug-$parent-$n"; do n=$((n + 1)); done
    dir="$base/$slug-$parent-$n"
  fi
fi

# Create-only: a repo may commit its own .gitignore here (e.g. to version
# progress.md ledgers); overwriting it would revert that on every run.
[ -e "$base/.gitignore" ] || printf '*\n' > "$base/.gitignore"
CDPATH='' cd -- "$dir" && pwd

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč jeden adresář na plán?

Zastaralý ledger z jiného plánu by controller mohl číst jako aktuální postup a přeskočit celé úkoly. Izolace po plánech tento typ chyby odstraní strukturálně.

2. K čemu je marker `plan-path`?

Rozlišuje workspace patřící různým plánům se stejným názvem souboru. Skript podle něj pozná, že adresář není jeho, a zvolí jiný název.

3. Proč se workspace neumisťuje do `.git/`?

Claude Code .git/ považuje za chráněnou cestu a zakazuje agentům psát. Implementátor by pak nemohl zapsat svůj report. Working tree tento problém nemá.

4. Jak se artefakty vyloučí z gitu bez úpravy sledovaných souborů?

Do .superpowers/sdd/ se vytvoří .gitignore s obsahem *. Ignoruje sám sebe i vše v adresáři. Vytváří se jen pokud neexistuje, aby se nepřepsal vlastní .gitignore repozitáře.

5. Proč se cesty normalizují přes `pwd -P`?

Různé zápisy téhož plánu (relativní, absolutní, s ../) se musí porovnat jako stejné. Na Git Bash navíc rev-parse a pwd píšou cestu jinak, takže obě musí mít stejný tvar.

6. Co se stane s workspace bez markeru?

Považuje se za starší a plán ho adoptuje zapsáním markeru. Tak se zachová funkčnost rozpracovaných workspaces. Cenou je, že první kolize na takovém adresáři se nezjistí.

7. Proč je skript jediným zdrojem pravdy o umístění?

task-brief a review-package ho volají, takže se nemohou rozejít a ukládat do různých adresářů.

8. Jak se řeší více kolizí?

Nejprve slug + rodičovský adresář, potom počitadlo (-2, -3…), dokud owns nenajde volný nebo vlastní adresář.

Slovník pojmů (9)

SDD workspace

Adresář .superpowers/sdd/<slug>/ s artefakty jednoho plánu.

Slug

Název odvozený z názvu souboru plánu bez .md.

`plan-path` marker

Soubor s cestou vlastnícího plánu v adresáři workspace.

Collision

Dva plány se stejným názvem souboru v různých adresářích.

Legacy workspace

Adresář bez markeru, který se adoptuje.

Self-ignoring `.gitignore`

Soubor s *, který ignoruje celý adresář včetně sebe.

Protected path

Cesta (.git/), do které agent nesmí zapisovat.

`owns`

Funkce rozhodující, zda workspace patří aktuálnímu plánu, případně ho nárokuje.

Physical path (`pwd -P`)

Cesta bez symlinků, vhodná k porovnání.

↑ nahoru

task-brief (subagent-driven-development)

Awk skript, který z plánu vyřízne celý text jednoho úkolu do souboru, aby se neprotahoval kontextem controlleru.

task-brief PLAN_FILE TASK_NUMBER [OUTFILE] přečte plán a do souboru task-<N>-brief.md zapíše kompletní text úkolu N: od nadpisu Task N po začátek dalšího nadpisu Task M. Implementátor pak úkol přečte jedním voláním a text nikdy neprochází kontextem controlleru.

Extrakci dělá awk, který ignoruje nadpisy uvnitř code fence (přepínač infence), takže ukázkový markdown v bloku kódu nezačne nový úkol. Regulár Task N([^0-9]|$) zabrání záměně Task 1 s Task 10. Pokud je výstup prázdný, skript končí kódem 3 s hláškou, že úkol nebyl nalezen. Výchozí cesta se získá z sdd-workspace.

Zdrojový kód

skills/subagent-driven-development/scripts/task-brief 44 řádků
#!/usr/bin/env bash
# Extract one task's full text from an implementation plan into a file the
# implementer reads in one call, so the task text never has to be pasted
# through the controller's context.
#
# Usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]
# Default OUTFILE: <repo-root>/.superpowers/sdd/<plan-basename>/task-<N>-brief.md
# (per plan and per worktree; concurrent runs of the SAME plan in the same
# working tree share it).
set -euo pipefail

if [ $# -lt 2 ] || [ $# -gt 3 ]; then
  echo "usage: task-brief PLAN_FILE TASK_NUMBER [OUTFILE]" >&2
  exit 2
fi

plan=$1
n=$2
[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }

if [ $# -eq 3 ]; then
  out=$3
else
  # Invoke via bash rather than direct exec: some extractors (Python zipfile)
  # strip Unix exec bits when unpacking marketplace packages (#2040).
  dir=$("${BASH:-bash}" "$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan")
  out="$dir/task-${n}-brief.md"
fi

awk -v n="$n" '
  /^```/ { infence = !infence }
  !infence && /^#+[ \t]+Task[ \t]+[0-9]+/ {
    intask = ($0 ~ ("^#+[ \t]+Task[ \t]+" n "([^0-9]|$)"))
  }
  intask { print }
' "$plan" > "$out"

if [ ! -s "$out" ]; then
  echo "task ${n} not found in ${plan} (no heading matching 'Task ${n}')" >&2
  exit 3
fi

echo "wrote ${out}: $(wc -l < "$out" | tr -d ' ') lines"

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se text úkolu neposílá controllerem do promptu?

Controller by ho musel nejdřív načíst do kontextu a pak znovu vypsat. U desítek úkolů je to velký objem. Soubor jde implementátorovi jako cesta a controller text nikdy nevidí.

2. Proč awk sleduje code fence?

Plán může obsahovat ukázkové bloky, ve kterých se vyskytují řádky typu ## Task 2. Bez sledování fence by skript v bloku kódu skončil nebo začal jiný úkol. Přepínač infence takové řádky ignoruje.

3. Jak se zabrání záměně `Task 1` a `Task 10`?

Regulární výraz vyžaduje, aby za číslem nebyla další číslice ([^0-9]|$). Bez toho by Task 1 zachytil i Task 10, Task 11…

4. Co se stane, když úkol v plánu není?

Výstupní soubor zůstane prázdný, skript to zkontroluje a skončí kódem 3 s textem „task N not found“. Implementátor tedy nedostane prázdný brief bez varování.

5. Proč jsou nadpisy hledány s libovolným počtem `#`?

Plány mohou používat různé úrovně nadpisů (##, ###). Vzor ^#+ je robustní vůči stylu plánu.

6. Proč se pracuje se souborem, který sdílí implementátor i reviewer?

Oba čtou stejné zadání. Reviewer může porovnat diff s přesně týmž textem, který viděl implementátor.

7. Proč se výchozí výstup odvozuje přes `sdd-workspace`?

Jedno místo určuje umístění všech artefaktů. Briefy tak neskončí v jiném adresáři než reporty a balíčky.

8. Co dělá poslední řádek `wrote ...: N lines`?

Je to strojově čitelný výstup. task-start z něj sedem vytahuje cestu.

Slovník pojmů (9)

Task brief

Soubor s textem jednoho úkolu pro implementátora.

Code fence

Blok kódu ohraničený ```; awk uvnitř nadpisy ignoruje.

`infence`

Proměnná awk, která se přepíná na každém řádku začínajícím ```.

`intask`

Proměnná, která je pravdivá, dokud se čte vybraný úkol.

Task heading

Nadpis ve tvaru # Task N … (libovolná úroveň).

Exit code 3

Úkol nenalezen.

OUTFILE

Volitelná cílová cesta; jinak se použije workspace.

Controller context

Kontext hlavního agenta; skript ho šetří.

Plan file

Markdown s úkoly vytvořený skillem writing-plans.

↑ nahoru

task-done (executing-plans)

Spustí testy úkolu, uloží celý výstup, vypíše konec a jen při úspěchu zapíše dokončení do ledgeru.

task-done PLAN_FILE TASK_NUMBER BASE -- TEST_COMMAND [ARGS...] uzavírá úkol při inline provádění plánu. Ověří, že BASE je platný commit, určí workspace (sdd-workspace), spustí zadaný testovací příkaz a celý výstup uloží do task-N-tests.log. Na terminál vypíše jen posledních pět řádků. Pokud příkaz selže, skript vypíše „Task N NOT recorded“ a skončí stejným exit kódem jako test; do ledgeru nic nezapíše.

Při úspěchu přidá do progress.md řádek Task N: complete (commits BASE..HEAD, tests: <příkaz> → <poslední řádek výstupu>). Příkaz se do ledgeru zapíše tak, jak by ho napsal člověk (argumenty s mezerami a speciálními znaky v apostrofech). Ledger je tedy důkaz, že úkol prošel testy, a nemůže vzniknout ručně bez úspěšného běhu.

Zdrojový kód

skills/executing-plans/scripts/task-done 53 řádků
#!/usr/bin/env bash
# Close one task of an inline plan execution in a single call: run the task's
# test command, keep its full output in the workspace, print the tail, and —
# only if the command succeeded — append the completion line to the ledger.
# A failing command records nothing: the task is not complete.
#
# Usage: task-done PLAN_FILE TASK_NUMBER BASE -- TEST_COMMAND [ARGS...]
#   BASE is the SHA task-start printed; the completion line records BASE..HEAD.
# Exit: the test command's exit status.
set -euo pipefail

if [ $# -lt 5 ] || [ "$4" != "--" ]; then
  echo "usage: task-done PLAN_FILE TASK_NUMBER BASE -- TEST_COMMAND [ARGS...]" >&2
  exit 2
fi

plan=$1
n=$2
base=$3
shift 4
sdd="$(cd "$(dirname "$0")/../../subagent-driven-development/scripts" && pwd)"

git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; }

dir=$("$sdd/sdd-workspace" "$plan")
log="$dir/task-${n}-tests.log"
ledger="$dir/progress.md"

# Render the command the way a person would type it, for the ledger line.
cmd=""
for a in "$@"; do
  case "$a" in
    *[[:space:]\"\;\|\&]*) cmd="$cmd '$a'" ;;
    *) cmd="$cmd $a" ;;
  esac
done
cmd=${cmd# }

rc=0
"$@" > "$log" 2>&1 || rc=$?

tail -n 5 "$log"
if [ "$rc" -ne 0 ]; then
  echo "task-done: test command exited $rc; Task $n NOT recorded (full output: $log)" >&2
  exit "$rc"
fi

last=$(grep -v '^[[:space:]]*$' "$log" | tail -n 1) || last="(no output)"
[ -f "$ledger" ] || printf '# SDD ledger — plan: %s\n' "$plan" > "$ledger"
line="Task $n: complete (commits $(git rev-parse --short=7 "$base")..$(git rev-parse --short=7 HEAD), tests: $cmd → $last)"
printf '%s\n' "$line" >> "$ledger"
echo "ledger: $line"

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč se do ledgeru zapíše dokončení jen při úspěchu testů?

Ledger slouží jako důvěryhodný záznam postupu. Pokud by se zapisovalo i při selhání, controller by mohl číst starý nebo nepravdivý stav a přeskočit celé sekvence úkolů. Selhání znamená „úkol není hotový“.

2. Proč se celý výstup ukládá do souboru a vypisuje jen pět řádků?

Plný výstup testů může být obrovský a plnil by kontext. Soubor je dohledatelný v případě potřeby, zatímco agent dostane jen to podstatné.

3. Proč skript vrací exit kód testovacího příkazu?

Volající (agent nebo skript) pozná, zda testy prošly, standardním způsobem. Skript nezakrývá ani nepřevádí výsledek.

4. Proč se `BASE` ověřuje pomocí `git rev-parse --verify`?

Špatný BASE by vedl k nesmyslnému rozsahu v ledgeru. Brzké odmítnutí s kódem 2 je levnější než zapsat chybný záznam.

5. K čemu je cyklus, který „renderuje“ příkaz?

Do ledgeru se příkaz zapisuje čitelně: argumenty s mezerami, uvozovkami nebo ;|& se obalí apostrofy. Čtenář ledgeru ho může zkopírovat a spustit.

6. Co zachytí řádek `last=$(grep -v '^[[:space:]]*$' ...)`?

Poslední neprázdný řádek výstupu (typicky „14 passing“). Dává ledgeru stručný důkaz výsledku bez přepisování celého logu.

7. Proč používá `"$@" > "$log" 2>&1 || rc=$?`?

Kombinace dovolí zachytit exit kód bez toho, aby set -e ukončil skript dříve, než se vypíše tail a zpráva. Výstup včetně chyb jde do logu.

8. Jak je zajištěno, že ledger existuje?

Pokud soubor chybí, skript ho vytvoří s hlavičkou obsahující cestu k plánu. Další úkoly se jen přidávají.

9. Proč jsou argumenty `--` povinné?

Oddělují parametry skriptu od testovacího příkazu, který může mít vlastní přepínače. Bez toho by nešlo jednoznačně určit, kde příkaz začíná.

Slovník pojmů (9)

Ledger (`progress.md`)

Soubor se záznamy o dokončených úkolech; zdroj pravdy o postupu.

Test log

task-N-tests.log s plným výstupem testovacího příkazu.

BASE..HEAD

Rozsah commitů úkolu zaznamenaný v ledgeru.

Exit status

Návratový kód příkazu. Skript ho předává dál.

`--` (oddělovač)

Odděluje argumenty skriptu od příkazu k spuštění.

Tail

Posledních pět řádků výstupu vypsaných na terminál.

`sdd-workspace`

Skript, který určí adresář s artefakty plánu.

`pipefail` / `set -e`

Pojistky shellu, které brání ignorování chyb.

Completion line

Řádek Task N: complete (...) v ledgeru.

↑ nahoru

task-start (executing-plans)

Jedním voláním vytáhne brief úkolu z plánu a zaznamená BASE commit, od kterého se bude úkol reviewovat.

Skript task-start PLAN_FILE TASK_NUMBER zahajuje jeden úkol při inline provádění plánu (agent plán provádí sám, bez subagentů). Dělá dvě věci: zavolá task-brief ze skillu subagent-driven-development, který vyřízne text úkolu do souboru ve sdíleném workspace, a vypíše brief: s cestou k tomuto souboru a base: s plným SHA aktuálního HEAD.

Důvod existence je zapsán v komentáři: v inline session je každé volání nástroje turn, který znovu čte celý kontext. Proto jedno volání místo dvou. Skript záměrně sdílí workspace s SDD, takže oba skilly pracují se stejnou strukturou souborů. Pokud task-brief nevypíše cestu, skript skončí s chybou místo tichého pokračování.

Zdrojový kód

skills/executing-plans/scripts/task-start 29 řádků
#!/usr/bin/env bash
# Begin one task of an inline plan execution in a single call: extract the
# task's brief (via subagent-driven-development's task-brief, so both skills
# share one workspace) and record BASE, the commit the task's review range is
# cut from. One tool call instead of two, because every call in an inline
# session is a turn that re-reads the whole context.
#
# Usage: task-start PLAN_FILE TASK_NUMBER
# Prints:
#   brief: <path to the task's brief file>
#   base:  <full SHA of HEAD>
set -euo pipefail

if [ $# -ne 2 ]; then
  echo "usage: task-start PLAN_FILE TASK_NUMBER" >&2
  exit 2
fi

plan=$1
n=$2
sdd="$(cd "$(dirname "$0")/../../subagent-driven-development/scripts" && pwd)"

out=$("$sdd/task-brief" "$plan" "$n")
brief=$(printf '%s\n' "$out" | sed -n 's/^wrote \(.*\): [0-9][0-9]* lines$/\1/p')
[ -n "$brief" ] || { echo "task-brief did not report a path: $out" >&2; exit 1; }

echo "brief: $brief"
echo "base: $(git rev-parse HEAD)"

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč skript dělá dvě věci v jednom volání?

Každé volání nástroje v inline session je turn, který znovu načítá celý kontext. Sloučení brief + base do jednoho volání ušetří jeden turn, a tedy tokeny i čas, bez ztráty funkce.

2. K čemu je zapamatovaný BASE?

BASE je commit před zahájením úkolu. Z rozsahu BASE..HEAD se později sestaví review i záznam v ledgeru. Použití konkrétního SHA je spolehlivější než HEAD~1, protože úkol může mít víc commitů.

3. Proč skript volá `task-brief` z jiného skillu a nemá vlastní extrakci?

Jediný zdroj logiky a jediný workspace. Kdyby obě verze žila zvlášť, rozešly by se a briefy by končily v různých adresářích.

4. Jak skript zjistí cestu briefu?

Z výstupu task-brief (wrote <cesta>: N lines) ji vytáhne sed. Pokud se vzorec nenajde, skript skončí chybou „task-brief did not report a path“, takže se nepokračuje s prázdnou cestou.

5. Proč `set -euo pipefail`?

-e ukončí skript při chybě, -u při nedefinované proměnné, pipefail zachytí chybu uprostřed pipeline. Společně brání tichému selhání, které by pak vedlo k úkolu bez briefu.

6. Proč je exit kód 2 pro špatné argumenty?

Konvence: 2 znamená chybné použití. Odlišuje chybu volání od chyby běhu (1) a snadno se odliší ve skriptech.

7. Proč je výstup ve tvaru `klíč: hodnota`?

Je čitelný člověku i agentovi a dá se jednoduše zpracovat (brief: a base: řádky). Agent z něj hned získá dvě informace, které potřebuje dál.

8. Proč skript bezpečně volá `sdd` přes `cd` a `pwd`?

Cesta se vypočítá relativně k umístění skriptu, takže funguje nezávisle na aktuálním adresáři.

Slovník pojmů (9)

Inline execution

Provádění plánu přímo v aktuální session bez subagentů.

Task brief

Soubor s plným textem jednoho úkolu z plánu.

BASE

SHA commitu, ze kterého se počítá rozsah review úkolu.

Workspace

Adresář .superpowers/sdd/<plan>/ s briefy, reporty a ledgerem.

`task-brief`

Skript SDD, který z plánu vyřízne úkol do souboru.

HEAD

Aktuální commit; vypisuje se jako plné SHA.

Turn

Jedno kolo volání nástroje. V inline session znovu čte celý kontext.

`set -euo pipefail`

Přísný režim shellu: ukončit při chybě, nedefinované proměnné a chybě v pipeline.

Exit code 2

Konvence pro chybné použití skriptu.

↑ nahoru

Ukázky kódu

condition-based-waiting (ukázka kódu v TypeScriptu)

Tři pollingové funkce, které místo „hádání“ pevného timeoutu čekají na podmínku; z 60 % na 100 % spolehlivosti testů.

Příklad ukazuje, jak opravit flaky testy: místo await sleep(300) („doufám, že se nástroje za 300 ms spustí“) test čeká na podmínku. Soubor obsahuje tři funkce: waitForEvent (první událost daného typu), waitForEventCount (až bude N událostí) a waitForEventMatch (událost vyhovující predikátu s popisem pro chybovou zprávu). Každá vrací Promise, opakuje kontrolu každých 10 ms a po vypršení timeoutMs (výchozí 5000) odmítne s jasnou chybou, např. „Timeout waiting for 2 TOOL_RESULT events after 5000ms (got 1)“.

Komentář na konci porovnává PŘED (dvě libovolné pauzy, test padá náhodně) a PO (čekání na TOOL_CALL a TOOL_RESULT) a uvádí výsledek: pass rate 60 % → 100 %, o 40 % rychlejší běh. Příklad pochází z opravy 15 flaky testů v infrastruktuře Lace.

Zdrojový kód

skills/systematic-debugging/condition-based-waiting-example.ts 159 řádků
// Complete implementation of condition-based waiting utilities
// From: Lace test infrastructure improvements (2025-10-03)
// Context: Fixed 15 flaky tests by replacing arbitrary timeouts

import type { ThreadManager } from '~/threads/thread-manager';
import type { LaceEvent, LaceEventType } from '~/threads/types';

/**
 * Wait for a specific event type to appear in thread
 *
 * @param threadManager - The thread manager to query
 * @param threadId - Thread to check for events
 * @param eventType - Type of event to wait for
 * @param timeoutMs - Maximum time to wait (default 5000ms)
 * @returns Promise resolving to the first matching event
 *
 * Example:
 *   await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT');
 */
export function waitForEvent(
  threadManager: ThreadManager,
  threadId: string,
  eventType: LaceEventType,
  timeoutMs = 5000
): Promise<LaceEvent> {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();

    const check = () => {
      const events = threadManager.getEvents(threadId);
      const event = events.find((e) => e.type === eventType);

      if (event) {
        resolve(event);
      } else if (Date.now() - startTime > timeoutMs) {
        reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`));
      } else {
        setTimeout(check, 10); // Poll every 10ms for efficiency
      }
    };

    check();
  });
}

/**
 * Wait for a specific number of events of a given type
 *
 * @param threadManager - The thread manager to query
 * @param threadId - Thread to check for events
 * @param eventType - Type of event to wait for
 * @param count - Number of events to wait for
 * @param timeoutMs - Maximum time to wait (default 5000ms)
 * @returns Promise resolving to all matching events once count is reached
 *
 * Example:
 *   // Wait for 2 AGENT_MESSAGE events (initial response + continuation)
 *   await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2);
 */
export function waitForEventCount(
  threadManager: ThreadManager,
  threadId: string,
  eventType: LaceEventType,
  count: number,
  timeoutMs = 5000
): Promise<LaceEvent[]> {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();

    const check = () => {
      const events = threadManager.getEvents(threadId);
      const matchingEvents = events.filter((e) => e.type === eventType);

      if (matchingEvents.length >= count) {
        resolve(matchingEvents);
      } else if (Date.now() - startTime > timeoutMs) {
        reject(
          new Error(
            `Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})`
          )
        );
      } else {
        setTimeout(check, 10);
      }
    };

    check();
  });
}

/**
 * Wait for an event matching a custom predicate
 * Useful when you need to check event data, not just type
 *
 * @param threadManager - The thread manager to query
 * @param threadId - Thread to check for events
 * @param predicate - Function that returns true when event matches
 * @param description - Human-readable description for error messages
 * @param timeoutMs - Maximum time to wait (default 5000ms)
 * @returns Promise resolving to the first matching event
 *
 * Example:
 *   // Wait for TOOL_RESULT with specific ID
 *   await waitForEventMatch(
 *     threadManager,
 *     agentThreadId,
 *     (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123',
 *     'TOOL_RESULT with id=call_123'
 *   );
 */
export function waitForEventMatch(
  threadManager: ThreadManager,
  threadId: string,
  predicate: (event: LaceEvent) => boolean,
  description: string,
  timeoutMs = 5000
): Promise<LaceEvent> {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();

    const check = () => {
      const events = threadManager.getEvents(threadId);
      const event = events.find(predicate);

      if (event) {
        resolve(event);
      } else if (Date.now() - startTime > timeoutMs) {
        reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`));
      } else {
        setTimeout(check, 10);
      }
    };

    check();
  });
}

// Usage example from actual debugging session:
//
// BEFORE (flaky):
// ---------------
// const messagePromise = agent.sendMessage('Execute tools');
// await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms
// agent.abort();
// await messagePromise;
// await new Promise(r => setTimeout(r, 50));  // Hope results arrive in 50ms
// expect(toolResults.length).toBe(2);         // Fails randomly
//
// AFTER (reliable):
// ----------------
// const messagePromise = agent.sendMessage('Execute tools');
// await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start
// agent.abort();
// await messagePromise;
// await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results
// expect(toolResults.length).toBe(2); // Always succeeds
//
// Result: 60% pass rate → 100%, 40% faster execution

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč jsou pevné timeouty špatné řešení?

Hádají dobu, kterou operace potřebuje. Na pomalejším stroji nestačí (test padá), na rychlém zbytečně zdržují. Čekání na podmínku skončí v okamžiku, kdy je splněna, a je tedy zároveň spolehlivé i rychlé.

2. Proč se kontroluje každých 10 ms a ne 1 ms nebo 1 s?

10 ms je kompromis: dost často pro rychlou reakci, ale bez zbytečné zátěže procesoru. Komentář „Poll every 10ms for efficiency“ to zdůvodňuje.

3. K čemu je timeout, když se čeká na podmínku?

Pokud se podmínka nikdy nesplní, test by visel navždy. Timeout garantuje konec a produkuje jasnou chybovou zprávu místo záhadného zablokování.

4. Proč chybová zpráva uvádí „got N“?

waitForEventCount ukáže, kolik událostí skutečně dorazilo. Diagnostika je okamžitá: víme, zda chybí všechny, nebo jen jedna.

5. K čemu je parametr `description` ve `waitForEventMatch`?

Predikát je funkce, kterou nelze vypsat. Popis („TOOL_RESULT with id=call_123“) se objeví v chybě, aby bylo zřejmé, na co se čekalo.

6. Proč `setTimeout(check, 10)` místo `setInterval`?

Další kontrola se naplánuje až po dokončení předchozí, takže se nemohou překrývat. Po splnění podmínky se plánování zastaví (resolve) a nic nezůstává běžet.

7. Proč se funkce vracejí jako Promise?

Testy mohou await. Kód je lineární a čitelný, zatímco asynchronní čekání se děje uvnitř.

8. Proč test nově čeká na `TOOL_CALL` před `agent.abort()`?

Abort má smysl až když nástroje opravdu běží. Čekání na událost zaručí, že je test ve správném stavu, a ne že uplynul nějaký čas.

9. Jaká je souvislost se systematic-debugging?

Tento příklad je ukázka řešení nalezené kořenové příčiny: flaky test není problém testu, ale špatného předpokladu o časování. Skill učí nahradit „tipování“ ověřitelnou podmínkou.

Slovník pojmů (10)

Flaky test

Test, který občas projde a občas selže bez změny kódu.

Condition-based waiting

Čekání na splnění podmínky místo pevné doby.

Polling

Opakovaná kontrola stavu v intervalu (zde 10 ms).

Timeout

Maximální doba čekání; po jejím uplynutí se Promise odmítne.

Predicate

Funkce vracející true, když událost vyhovuje.

`waitForEvent`

Čeká na první událost daného typu.

`waitForEventCount`

Čeká na N událostí daného typu.

`waitForEventMatch`

Čeká na událost podle predikátu s popisem do chyby.

Race condition

Chyba závislá na časování dvou operací; pevné pauzy ji jen maskují.

Pass rate

Podíl úspěšných běhů; zde 60 % → 100 %.

↑ nahoru

Testy

Testy brainstorm serveru: autentizace a branding

Bezpečnostní testy klíče relace (403, cookie, Origin, hlavičky) a testy brandingu včetně vypnutí telemetrie.

auth.test.js ověřuje, že companion server nelze číst ani zneužít bez klíče relace. Server je dostupný z každé lokální záložky prohlížeče (loopback) a při --host 0.0.0.0 i vzdáleně; proto každý endpoint chrání ?key= nebo cookie. Testy kontrolují: GET / bez klíče nebo se špatným klíčem → 403 (i s platnou cookie, pokud je query klíč špatný), 403 stránka zmiňuje „coding agent“, platný klíč vrátí bootstrap místo obsahu a nastaví HttpOnly SameSite=Strict cookie, /files bez klíče → 403, WebSocket upgrade bez klíče selže, s cookie a stejným Origin projde, s cross-origin Origin je odmítnut, a null payload po autentizovaném WS server nezhroutí. Všechny odpovědi musí mít hlavičky snižující únik a proti zarámování.

branding.test.js kontroluje, že obrazovky nesou verzované logo Prime Radiant, že balíčkovaný Codex plugin čte verzi z manifestu a že proměnné SUPERPOWERS_DISABLE_TELEMETRY, DISABLE_TELEMETRY a CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC vypnou vzdálený obrázek, ale ponechají lokální branding.

Zdrojový kód

tests/brainstorm-server/auth.test.js 313 řádků
/**
 * Security tests for the brainstorm server's per-session key.
 *
 * The companion server is reachable by any local browser tab (default loopback
 * bind) and by any host that can route to it (remote `--host 0.0.0.0` bind).
 * A per-session secret key gates every endpoint so that neither a browser
 * confused-deputy nor a direct remote client can read screens/files or inject
 * events into state/events (prompt injection into a live agent session).
 *
 * Auth = a valid `?key=<token>` query param OR a valid session cookie.
 *
 * Uses the `ws` npm package as a test client (test-only dependency).
 */

const { spawn } = require('child_process');
const http = require('http');
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const assert = require('assert');

const SERVER_PATH = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');
const TEST_PORT = 3335;
const TEST_DIR = '/tmp/brainstorm-auth-test';
const CONTENT_DIR = path.join(TEST_DIR, 'content');
const TOKEN = 'testtoken-0123456789abcdef0123456789abcdef';
const COOKIE_NAME = `brainstorm-key-${TEST_PORT}`;
const EXPECTED_SECURITY_HEADERS = {
  'referrer-policy': 'no-referrer',
  'cache-control': 'no-store',
  'x-frame-options': 'DENY',
  'content-security-policy': "frame-ancestors 'none'",
  'cross-origin-resource-policy': 'same-origin'
};

function cleanup() {
  if (fs.existsSync(TEST_DIR)) fs.rmSync(TEST_DIR, { recursive: true });
}

async function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Raw HTTP GET with optional key query and Cookie header.
function get(pathname, { key, cookie } = {}) {
  const url = `http://localhost:${TEST_PORT}${pathname}` + (key !== undefined ? `?key=${key}` : '');
  const headers = {};
  if (cookie) headers['Cookie'] = cookie;
  return new Promise((resolve, reject) => {
    http.get(url, { headers }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: data }));
    }).on('error', reject);
  });
}

// Try to open a WebSocket; resolve 'opened' or 'rejected'.
function wsConnect({ key, cookie, origin } = {}) {
  const url = `ws://localhost:${TEST_PORT}/` + (key !== undefined ? `?key=${key}` : '');
  const headers = {};
  if (cookie) headers['Cookie'] = cookie;
  if (origin) headers['Origin'] = origin;
  const opts = Object.keys(headers).length ? { headers } : {};
  const ws = new WebSocket(url, opts);
  return new Promise((resolve) => {
    let settled = false;
    const done = (outcome) => { if (!settled) { settled = true; resolve({ outcome, ws }); } };
    ws.on('open', () => done('opened'));
    ws.on('error', () => done('rejected'));
    ws.on('close', () => done('rejected'));
    setTimeout(() => done('rejected'), 1500);
  });
}

function startServer() {
  return spawn('node', [SERVER_PATH], {
    env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_DIR: TEST_DIR, BRAINSTORM_TOKEN: TOKEN }
  });
}

function assertSecurityHeaders(headers) {
  for (const [name, value] of Object.entries(EXPECTED_SECURITY_HEADERS)) {
    assert.strictEqual(headers[name], value, `${name} should be ${value}`);
  }
}

function runBootstrapScript(html, sessionStorage) {
  const match = html.match(/<script>\n([\s\S]*?)\n<\/script>/);
  assert(match, 'bootstrap response should contain a script block');
  const replacements = [];
  const location = { replace(url) { replacements.push(url); } };
  new Function('sessionStorage', 'location', match[1])(sessionStorage, location);
  return replacements;
}

async function waitForServer(server) {
  let stdout = '', stderr = '';
  return new Promise((resolve, reject) => {
    server.stdout.on('data', (d) => {
      stdout += d.toString();
      if (stdout.includes('server-started')) resolve({ stdout });
    });
    server.stderr.on('data', (d) => { stderr += d.toString(); });
    server.on('error', reject);
    setTimeout(() => reject(new Error(`Server didn't start. stderr: ${stderr}`)), 5000);
  });
}

function serverStartedMessage(out) {
  const line = out.trim().split('\n').find(l => l.includes('server-started'));
  assert(line, 'server-started JSON should be present');
  return JSON.parse(line);
}

function assertStartedOnExpectedPort(out) {
  const msg = serverStartedMessage(out);
  assert.strictEqual(
    msg.port,
    TEST_PORT,
    `auth.test.js expected fixed port ${TEST_PORT}, got ${msg.port}; fixed-port tests must not run through fallback`
  );
  return msg;
}

async function runTests() {
  cleanup();
  fs.mkdirSync(CONTENT_DIR, { recursive: true });
  fs.writeFileSync(path.join(CONTENT_DIR, 'screen.html'), '<h2>Secret screen</h2>');
  fs.writeFileSync(path.join(CONTENT_DIR, 'asset.txt'), 'secret asset');

  const server = startServer();
  let stdoutAccum = '';
  server.stdout.on('data', (d) => { stdoutAccum += d.toString(); });

  let passed = 0, failed = 0;
  async function test(name, fn) {
    try { await fn(); console.log(`  PASS: ${name}`); passed++; }
    catch (e) { console.log(`  FAIL: ${name}`); console.log(`    ${e.message}`); failed++; }
  }

  try {
    const { stdout: initialStdout } = await waitForServer(server);
    assertStartedOnExpectedPort(initialStdout);

    console.log('\n--- Startup URL ---');

    await test('server-started url includes the session key', () => {
      const msg = serverStartedMessage(initialStdout);
      assert(msg.url.includes(`key=${TOKEN}`), `url should carry the key, got: ${msg.url}`);
    });

    console.log('\n--- HTTP / gate ---');

    await test('GET / without key is rejected with 403', async () => {
      const res = await get('/');
      assert.strictEqual(res.status, 403, 'no-key request must be 403');
    });

    await test('403 page names "coding agent" and the key', async () => {
      const res = await get('/');
      assert(/coding agent/i.test(res.body), '403 body should reference the coding agent');
      assert(/key/i.test(res.body), '403 body should mention the key');
    });

    await test('403 responses include leak-reduction and anti-framing headers', async () => {
      const res = await get('/');
      assert.strictEqual(res.status, 403);
      assertSecurityHeaders(res.headers);
    });

    await test('GET / with wrong key is rejected with 403', async () => {
      const res = await get('/', { key: 'wrong-token' });
      assert.strictEqual(res.status, 403);
    });

    await test('GET / with wrong key and valid cookie is rejected with 403', async () => {
      const res = await get('/', { key: 'wrong-token', cookie: `${COOKIE_NAME}=${TOKEN}` });
      assert.strictEqual(res.status, 403, 'explicit wrong query key must not fall back to cookie auth');
    });

    await test('GET / with valid query returns bootstrap instead of screen content', async () => {
      const res = await get('/', { key: TOKEN });
      assert.strictEqual(res.status, 200);
      assert(res.body.includes('sessionStorage'), 'bootstrap should store the session key in tab storage');
      assert(res.body.includes('location.replace'), 'bootstrap should navigate to the bare root URL');
      assert(!res.body.includes('Secret screen'), 'bootstrap must not serve screen HTML at the keyed URL');
    });

    await test('bootstrap strips the key URL even when sessionStorage write fails', async () => {
      const res = await get('/', { key: TOKEN });
      assert.strictEqual(res.status, 200);
      let replacements;
      assert.doesNotThrow(() => {
        replacements = runBootstrapScript(res.body, {
        setItem() { throw new Error('storage blocked'); }
        });
      });
      assert.deepStrictEqual(replacements, ['/']);
    });

    await test('HTML responses include leak-reduction and anti-framing headers', async () => {
      const res = await get('/', { key: TOKEN });
      assert.strictEqual(res.status, 200);
      assertSecurityHeaders(res.headers);
    });

    await test('valid key load sets an HttpOnly SameSite=Strict cookie', async () => {
      const res = await get('/', { key: TOKEN });
      const setCookie = (res.headers['set-cookie'] || []).join('; ');
      assert(setCookie.includes(`${COOKIE_NAME}=${TOKEN}`), `should set ${COOKIE_NAME}`);
      assert(/HttpOnly/i.test(setCookie), 'cookie should be HttpOnly');
      assert(/SameSite=Strict/i.test(setCookie), 'cookie should be SameSite=Strict');
    });

    await test('GET / with valid cookie (no query key) serves the screen', async () => {
      const res = await get('/', { cookie: `${COOKIE_NAME}=${TOKEN}` });
      assert.strictEqual(res.status, 200);
      assert(res.body.includes('Secret screen'), 'cookie-authenticated bare root should serve the screen');
      assert(!res.body.includes("location.replace('/');"), 'bare screen response should not be the bootstrap page');
    });

    console.log('\n--- HTTP /files gate ---');

    await test('GET /files without key is rejected with 403', async () => {
      const res = await get('/files/asset.txt');
      assert.strictEqual(res.status, 403);
    });

    await test('GET /files with valid key serves the file', async () => {
      const res = await get('/files/asset.txt', { key: TOKEN });
      assert.strictEqual(res.status, 200);
      assert(res.body.includes('secret asset'));
    });

    await test('/files responses include leak-reduction and anti-framing headers', async () => {
      const res = await get('/files/asset.txt', { key: TOKEN });
      assert.strictEqual(res.status, 200);
      assertSecurityHeaders(res.headers);
    });

    console.log('\n--- WebSocket gate ---');

    await test('WS upgrade without key is rejected', async () => {
      const { outcome, ws } = await wsConnect();
      ws.close();
      assert.strictEqual(outcome, 'rejected', 'unauthenticated WS must not open');
    });

    await test('WS upgrade with valid key opens', async () => {
      const { outcome, ws } = await wsConnect({ key: TOKEN });
      ws.close();
      assert.strictEqual(outcome, 'opened');
    });

    await test('WS upgrade with valid cookie opens', async () => {
      const { outcome, ws } = await wsConnect({ cookie: `${COOKIE_NAME}=${TOKEN}` });
      ws.close();
      assert.strictEqual(outcome, 'opened');
    });

    await test('WS upgrade with valid cookie and same-origin Origin opens', async () => {
      const { outcome, ws } = await wsConnect({
        cookie: `${COOKIE_NAME}=${TOKEN}`,
        origin: `http://localhost:${TEST_PORT}`
      });
      ws.close();
      assert.strictEqual(outcome, 'opened');
    });

    await test('WS upgrade with valid cookie but cross-origin Origin is rejected', async () => {
      const eventsFile = path.join(TEST_DIR, 'state', 'events');
      if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);

      const { outcome, ws } = await wsConnect({
        cookie: `${COOKIE_NAME}=${TOKEN}`,
        origin: 'http://localhost:9999'
      });
      if (outcome === 'opened') {
        ws.send(JSON.stringify({ type: 'choice', choice: 'attacker-injected', text: 'local attacker probe' }));
        await sleep(300);
      }
      ws.close();

      assert.strictEqual(outcome, 'rejected', 'cross-origin browser WS must not open even with cookie');
      assert(!fs.existsSync(eventsFile), 'cross-origin WS must not write state/events');
    });

    console.log('\n--- Robustness (A3) ---');

    await test('null payload over an authed WS does not crash the server', async () => {
      const { ws } = await wsConnect({ key: TOKEN });
      ws.send('null');
      await sleep(300);
      const res = await get('/', { key: TOKEN });
      assert.strictEqual(res.status, 200, 'server must still respond after null payload');
      ws.close();
    });

    console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
    if (failed > 0) {
      process.exitCode = 1;
      return;
    }
  } finally {
    server.kill();
    await sleep(100);
    cleanup();
  }
}

runTests().catch(err => { console.error('Test failed:', err); process.exit(1); });
tests/brainstorm-server/branding.test.js 345 řádků
/**
 * Tests for the visual companion's Superpowers/Prime Radiant branding.
 */

const { spawn } = require('child_process');
const http = require('http');
const fs = require('fs');
const path = require('path');
const assert = require('assert');

const REPO_ROOT = path.join(__dirname, '../..');
const SERVER_PATH = path.join(REPO_ROOT, 'skills/brainstorming/scripts/server.cjs');
const PACKAGE_VERSION = JSON.parse(
  fs.readFileSync(path.join(REPO_ROOT, 'package.json'), 'utf-8')
).version;
const TOKEN = 'testtoken-branding-0123456789abcdef';
const ASSET_URL = 'https://primeradiant.com/brand/superpowers-visual-brainstorming-logo.png';

function cleanup(dir) {
  if (fs.existsSync(dir)) {
    fs.rmSync(dir, { recursive: true });
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function startServer({ port, dir, env = {}, serverPath = SERVER_PATH }) {
  cleanup(dir);
  return spawn('node', [serverPath], {
    env: {
      ...process.env,
      BRAINSTORM_PORT: String(port),
      BRAINSTORM_DIR: dir,
      BRAINSTORM_TOKEN: TOKEN,
      ...env
    }
  });
}

function waitForServer(server) {
  let stdout = '';
  let stderr = '';

  return new Promise((resolve, reject) => {
    const timeout = setTimeout(() => reject(new Error(`Server did not start. stderr: ${stderr}`)), 5000);
    server.stdout.on('data', (data) => {
      stdout += data.toString();
      if (stdout.includes('server-started')) {
        clearTimeout(timeout);
        resolve();
      }
    });
    server.stderr.on('data', (data) => { stderr += data.toString(); });
    server.on('error', reject);
  });
}

function fetchHtml(port) {
  return new Promise((resolve, reject) => {
    const headers = { Cookie: `brainstorm-key-${port}=${TOKEN}` };
    http.get(`http://localhost:${port}/`, { headers }, (res) => {
      let body = '';
      res.on('data', chunk => { body += chunk; });
      res.on('end', () => resolve(body));
    }).on('error', reject);
  });
}

function writeFragment(dir) {
  const contentDir = path.join(dir, 'content');
  fs.mkdirSync(contentDir, { recursive: true });
  fs.writeFileSync(path.join(contentDir, 'screen.html'), '<h2>Pick a layout</h2>');
}

function createPackagedServerFixture(version) {
  const root = fs.mkdtempSync(path.join('/tmp', 'superpowers-packaged-server-'));
  const scriptDir = path.join(root, 'skills/brainstorming/scripts');
  fs.cpSync(path.join(REPO_ROOT, 'skills/brainstorming/scripts'), scriptDir, { recursive: true });
  fs.mkdirSync(path.join(root, '.codex-plugin'), { recursive: true });
  fs.writeFileSync(
    path.join(root, '.codex-plugin/plugin.json'),
    JSON.stringify({ name: 'superpowers', version }, null, 2)
  );
  return {
    root,
    serverPath: path.join(scriptDir, 'server.cjs')
  };
}

async function withServer(options, fn) {
  const server = startServer(options);
  try {
    await waitForServer(server);
    await fn();
  } finally {
    if (server.exitCode === null && server.signalCode === null) {
      server.kill();
      await new Promise(resolve => server.once('exit', resolve));
    }
    await sleep(100);
    cleanup(options.dir);
  }
}

let passed = 0;
let failed = 0;

async function test(name, fn) {
  try {
    await fn();
    console.log(`  PASS: ${name}`);
    passed++;
  } catch (e) {
    console.log(`  FAIL: ${name}`);
    console.log(`    ${e.message}`);
    failed++;
  }
}

function assertBrandedWithLogo(html, version = PACKAGE_VERSION) {
  assert(
    html.includes(`Superpowers v${version}`),
    'branding text should include dynamic package version'
  );
  assert(
    !html.includes(`Superpowers v${version} by`),
    'branding text should not include "by" when the logo is visible'
  );
  assert(
    /<img class="brand-logo"[^>]*>\s*<span class="brand-copy">Superpowers v/.test(html),
    'visible logo should appear before the Superpowers version text'
  );
  assert(
    /\.brand a\s*\{[^}]*line-height:\s*1/i.test(html),
    'brand row should align the logo and version text by their visual height'
  );
  assert(
    /\.brand a\s*\{[^}]*gap:\s*0\.5rem/i.test(html),
    'brand row should keep the logo and version text close together'
  );
  assert(
    /\.brand a\s*\{[^}]*max-width:\s*100%/i.test(html),
    'brand link should be constrained so it cannot overlap the status column'
  );
  assert(
    /\.brand\s*\{[^}]*line-height:\s*1/i.test(html),
    'brand wrapper should not inherit the page line height'
  );
  assert(
    /\.brand\s*\{[^}]*overflow:\s*hidden/i.test(html),
    'brand wrapper should clip before it reaches the status column'
  );
}

function assertBrandedFallbackText(html, version = PACKAGE_VERSION) {
  assert(
    html.includes(`Prime Radiant Superpowers v${version}`),
    'disabled telemetry should keep plain text Prime Radiant/Superpowers branding'
  );
}

function assertTelemetryImage(html, version = PACKAGE_VERSION) {
  const expectedUrl = `${ASSET_URL}?v=${encodeURIComponent(version)}`;
  assert(html.includes(`src="${expectedUrl}"`), 'remote image should use the dedicated main-domain asset with only v=');
  assert(!html.includes('event='), 'remote image URL must not include event=');
  assert(!html.includes('surface='), 'remote image URL must not include surface=');
  assert(!html.includes('launch_id='), 'remote image URL must not include launch_id=');
  assert(!html.includes('lid='), 'remote image URL must not include lid=');
}

function assertLogoKeepsTransparentBackground(html) {
  assert(
    /\.brand-logo\s*\{[^}]*height:\s*1em/i.test(html),
    'logo should match the surrounding brand text size'
  );
  assert(
    /\.brand-logo\s*\{[^}]*display:\s*block/i.test(html),
    'logo should not reserve inline-image descender space'
  );
  assert(
    /\.brand-copy\s*\{[^}]*line-height:\s*1/i.test(html),
    'version text should use the same compact line height as the logo'
  );
  assert(
    /\.brand-copy\s*\{[^}]*min-width:\s*0/i.test(html),
    'version text should be allowed to shrink inside the brand row'
  );
  assert(
    /\.brand-copy\s*\{[^}]*transform:\s*translateY\(-1px\)/i.test(html),
    'version text should compensate for bottom padding inside the logo asset'
  );
  assert(
    /\.brand-logo\s*\{[^}]*filter:\s*invert\(1\)/i.test(html),
    'white logo asset should invert on light backgrounds'
  );
  assert(
    !/\.brand-logo\s*\{[^}]*background:/i.test(html),
    'logo should keep its transparent background'
  );
  assert(
    !/\.brand-logo\s*\{[^}]*padding:/i.test(html),
    'logo should not rely on a padded backing'
  );
}

function assertFramedLogoSupportsDarkTheme(html) {
  assert(
    /@media\s*\(prefers-color-scheme:\s*dark\)[\s\S]*\.brand-logo\s*\{[^}]*filter:\s*none/i.test(html),
    'framed screens should leave the white logo unfiltered in dark mode'
  );
}

function assertFramedScreenUsesBrandHeader(html) {
  const logoCount = (html.match(/class="brand-logo"/g) || []).length;
  assert.strictEqual(logoCount, 1, 'framed screens should render the logo only in the header');
  assert(!html.includes('<div class="indicator-bar">'), 'framed screens should not render footer chrome');
  assert(
    /<div class="header">[\s\S]*<div class="brand">[\s\S]*<div class="status">Connecting…<\/div>/.test(html),
    'header should contain branding and connection status'
  );
  assert(!html.includes('id="indicator-text"'), 'header should not render the selection indicator text');
  assert(!html.includes('Click an option above'), 'header should not render the selection instruction');
}

function assertHeaderAvoidsNarrowOverlap(html) {
  assert(
    /grid-template-columns:\s*minmax\(0,\s*1fr\)\s*auto/i.test(html),
    'header should allocate shrinkable space to branding before the status column'
  );
  assert(
    /\.header \.status\s*\{[^}]*grid-column:\s*2/i.test(html),
    'status should live in the final fixed-width grid column'
  );
  assert(
    /\.header \.brand\s*\{[^}]*width:\s*100%/i.test(html),
    'header brand should fill its grid track so overflow clipping prevents overlap'
  );
}

async function main() {
  console.log('\n--- Visual Companion Branding ---');

  await test('framed screens render versioned Prime Radiant logo by default', async () => {
    const port = 3451;
    const dir = '/tmp/brainstorm-branding-default';
    await withServer({ port, dir }, async () => {
      writeFragment(dir);
      await sleep(300);
      const html = await fetchHtml(port);
      assertBrandedWithLogo(html);
      assertTelemetryImage(html);
      assertLogoKeepsTransparentBackground(html);
      assertFramedLogoSupportsDarkTheme(html);
      assertFramedScreenUsesBrandHeader(html);
      assertHeaderAvoidsNarrowOverlap(html);
    });
  });

  await test('waiting screen renders versioned Prime Radiant logo by default', async () => {
    const port = 3452;
    const dir = '/tmp/brainstorm-branding-waiting';
    await withServer({ port, dir }, async () => {
      const html = await fetchHtml(port);
      assert(html.includes('Waiting for the agent'), 'waiting page should still render');
      assertBrandedWithLogo(html);
      assertTelemetryImage(html);
      assertLogoKeepsTransparentBackground(html);
    });
  });

  await test('packaged Codex plugin reads version from .codex-plugin manifest', async () => {
    const port = 3457;
    const dir = '/tmp/brainstorm-branding-packaged-codex';
    const packagedVersion = '7.8.9';
    const fixture = createPackagedServerFixture(packagedVersion);

    try {
      await withServer({ port, dir, serverPath: fixture.serverPath }, async () => {
        writeFragment(dir);
        await sleep(300);
        const html = await fetchHtml(port);
        assertBrandedWithLogo(html, packagedVersion);
        assertTelemetryImage(html, packagedVersion);
        assert(!html.includes('Superpowers vunknown'), 'packaged plugin should not fall back to unknown version');
      });
    } finally {
      cleanup(fixture.root);
    }
  });

  await test('SUPERPOWERS_DISABLE_TELEMETRY=true omits remote image but keeps local branding', async () => {
    const port = 3453;
    const dir = '/tmp/brainstorm-branding-disabled';
    await withServer({ port, dir, env: { SUPERPOWERS_DISABLE_TELEMETRY: 'true' } }, async () => {
      writeFragment(dir);
      await sleep(300);
      const html = await fetchHtml(port);
      assertBrandedFallbackText(html);
      assert(!html.includes(ASSET_URL), 'disabled telemetry should omit the remote image');
    });
  });

  await test('SUPERPOWERS_DISABLE_TELEMETRY=yes also omits the remote image on the waiting screen', async () => {
    const port = 3454;
    const dir = '/tmp/brainstorm-branding-disabled-waiting';
    await withServer({ port, dir, env: { SUPERPOWERS_DISABLE_TELEMETRY: 'yes' } }, async () => {
      const html = await fetchHtml(port);
      assertBrandedFallbackText(html);
      assert(!html.includes(ASSET_URL), 'disabled telemetry should omit the remote image');
    });
  });

  await test('DISABLE_TELEMETRY=true omits remote image for Claude Code telemetry opt-out', async () => {
    const port = 3455;
    const dir = '/tmp/brainstorm-branding-claude-disable-telemetry';
    await withServer({ port, dir, env: { DISABLE_TELEMETRY: 'true' } }, async () => {
      writeFragment(dir);
      await sleep(300);
      const html = await fetchHtml(port);
      assertBrandedFallbackText(html);
      assert(!html.includes(ASSET_URL), 'Claude Code telemetry opt-out should omit the remote image');
    });
  });

  await test('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 omits remote image for Claude Code traffic opt-out', async () => {
    const port = 3456;
    const dir = '/tmp/brainstorm-branding-claude-disable-nonessential';
    await withServer({ port, dir, env: { CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1' } }, async () => {
      const html = await fetchHtml(port);
      assertBrandedFallbackText(html);
      assert(!html.includes(ASSET_URL), 'Claude Code non-essential traffic opt-out should omit the remote image');
    });
  });

  console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  if (failed > 0) process.exitCode = 1;
}

main().catch((err) => {
  console.error('Test failed:', err);
  process.exit(1);
});

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč je klíč relace nutný, i když server běží jen na loopbacku?

Libovolná záložka prohlížeče uživatele může volat localhost. Zlomyslná stránka by mohla číst obrazovky nebo vkládat události do state/events, tedy prompt injection do živé agentní session. Klíč zajišťuje, že přístup mají jen ti, kdo URL dostali od agenta.

2. Proč 403 platí i se špatným klíčem a platnou cookie?

Neplatný explicitní klíč je podezřelý. Pokud by cookie přepsala špatný query klíč, útočník by měl větší prostor. Testovaná logika je přísná: explicitní chybný klíč je zamítnut.

3. Co je „bootstrap“ a proč se platný klíč nevrací rovnou s obsahem?

Bootstrap stránka nastaví cookie, uloží klíč a odstraní ho z URL, aby neprosakoval do historie a Referer. Test navíc ověřuje, že se klíč z URL odstraní, i když zápis do sessionStorage selže.

4. Co ověřuje test cross-origin WebSocketu?

Že cizí stránka v prohlížeči nemůže otevřít spojení s cookie uživatele (cross-site WebSocket hijacking). Origin musí odpovídat Host.

5. Proč testy kontrolují bezpečnostní hlavičky i na 403 odpovědích?

Chybové stránky se mohou také zarámovat nebo prozradit klíč v Refereru. Hlavičky no-store, no-referrer a X-Frame-Options: DENY se proto vyžadují na každé odpovědi.

6. Proč se zkouší null payload přes autentizovaný WebSocket?

Neočekávaný vstup od autentizovaného klienta nesmí server shodit. Je to ochrana proti DoS způsobené chybou parsování.

7. Proč branding test kontroluje několik proměnných pro vypnutí telemetrie?

Uživatelé mohou telemetrii vypnout různými způsoby (proměnná superpowers, obecná DISABLE_TELEMETRY, nastavení Claude Code). Respektování všech je otázka důvěry. Odpověď bez vzdáleného obrázku nesmí volat ven.

8. Proč se verze loga čte z manifestu balíčkovaného pluginu?

Codex plugin se distribuuje bez package.json v kořeni. Server musí najít verzi i tam, aby logo nebylo bez verze.

9. Proč fixní token `testtoken-server-...` v testech?

Test klient musí vědět klíč předem. Server umožňuje explicitní BRAINSTORM_TOKEN, takže testy jsou deterministické.

Slovník pojmů (11)

Session key

Per-session secret (token), který chrání každý endpoint.

403 Forbidden

Odpověď pro chybějící nebo špatný klíč.

Bootstrap page

Stránka, která nastaví cookie, uloží klíč a vyčistí URL.

HttpOnly cookie

Cookie nedostupná skriptům.

SameSite=Strict

Cookie se neposílá při cross-site požadavcích.

Origin check

Kontrola zdroje WebSocket spojení.

Prompt injection

Vložení škodlivých pokynů do kontextu agenta.

Clickjacking

Útok zarámováním stránky; brání X-Frame-Options.

Telemetry opt-out

Proměnné, které vypínají vzdálené načítání obrázku.

Prime Radiant branding

Logo a verze zobrazená v rámu a waiting stránce.

Confused deputy

Útok, kdy oprávněný program (prohlížeč) provede akci za útočníka.

↑ nahoru

Testy brainstorm serveru: životní cyklus a shell skripty

Testy idle timeoutu, perzistence portu a klíče, fallbacku portu, auto-open prohlížeče a bezpečného startu/zastavení včetně Windows.

lifecycle.test.js ověřuje chování serveru v čase: server-info hlásí nastavený idle_timeout_ms, idle shutdown zavře otevřený WebSocket a proces opravdu skončí, start-server.sh --idle-timeout-minutes nastaví limit, URL s IPv6 hostem má hranaté závorky, port a klíč se po restartu obnoví (a oprávnění souboru s tokenem se zpřísní), uložený klíč autentizuje WebSocket po restartu na stejném portu, při obsazeném portu se spadne na náhodný port (s uloženým tokenem se vygeneruje nový neperzistovaný klíč, s explicitním BRAINSTORM_TOKEN server selže uzavřeně), prohlížeč se automaticky otevře jednou a jen po schválení, a neautentizované požadavky neprodlouží idle timeout.

Shell testy: start-server.test.sh rychle ověřuje platformní rozhodnutí (foreground), stop-server.test.sh ověřuje, že skript nezabije cizí proces po recyklaci PID, a windows-lifecycle.test.sh kontroluje foreground režim na Windows/MSYS2, prázdný owner PID, přežití přes 60 s lifecycle check, validaci mrtvého owner PID a čisté zastavení.

Zdrojový kód

tests/brainstorm-server/lifecycle.test.js 516 řádků
/**
 * Tests for the brainstorm server's lifecycle (idle timeout + shutdown).
 *
 * - The idle timeout is configurable (default 4h) and reported in server-info.
 * - Idle shutdown must close any open WebSocket so the process actually exits,
 *   not hang on a lingering connection.
 * - start-server.sh exposes the timeout via --idle-timeout-minutes.
 *
 * Uses the `ws` npm package as a test client (test-only dependency).
 */

const { spawn, execFileSync } = require('child_process');
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const assert = require('assert');

const SERVER = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');
const START = path.join(__dirname, '../../skills/brainstorming/scripts/start-server.sh');
const STOP = path.join(__dirname, '../../skills/brainstorming/scripts/stop-server.sh');
const sleep = ms => new Promise(r => setTimeout(r, ms));

function waitForExit(child, timeoutMs = 2000) {
  if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
  return new Promise(resolve => {
    let settled = false;
    const finish = (exited) => {
      if (settled) return;
      settled = true;
      resolve(exited);
    };
    child.once('exit', () => finish(true));
    setTimeout(() => finish(false), timeoutMs);
  });
}

async function killAndWait(child, timeoutMs = 2000) {
  if (!child || child.exitCode !== null || child.signalCode !== null) return true;
  const exited = waitForExit(child, timeoutMs);
  child.kill();
  if (await exited) return true;

  child.kill('SIGKILL');
  return waitForExit(child, 500);
}

async function waitForFile(file, timeoutMs = 3000) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    if (fs.existsSync(file)) return true;
    await sleep(50);
  }
  return fs.existsSync(file);
}

function firstServerStarted(out) {
  return JSON.parse(out.trim().split('\n').find(l => l.includes('server-started')));
}

function openCaptureCommand(dir, marker) {
  const scriptPath = path.resolve(dir, 'capture-open.cjs');
  const markerPath = path.resolve(marker);
  fs.writeFileSync(scriptPath,
    "const fs = require('fs');\n" +
    "fs.appendFileSync(process.argv[2], process.argv[3] + '\\n');\n");
  return `node ${JSON.stringify(scriptPath)} ${JSON.stringify(markerPath)}`;
}

function httpStatus(port, key) {
  return new Promise(resolve => {
    const pathWithKey = key ? '/?key=' + encodeURIComponent(key) : '/';
    require('http')
      .get({ hostname: '127.0.0.1', port, path: pathWithKey }, res => {
        res.resume();
        resolve(res.statusCode);
      })
      .on('error', () => resolve(0));
  });
}

function isWindowsLikeShell() {
  return process.platform === 'win32' ||
    /^msys|^cygwin|^mingw/i.test(process.env.OSTYPE || '') ||
    !!process.env.MSYSTEM;
}

async function waitForStartedOutput(child, timeoutMs = 5000) {
  let stdout = '';
  let stderr = '';
  child.stdout.on('data', d => { stdout += d.toString(); });
  child.stderr.on('data', d => { stderr += d.toString(); });

  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline && !stdout.includes('server-started') && child.exitCode === null) {
    await sleep(50);
  }

  if (!stdout.includes('server-started')) {
    throw new Error(`start-server.sh did not report server-started. exit=${child.exitCode} stdout=${stdout} stderr=${stderr}`);
  }
  return stdout;
}

function makeShellTempDir(prefix) {
  return execFileSync('bash', ['-c', `mktemp -d "\${TMPDIR:-/tmp}/${prefix}-XXXXXX"`], { encoding: 'utf8' }).trim();
}

function removeShellPath(p) {
  execFileSync('bash', ['-c', 'rm -rf "$1"', 'bash', p], { stdio: 'ignore' });
}

function newestSessionDir(projectDir) {
  const sessionDir = execFileSync('bash', [
    '-c',
    'find "$1/.superpowers/brainstorm" -mindepth 1 -maxdepth 1 -type d -print | sort | tail -1',
    'bash',
    projectDir
  ], { encoding: 'utf8' }).trim();
  assert(sessionDir, `expected at least one session dir under ${projectDir}/.superpowers/brainstorm`);
  return sessionDir;
}

async function runTests() {
  let passed = 0, failed = 0;
  async function test(name, fn) {
    try { await fn(); console.log(`  PASS: ${name}`); passed++; }
    catch (e) { console.log(`  FAIL: ${name}`); console.log(`    ${e.message}`); failed++; }
  }

  await test('server-info reports the configured idle_timeout_ms', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-life-');
    const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3401, BRAINSTORM_DIR: dir, BRAINSTORM_IDLE_TIMEOUT_MS: 1234567 } });
    let out = ''; srv.stdout.on('data', d => out += d.toString());
    for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
    try {
      const info = firstServerStarted(out);
      assert.strictEqual(info.idle_timeout_ms, 1234567, 'idle_timeout_ms should reflect the env override');
    } finally {
      await killAndWait(srv);
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('idle shutdown closes an open WebSocket and the process exits', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-life-');
    const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3402, BRAINSTORM_DIR: dir, BRAINSTORM_TOKEN: 'lifetoken', BRAINSTORM_IDLE_TIMEOUT_MS: 200, BRAINSTORM_LIFECYCLE_CHECK_MS: 100 } });
    let out = ''; srv.stdout.on('data', d => out += d.toString());
    let exited = false, code = null; srv.on('exit', c => { exited = true; code = c; });
    for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);

    const ws = new WebSocket('ws://localhost:3402/?key=lifetoken');
    await new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); });

    // 200ms idle, checked every 100ms — should shut down and exit well within 4s,
    // *despite* the open WS, only if shutdown() closes client sockets.
    for (let i = 0; i < 40 && !exited; i++) await sleep(100);

    try {
      assert(exited, 'process must exit after idle shutdown even with an open WebSocket');
      assert.strictEqual(code, 0, 'should exit cleanly (0)');
      assert(fs.existsSync(path.join(dir, 'state', 'server-stopped')), 'should write server-stopped');
    } finally {
      try { ws.close(); } catch (e) {}
      if (!exited) await killAndWait(srv);
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('start-server.sh --idle-timeout-minutes sets the timeout', async () => {
    const dir = makeShellTempDir('bs-life');
    let info = null;
    let startProcess = null;
    let sessionDir = null;
    try {
      if (isWindowsLikeShell()) {
        startProcess = spawn('bash', [START, '--project-dir', dir, '--idle-timeout-minutes', '5']);
        info = firstServerStarted(await waitForStartedOutput(startProcess));
      } else {
        const out = execFileSync('bash', [START, '--project-dir', dir, '--idle-timeout-minutes', '5', '--background'], { encoding: 'utf8' });
        info = firstServerStarted(out);
      }
      sessionDir = newestSessionDir(dir);
      assert.strictEqual(info.idle_timeout_ms, 5 * 60 * 1000, '5 minutes -> 300000 ms');
    } finally {
      if (sessionDir) execFileSync('bash', [STOP, sessionDir], { stdio: 'ignore' });
      if (startProcess && !await waitForExit(startProcess, 3000)) {
        await killAndWait(startProcess);
      }
      removeShellPath(dir);
    }
  });

  await test('server-started URL brackets IPv6 URL hosts', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-ipv6-url-');
    const srv = spawn('node', [SERVER], {
      env: {
        ...process.env,
        BRAINSTORM_PORT: 3421,
        BRAINSTORM_HOST: '127.0.0.1',
        BRAINSTORM_URL_HOST: '::1',
        BRAINSTORM_TOKEN: 'ipv6token',
        BRAINSTORM_DIR: dir,
        BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
      }
    });
    let out = ''; srv.stdout.on('data', d => out += d.toString());
    try {
      for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
      const info = firstServerStarted(out);
      assert.strictEqual(info.url, 'http://[::1]:3421/?key=ipv6token');
    } finally {
      await killAndWait(srv);
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('persists the bound port AND key, and restores both on restart', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-port-');
    const portFile = path.join(dir, '.last-port');
    const tokenFile = path.join(dir, '.last-token');
    const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };

    const a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
    let outA = ''; a.stdout.on('data', d => outA += d.toString());
    for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
    const infoA = firstServerStarted(outA);
    const keyA = new URL(infoA.url).searchParams.get('key');
    assert(fs.existsSync(portFile) && fs.existsSync(tokenFile), 'should write the port and token files');
    const exitedA = waitForExit(a);
    a.kill();
    assert(await exitedA, 'first server should exit before restart binds its port');

    const b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
    let outB = ''; b.stdout.on('data', d => outB += d.toString());
    for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
    const infoB = firstServerStarted(outB);
    const keyB = new URL(infoB.url).searchParams.get('key');
    await killAndWait(b);
    fs.rmSync(dir, { recursive: true, force: true });

    assert.strictEqual(infoB.port, infoA.port, 'restart should reuse the same port');
    // Same key too — otherwise the open tab's cookie would 403 against the restart.
    assert.strictEqual(keyB, keyA, 'restart should reuse the same session key');
  });

  await test('hardens existing persisted token file permissions', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-token-mode-');
    const portFile = path.join(dir, '.last-port');
    const tokenFile = path.join(dir, '.last-token');
    const token = 'efefefefefefefefefefefefefefefef';
    let srv = null;

    try {
      fs.writeFileSync(tokenFile, token, { mode: 0o644 });
      fs.chmodSync(tokenFile, 0o644);
      srv = spawn('node', [SERVER], {
        env: {
          ...process.env,
          BRAINSTORM_DIR: path.join(dir, 's1'),
          BRAINSTORM_PORT_FILE: portFile,
          BRAINSTORM_TOKEN_FILE: tokenFile,
          BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
        }
      });
      let out = ''; srv.stdout.on('data', d => out += d.toString());
      for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
      assert(out.includes('server-started'), 'server should start with persisted token');

      if (process.platform !== 'win32') {
        const mode = fs.statSync(tokenFile).mode & 0o777;
        assert.strictEqual(mode, 0o600, `.last-token mode should be 0600, got ${mode.toString(8)}`);
      } else {
        assert(fs.existsSync(tokenFile), 'token file should remain present on Windows');
      }
    } finally {
      await killAndWait(srv);
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('stored key can authenticate WebSocket after same-port restart', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-reconnect-');
    const portFile = path.join(dir, '.last-port');
    const tokenFile = path.join(dir, '.last-token');
    const env = { ...process.env, BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_TOKEN_FILE: tokenFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 };
    let a = null, b = null, ws = null;

    try {
      a = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's1') } });
      let outA = ''; a.stdout.on('data', d => outA += d.toString());
      for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
      const infoA = firstServerStarted(outA);
      const keyA = new URL(infoA.url).searchParams.get('key');
      const exitedA = waitForExit(a);
      a.kill();
      assert(await exitedA, 'first server should exit before restart binds its port');
      a = null;

      b = spawn('node', [SERVER], { env: { ...env, BRAINSTORM_DIR: path.join(dir, 's2') } });
      let outB = ''; b.stdout.on('data', d => outB += d.toString());
      for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
      const infoB = firstServerStarted(outB);

      ws = new WebSocket(`ws://localhost:${infoB.port}/?key=${keyA}`, {
        headers: { Origin: `http://localhost:${infoB.port}` }
      });
      const opened = await new Promise(resolve => {
        ws.on('open', () => resolve(true));
        ws.on('error', () => resolve(false));
        setTimeout(() => resolve(false), 1500);
      });

      assert.strictEqual(infoB.port, infoA.port, 'restart should reuse same port');
      assert(opened, 'stored key should authenticate WS after restart');
    } finally {
      try { if (ws) ws.close(); } catch (e) {}
      await killAndWait(a);
      await killAndWait(b);
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('falls back to a random port when the preferred port is taken', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-port-');
    const portFile = path.join(dir, '.last-port');

    const a = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'a'), BRAINSTORM_PORT: 3415, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
    let outA = ''; a.stdout.on('data', d => outA += d.toString());
    for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);

    fs.writeFileSync(portFile, '3415'); // preferred port, but it's taken by A
    const b = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_DIR: path.join(dir, 'b'), BRAINSTORM_PORT_FILE: portFile, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
    let outB = ''; b.stdout.on('data', d => outB += d.toString());
    for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
    const portB = firstServerStarted(outB).port;
    const persisted = fs.readFileSync(portFile, 'utf8').trim();

    await killAndWait(a);
    await killAndWait(b);
    fs.rmSync(dir, { recursive: true, force: true });

    assert.notStrictEqual(portB, 3415, 'must not bind the already-taken port');
    assert(portB >= 49152, 'should fall back to a random high port');
    // The fallback must NOT clobber the shared port file — A still owns 3415 and
    // its open tab must keep reconnecting there.
    assert.strictEqual(persisted, '3415', 'fallback must not overwrite .last-port');
  });

  await test('fallback with persisted token generates a fresh unpersisted key', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-port-');
    const portFile = path.join(dir, '.last-port');
    const tokenFile = path.join(dir, '.last-token');
    const preferredToken = 'abababababababababababababababab';
    let a = null, b = null;

    try {
      a = spawn('node', [SERVER], {
        env: {
          ...process.env,
          BRAINSTORM_DIR: path.join(dir, 'a'),
          BRAINSTORM_PORT: 3422,
          BRAINSTORM_TOKEN: preferredToken,
          BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
        }
      });
      let outA = ''; a.stdout.on('data', d => outA += d.toString());
      for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
      assert(outA.includes('server-started'), 'preferred-port server should start');

      fs.writeFileSync(portFile, '3422');
      fs.writeFileSync(tokenFile, preferredToken, { mode: 0o600 });

      b = spawn('node', [SERVER], {
        env: {
          ...process.env,
          BRAINSTORM_DIR: path.join(dir, 'b'),
          BRAINSTORM_PORT_FILE: portFile,
          BRAINSTORM_TOKEN_FILE: tokenFile,
          BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
        }
      });
      let outB = ''; b.stdout.on('data', d => outB += d.toString());
      for (let i = 0; i < 60 && !outB.includes('server-started'); i++) await sleep(50);
      const infoB = firstServerStarted(outB);
      const fallbackKey = new URL(infoB.url).searchParams.get('key');
      const persistedAfter = fs.readFileSync(tokenFile, 'utf8').trim();
      const originalStatus = await httpStatus(3422, fallbackKey);

      assert.notStrictEqual(infoB.port, 3422, 'fallback should use a different port');
      assert.notStrictEqual(fallbackKey, preferredToken, 'fallback must not reuse persisted key');
      assert.strictEqual(persistedAfter, preferredToken, 'fallback must not overwrite .last-token');
      assert.strictEqual(originalStatus, 403, 'fallback key must not authenticate to original server');
    } finally {
      await killAndWait(a);
      await killAndWait(b);
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('fallback with explicit BRAINSTORM_TOKEN fails closed', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-port-');
    const portFile = path.join(dir, '.last-port');
    const explicitToken = 'cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd';
    let a = null, b = null;

    try {
      a = spawn('node', [SERVER], {
        env: {
          ...process.env,
          BRAINSTORM_DIR: path.join(dir, 'a'),
          BRAINSTORM_PORT: 3423,
          BRAINSTORM_TOKEN: explicitToken,
          BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
        }
      });
      let outA = ''; a.stdout.on('data', d => outA += d.toString());
      for (let i = 0; i < 60 && !outA.includes('server-started'); i++) await sleep(50);
      assert(outA.includes('server-started'), 'preferred-port server should start');

      fs.writeFileSync(portFile, '3423');
      b = spawn('node', [SERVER], {
        env: {
          ...process.env,
          BRAINSTORM_DIR: path.join(dir, 'b'),
          BRAINSTORM_PORT_FILE: portFile,
          BRAINSTORM_TOKEN: explicitToken,
          BRAINSTORM_LIFECYCLE_CHECK_MS: 100000
        }
      });
      let outB = ''; let errB = '';
      b.stdout.on('data', d => outB += d.toString());
      b.stderr.on('data', d => errB += d.toString());
      for (let i = 0; i < 60 && !outB.includes('server-started') && b.exitCode === null; i++) await sleep(50);
      const exited = await waitForExit(b, 1500);

      assert(exited, 'explicit-token fallback process should exit');
      assert.notStrictEqual(b.exitCode, 0, 'explicit-token fallback should fail non-zero');
      assert(!outB.includes('server-started'), 'explicit-token fallback must not start on a random port');
      assert(/BRAINSTORM_TOKEN/.test(errB), `stderr should explain explicit token fallback refusal, got: ${errB}`);
    } finally {
      await killAndWait(a);
      await killAndWait(b);
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  await test('auto-opens the browser once, on the first screen', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-open-');
    const marker = path.join(dir, 'opened.log');
    const openCmd = openCaptureCommand(dir, marker); // capture the launch instead of opening a browser
    const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3417, BRAINSTORM_DIR: dir, BRAINSTORM_OPEN: '1', BRAINSTORM_OPEN_CMD: openCmd, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
    let out = ''; srv.stdout.on('data', d => out += d.toString());
    for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);

    // First screen, with no browser connected -> should auto-open.
    fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
    await waitForFile(marker);
    // Second screen -> must NOT open again.
    fs.writeFileSync(path.join(dir, 'content', 'second.html'), '<h2>Second</h2>');
    await sleep(700);

    const lines = fs.existsSync(marker) ? fs.readFileSync(marker, 'utf8').trim().split('\n').filter(Boolean) : [];
    // The opened URL must carry the key AND be reachable — a keyless URL hits 403.
    let status = 0;
    if (lines[0]) {
      status = await new Promise(r => require('http').get(lines[0], res => { res.resume(); r(res.statusCode); }).on('error', () => r(0)));
    }
    await killAndWait(srv);
    fs.rmSync(dir, { recursive: true, force: true });

    assert.strictEqual(lines.length, 1, 'should open exactly once');
    assert(lines[0].includes('3417'), `should open the server URL, got: ${lines[0]}`);
    assert(/[?&]key=/.test(lines[0]), `opened URL must carry the session key, got: ${lines[0]}`);
    assert.strictEqual(status, 200, 'the opened URL must be reachable (valid key), not the 403 page');
  });

  await test('does NOT auto-open unless approved (BRAINSTORM_OPEN unset)', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-open-');
    const marker = path.join(dir, 'opened.log');
    const openCmd = openCaptureCommand(dir, marker);
    // BRAINSTORM_OPEN intentionally NOT set — auto-open must stay off.
    const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3418, BRAINSTORM_DIR: dir, BRAINSTORM_OPEN_CMD: openCmd, BRAINSTORM_LIFECYCLE_CHECK_MS: 100000 } });
    let out = ''; srv.stdout.on('data', d => out += d.toString());
    for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);
    fs.writeFileSync(path.join(dir, 'content', 'first.html'), '<h2>First</h2>');
    await sleep(700);
    await killAndWait(srv);
    const opened = fs.existsSync(marker);
    fs.rmSync(dir, { recursive: true, force: true });
    assert(!opened, 'must not open the browser without explicit approval');
  });

  await test('unauthenticated requests do not defeat the idle timeout', async () => {
    const dir = fs.mkdtempSync('/tmp/bs-life-');
    const srv = spawn('node', [SERVER], { env: { ...process.env, BRAINSTORM_PORT: 3419, BRAINSTORM_DIR: dir, BRAINSTORM_TOKEN: 'authtok', BRAINSTORM_IDLE_TIMEOUT_MS: 400, BRAINSTORM_LIFECYCLE_CHECK_MS: 100 } });
    let out = ''; srv.stdout.on('data', d => out += d.toString());
    let exited = false; srv.on('exit', () => { exited = true; });
    for (let i = 0; i < 60 && !out.includes('server-started'); i++) await sleep(50);

    // Flood with UNAUTHENTICATED (keyless → 403) requests. These must NOT count
    // as activity, so the idle timeout still fires and the process exits.
    const hammer = setInterval(() => { require('http').get('http://localhost:3419/', r => r.resume()).on('error', () => {}); }, 60);
    for (let i = 0; i < 40 && !exited; i++) await sleep(100);
    clearInterval(hammer);
    if (!exited) await killAndWait(srv);
    fs.rmSync(dir, { recursive: true, force: true });

    assert(exited, 'idle shutdown must still fire despite a flood of unauthenticated requests');
  });

  console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  if (failed > 0) process.exit(1);
}

runTests().catch(err => { console.error('Test failed:', err); process.exit(1); });
tests/brainstorm-server/start-server.test.sh 116 řádků
#!/usr/bin/env bash
# Fast tests for start-server.sh shell-only platform decisions.
set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
START_SCRIPT="$REPO_ROOT/skills/brainstorming/scripts/start-server.sh"

TEST_DIR="${TMPDIR:-/tmp}/brainstorm-start-test-$$"
passed=0
failed=0

cleanup() {
  rm -rf "$TEST_DIR"
}
trap cleanup EXIT

pass() {
  echo "  PASS: $1"
  passed=$((passed + 1))
}

fail() {
  echo "  FAIL: $1"
  echo "    $2"
  failed=$((failed + 1))
}

make_fake_uname() {
  local fake_bin="$1"
  cat > "$fake_bin/uname" <<'EOF'
#!/usr/bin/env bash
if [[ "${1:-}" == "-s" ]]; then
  echo "MINGW64_NT-10.0"
else
  /usr/bin/uname "$@"
fi
EOF
  chmod +x "$fake_bin/uname"
}

echo ""
echo "--- start-server.sh platform detection ---"

mkdir -p "$TEST_DIR/fake-bin" "$TEST_DIR/project"
make_fake_uname "$TEST_DIR/fake-bin"

cat > "$TEST_DIR/fake-bin/node" <<'EOF'
#!/usr/bin/env bash
echo "CAPTURED_OWNER_PID=${BRAINSTORM_OWNER_PID:-__UNSET__}"
printf 'CAPTURED_ARGV=%s\n' "$@"
exit 0
EOF
chmod +x "$TEST_DIR/fake-bin/node"

captured=$(
  PATH="$TEST_DIR/fake-bin:$PATH" \
    MSYSTEM="" \
    bash "$START_SCRIPT" --project-dir "$TEST_DIR/project" --foreground 2>/dev/null || true
)
owner_pid_value=$(echo "$captured" | grep "CAPTURED_OWNER_PID=" | head -1 | sed 's/CAPTURED_OWNER_PID=//')

if [[ "$owner_pid_value" == "" || "$owner_pid_value" == "__UNSET__" ]]; then
  pass "clears BRAINSTORM_OWNER_PID when uname reports a Windows-like shell"
else
  fail "clears BRAINSTORM_OWNER_PID when uname reports a Windows-like shell" \
       "expected empty or unset, got '$owner_pid_value'"
fi

if echo "$captured" | grep -Eq '^CAPTURED_ARGV=--brainstorm-server-id=[A-Za-z0-9_-]{32,64}$'; then
  pass "passes shell-safe server instance id argv"
else
  fail "passes shell-safe server instance id argv" \
       "expected exact --brainstorm-server-id=<safe id> argv line, got: $captured"
fi

server_id_file=$(find "$TEST_DIR/project/.superpowers/brainstorm" -name server-instance-id -print 2>/dev/null | head -1)
server_id_value=""
if [[ -n "$server_id_file" ]]; then
  server_id_value="$(tr -d '\r\n' < "$server_id_file")"
fi
if [[ "$server_id_value" =~ ^[A-Za-z0-9_-]{32,64}$ ]]; then
  pass "writes shell-safe server-instance-id state file"
else
  fail "writes shell-safe server-instance-id state file" \
       "expected valid id in state, got '$server_id_value'"
fi

rm -rf "$TEST_DIR/project"/*

cat > "$TEST_DIR/fake-bin/node" <<'EOF'
#!/usr/bin/env bash
echo "FOREGROUND_MODE=true"
exit 0
EOF
chmod +x "$TEST_DIR/fake-bin/node"

captured=$(
  PATH="$TEST_DIR/fake-bin:$PATH" \
    MSYSTEM="" \
    bash "$START_SCRIPT" --project-dir "$TEST_DIR/project" 2>/dev/null || true
)

if echo "$captured" | grep -q "FOREGROUND_MODE=true"; then
  pass "auto-foregrounds when uname reports a Windows-like shell"
else
  fail "auto-foregrounds when uname reports a Windows-like shell" \
       "expected foreground node path, got: $captured"
fi

echo ""
echo "--- Results: $passed passed, $failed failed ---"
if [[ $failed -gt 0 ]]; then
  exit 1
fi
tests/brainstorm-server/stop-server.test.sh 183 řádků
#!/usr/bin/env bash
# Tests for stop-server.sh PID-ownership safety.
#
# A stale server.pid (e.g. after a reboot, when the kernel has recycled the PID)
# can point at an unrelated, live process. stop-server.sh must verify the PID is
# actually our brainstorm server before signalling it.

set -u
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
STOP="$SCRIPT_DIR/../../skills/brainstorming/scripts/stop-server.sh"
SERVER="$SCRIPT_DIR/../../skills/brainstorming/scripts/server.cjs"

PASS=0; FAIL=0
PIDS=()
DIRS=()

cleanup() {
  for pid in "${PIDS[@]}"; do
    kill -9 "$pid" 2>/dev/null || true
    wait "$pid" 2>/dev/null || true
  done
  for dir in "${DIRS[@]}"; do
    rm -rf "$dir"
  done
}
trap cleanup EXIT

track_dir() { DIRS+=("$1"); }
track_pid() { PIDS+=("$1"); }
untrack_pid() {
  local remove="$1"
  local kept=()
  local pid
  for pid in "${PIDS[@]}"; do
    [[ "$pid" == "$remove" ]] || kept+=("$pid")
  done
  PIDS=("${kept[@]}")
}
new_server_id() {
  printf 'testid%026d\n' "$RANDOM"
}

ok() { echo "  PASS: $1"; PASS=$((PASS + 1)); }
bad() { echo "  FAIL: $1"; echo "    $2"; FAIL=$((FAIL + 1)); }

# --- Test 1: an unrelated, reused PID must NOT be killed ---
SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
sleep 600 &
UNRELATED=$!
track_pid "$UNRELATED"
disown "$UNRELATED" 2>/dev/null || true
echo "$UNRELATED" > "$SESS/state/server.pid"
OUT="$("$STOP" "$SESS")"
if kill -0 "$UNRELATED" 2>/dev/null; then
  case "$OUT" in
    *stale_pid*) ok "unrelated reused PID is left alone (stale_pid)" ;;
    *) bad "unrelated PID survived but status was not stale_pid" "$OUT" ;;
  esac
else
  bad "unrelated reused PID was KILLED" "$OUT"
fi

# --- Test 2: a real brainstorm server with matching instance id IS stopped ---
SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/content" "$SESS/state"
SERVER_ID="$(new_server_id)"
printf '%s\n' "$SERVER_ID" > "$SESS/state/server-instance-id"
BRAINSTORM_DIR="$SESS" BRAINSTORM_PORT=3399 node "$SERVER" "--brainstorm-server-id=$SERVER_ID" > /dev/null 2>&1 &
SRV=$!
track_pid "$SRV"
disown "$SRV" 2>/dev/null || true
for _ in $(seq 1 40); do kill -0 "$SRV" 2>/dev/null && break; sleep 0.1; done
sleep 0.4
echo "$SRV" > "$SESS/state/server.pid"
OUT="$("$STOP" "$SESS")"
sleep 0.3
if kill -0 "$SRV" 2>/dev/null; then
  bad "real brainstorm server still running after stop" "$OUT"
else
  wait "$SRV" 2>/dev/null || true
  untrack_pid "$SRV"
  case "$OUT" in
    *stopped*) ok "real brainstorm server with matching instance id is stopped" ;;
    *) bad "server stopped but status was not 'stopped'" "$OUT" ;;
  esac
fi

# --- Test 2b: persistent sessions stop with explicit stopped metadata ---
SESS="$(mktemp -d "$SCRIPT_DIR/.stop-persistent.XXXXXX")"; track_dir "$SESS"; mkdir -p "$SESS/content" "$SESS/state"
SERVER_ID="$(new_server_id)"
printf '%s\n' "$SERVER_ID" > "$SESS/state/server-instance-id"
BRAINSTORM_DIR="$SESS" BRAINSTORM_PORT=0 node "$SERVER" "--brainstorm-server-id=$SERVER_ID" > /dev/null 2>&1 &
SRV=$!
track_pid "$SRV"
disown "$SRV" 2>/dev/null || true
for _ in $(seq 1 40); do
  [[ -f "$SESS/state/server-info" ]] && break
  sleep 0.1
done
echo "$SRV" > "$SESS/state/server.pid"
OUT="$("$STOP" "$SESS")"
sleep 0.3
if kill -0 "$SRV" 2>/dev/null; then
  bad "persistent brainstorm server still running after stop" "$OUT"
else
  wait "$SRV" 2>/dev/null || true
  untrack_pid "$SRV"
  if [[ -f "$SESS/state/server-info" ]]; then
    bad "persistent stop clears server-info" "server-info still exists after: $OUT"
  elif [[ ! -f "$SESS/state/server-stopped" ]]; then
    bad "persistent stop writes server-stopped" "server-stopped missing after: $OUT"
  elif grep -q '"reason":"stop-server.sh"' "$SESS/state/server-stopped"; then
    ok "persistent stop clears alive metadata and writes server-stopped"
  else
    bad "persistent stop writes stop reason" "$(cat "$SESS/state/server-stopped" 2>/dev/null || true)"
  fi
fi

# --- Test 3: no pid file ---
SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
OUT="$("$STOP" "$SESS")"
case "$OUT" in
  *not_running*) ok "missing pid file reports not_running" ;;
  *) bad "missing pid file: unexpected status" "$OUT" ;;
esac

# --- Test 4: a node server.cjs impostor with missing instance id is spared ---
SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
( exec -a "node server.cjs" sleep 600 ) &
IMPOSTOR=$!
track_pid "$IMPOSTOR"
disown "$IMPOSTOR" 2>/dev/null || true
echo "$IMPOSTOR" > "$SESS/state/server.pid"
OUT="$("$STOP" "$SESS")"
if kill -0 "$IMPOSTOR" 2>/dev/null; then
  case "$OUT" in
    *stale_pid*) ok "missing instance id leaves node server.cjs impostor alone" ;;
    *) bad "impostor survived but status was not stale_pid" "$OUT" ;;
  esac
else
  bad "killed a node server.cjs impostor with missing instance id" "$OUT"
fi

# --- Test 5: a node server.cjs impostor with wrong instance id is spared ---
SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
EXPECTED_ID="$(new_server_id)"
WRONG_ID="$(new_server_id)"
printf '%s\n' "$EXPECTED_ID" > "$SESS/state/server-instance-id"
( exec -a "node server.cjs --brainstorm-server-id=$WRONG_ID" sleep 600 ) &
IMPOSTOR=$!
track_pid "$IMPOSTOR"
disown "$IMPOSTOR" 2>/dev/null || true
echo "$IMPOSTOR" > "$SESS/state/server.pid"
OUT="$("$STOP" "$SESS")"
if kill -0 "$IMPOSTOR" 2>/dev/null; then
  case "$OUT" in
    *stale_pid*) ok "wrong instance id leaves node server.cjs impostor alone" ;;
    *) bad "wrong-id impostor survived but status was not stale_pid" "$OUT" ;;
  esac
else
  bad "killed a node server.cjs impostor with wrong instance id" "$OUT"
fi

# --- Test 6: malformed instance id is fail-closed ---
SESS="$(mktemp -d)"; track_dir "$SESS"; mkdir -p "$SESS/state"
printf '%s\n' 'bad id with spaces' > "$SESS/state/server-instance-id"
( exec -a "node server.cjs --brainstorm-server-id=bad-id-with-spaces" sleep 600 ) &
IMPOSTOR=$!
track_pid "$IMPOSTOR"
disown "$IMPOSTOR" 2>/dev/null || true
echo "$IMPOSTOR" > "$SESS/state/server.pid"
OUT="$("$STOP" "$SESS")"
if kill -0 "$IMPOSTOR" 2>/dev/null; then
  case "$OUT" in
    *stale_pid*) ok "malformed instance id is fail-closed" ;;
    *) bad "malformed-id impostor survived but status was not stale_pid" "$OUT" ;;
  esac
else
  bad "killed process despite malformed instance id" "$OUT"
fi

echo "--- Results: $PASS passed, $FAIL failed ---"
[ "$FAIL" -eq 0 ] || exit 1
tests/brainstorm-server/windows-lifecycle.test.sh 395 řádků
#!/usr/bin/env bash
# Windows lifecycle tests for the brainstorm server.
#
# Verifies brainstorm server lifecycle behavior, including:
#  - Windows/MSYS2 foreground mode and empty OWNER_PID handling
#  - Server survival past the 60-second lifecycle check window
#  - Dead-at-startup OWNER_PID validation (logged, monitoring disabled)
#  - Clean stop-server.sh shutdown
#
# Requirements:
#   - Node.js in PATH
#   - Run from the repository root, or set SUPERPOWERS_ROOT
#   - On Windows: Git Bash (OSTYPE=msys*)
#
# Usage:
#   bash tests/brainstorm-server/windows-lifecycle.test.sh
set -uo pipefail

# ========== Configuration ==========

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="${SUPERPOWERS_ROOT:-$(cd "$SCRIPT_DIR/../.." && pwd)}"
START_SCRIPT="$REPO_ROOT/skills/brainstorming/scripts/start-server.sh"
STOP_SCRIPT="$REPO_ROOT/skills/brainstorming/scripts/stop-server.sh"
SERVER_SCRIPT="$REPO_ROOT/skills/brainstorming/scripts/server.cjs"

TEST_DIR="${TMPDIR:-/tmp}/brainstorm-win-test-$$"

passed=0
failed=0
skipped=0

# ========== Helpers ==========

cleanup() {
  # Kill any server processes we started
  for pidvar in SERVER_PID CONTROL_PID STOP_TEST_PID; do
    pid="${!pidvar:-}"
    if [[ -n "$pid" ]]; then
      kill "$pid" 2>/dev/null || true
      wait "$pid" 2>/dev/null || true
    fi
  done
  if [[ -n "${TEST_DIR:-}" && -d "$TEST_DIR" ]]; then
    rm -rf "$TEST_DIR"
  fi
}
trap cleanup EXIT

pass() {
  echo "  PASS: $1"
  passed=$((passed + 1))
}

fail() {
  echo "  FAIL: $1"
  echo "    $2"
  failed=$((failed + 1))
}

skip() {
  echo "  SKIP: $1 ($2)"
  skipped=$((skipped + 1))
}

wait_for_server_info() {
  local dir="$1"
  for _ in $(seq 1 50); do
    if [[ -f "$dir/state/server-info" ]]; then
      return 0
    fi
    sleep 0.1
  done
  return 1
}

get_port_from_info() {
  # Read the port from state/server-info. Use grep/sed instead of Node.js
  # to avoid MSYS2-to-Windows path translation issues.
  grep -o '"port":[0-9]*' "$1/state/server-info" | head -1 | sed 's/"port"://'
}

get_key_from_info() {
  grep -o '"url":"[^"]*key=[^"]*' "$1/state/server-info" | head -1 | sed 's/.*key=//'
}

http_check() {
  local port="$1"
  local key="${2:-}"
  node - "$port" "$key" <<'NODE'
    const http = require('http');
    const port = Number(process.argv[2]);
    const key = process.argv[3] || '';
    const path = key ? '/?key=' + encodeURIComponent(key) : '/';
    http.get({ hostname: '127.0.0.1', port, path }, (res) => {
      res.resume();
      process.exit(res.statusCode === 200 ? 0 : 1);
    }).on('error', () => process.exit(1));
NODE
}

# ========== Platform Detection ==========

echo ""
echo "=== Brainstorm Server Windows Lifecycle Tests ==="
echo "Platform: ${OSTYPE:-unknown}"
echo "MSYSTEM: ${MSYSTEM:-unset}"
echo "Node: $(node --version 2>/dev/null || echo 'not found')"
echo ""

is_windows="false"
case "${OSTYPE:-}" in
  msys*|cygwin*|mingw*) is_windows="true" ;;
esac
if [[ -n "${MSYSTEM:-}" ]]; then
  is_windows="true"
fi

if [[ "$is_windows" != "true" ]]; then
  echo "NOTE: Not running on Windows/MSYS2 (OSTYPE=${OSTYPE:-unset})."
  echo "Windows-specific tests will be skipped. Tests 4-6 still run."
  echo ""
fi

mkdir -p "$TEST_DIR"

SERVER_PID=""
CONTROL_PID=""
STOP_TEST_PID=""

# ========== Test 1: OWNER_PID is empty on Windows ==========

echo "--- Owner PID Resolution ---"

if [[ "$is_windows" == "true" ]]; then
  # Replicate the PID resolution logic from start-server.sh lines 104-112
  TEST_OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ' || true)"
  if [[ -z "$TEST_OWNER_PID" || "$TEST_OWNER_PID" == "1" ]]; then
    TEST_OWNER_PID="$PPID"
  fi
  # The fix: clear on Windows
  case "${OSTYPE:-}" in
    msys*|cygwin*|mingw*) TEST_OWNER_PID="" ;;
  esac

  if [[ -z "$TEST_OWNER_PID" ]]; then
    pass "OWNER_PID is empty on Windows after fix"
  else
    fail "OWNER_PID is empty on Windows after fix" \
         "Expected empty, got '$TEST_OWNER_PID'"
  fi
else
  skip "OWNER_PID is empty on Windows" "not on Windows"
fi

# ========== Test 2: start-server.sh passes empty BRAINSTORM_OWNER_PID ==========

if [[ "$is_windows" == "true" ]]; then
  # Use a fake 'node' that captures the env var and exits
  FAKE_NODE_DIR="$TEST_DIR/fake-bin"
  mkdir -p "$FAKE_NODE_DIR"
  cat > "$FAKE_NODE_DIR/node" <<'FAKENODE'
#!/usr/bin/env bash
echo "CAPTURED_OWNER_PID=${BRAINSTORM_OWNER_PID:-__UNSET__}"
printf 'CAPTURED_ARGV=%s\n' "$@"
exit 0
FAKENODE
  chmod +x "$FAKE_NODE_DIR/node"

  captured=$(PATH="$FAKE_NODE_DIR:$PATH" bash "$START_SCRIPT" --project-dir "$TEST_DIR/session" --foreground 2>/dev/null || true)
  owner_pid_value=$(echo "$captured" | grep "CAPTURED_OWNER_PID=" | head -1 | sed 's/CAPTURED_OWNER_PID=//')

  if [[ "$owner_pid_value" == "" || "$owner_pid_value" == "__UNSET__" ]]; then
    pass "start-server.sh passes empty BRAINSTORM_OWNER_PID on Windows"
  else
    fail "start-server.sh passes empty BRAINSTORM_OWNER_PID on Windows" \
         "Expected empty or unset, got '$owner_pid_value'"
  fi

  if echo "$captured" | grep -Eq '^CAPTURED_ARGV=--brainstorm-server-id=[A-Za-z0-9_-]{32,64}$'; then
    pass "start-server.sh passes server instance id argv on Windows"
  else
    fail "start-server.sh passes server instance id argv on Windows" \
         "Expected --brainstorm-server-id=<safe id>, output: $captured"
  fi

  rm -rf "$FAKE_NODE_DIR" "$TEST_DIR/session"
else
  skip "start-server.sh passes empty BRAINSTORM_OWNER_PID" "not on Windows"
fi

# ========== Test 3: Auto-foreground detection on Windows ==========

echo ""
echo "--- Foreground Mode Detection ---"

if [[ "$is_windows" == "true" ]]; then
  FAKE_NODE_DIR="$TEST_DIR/fake-bin"
  mkdir -p "$FAKE_NODE_DIR"
  cat > "$FAKE_NODE_DIR/node" <<'FAKENODE'
#!/usr/bin/env bash
echo "FOREGROUND_MODE=true"
exit 0
FAKENODE
  chmod +x "$FAKE_NODE_DIR/node"

  # Run WITHOUT --foreground flag — Windows should auto-detect
  captured=$(PATH="$FAKE_NODE_DIR:$PATH" bash "$START_SCRIPT" --project-dir "$TEST_DIR/session2" 2>/dev/null || true)

  if echo "$captured" | grep -q "FOREGROUND_MODE=true"; then
    pass "Windows auto-detects foreground mode"
  else
    fail "Windows auto-detects foreground mode" \
         "Expected foreground code path, output: $captured"
  fi

  rm -rf "$FAKE_NODE_DIR" "$TEST_DIR/session2"
else
  skip "Windows auto-detects foreground mode" "not on Windows"
fi

# ========== Test 4: Server survives past 60-second lifecycle check ==========

echo ""
echo "--- Server Survival (lifecycle check) ---"

mkdir -p "$TEST_DIR/survival"

echo "  Starting server (will wait ~75s to verify survival past lifecycle check)..."

BRAINSTORM_DIR="$TEST_DIR/survival" \
BRAINSTORM_HOST="127.0.0.1" \
BRAINSTORM_URL_HOST="localhost" \
BRAINSTORM_OWNER_PID="" \
BRAINSTORM_PORT=$((49152 + RANDOM % 16383)) \
  node "$SERVER_SCRIPT" > "$TEST_DIR/survival/.server.log" 2>&1 &
SERVER_PID=$!

if ! wait_for_server_info "$TEST_DIR/survival"; then
  fail "Server starts successfully" "Server did not write state/server-info within 5 seconds"
  kill "$SERVER_PID" 2>/dev/null || true
  SERVER_PID=""
else
  pass "Server starts successfully with empty OWNER_PID"

  SERVER_PORT=$(get_port_from_info "$TEST_DIR/survival")
  SERVER_KEY=$(get_key_from_info "$TEST_DIR/survival")

  sleep 75

  if kill -0 "$SERVER_PID" 2>/dev/null; then
    pass "Server is still alive after 75 seconds"
  else
    fail "Server is still alive after 75 seconds" \
         "Server died. Log tail: $(tail -5 "$TEST_DIR/survival/.server.log" 2>/dev/null)"
  fi

  if http_check "$SERVER_PORT" "$SERVER_KEY"; then
    pass "Server responds to HTTP after lifecycle check window"
  else
    fail "Server responds to HTTP after lifecycle check window" \
         "Authenticated HTTP request to port $SERVER_PORT failed"
  fi

  if grep -q "owner process exited" "$TEST_DIR/survival/.server.log" 2>/dev/null; then
    fail "No 'owner process exited' in logs" \
         "Found spurious owner-exit shutdown in log"
  else
    pass "No 'owner process exited' in logs"
  fi

  kill "$SERVER_PID" 2>/dev/null || true
  wait "$SERVER_PID" 2>/dev/null || true
  SERVER_PID=""
fi

# ========== Test 5: Dead-at-startup OWNER_PID is logged but does not kill the server ==========
#
# The server validates BRAINSTORM_OWNER_PID at startup. If it's already dead,
# the PID resolution was wrong (common on WSL, Tailscale SSH, cross-user
# scenarios). The server logs 'owner-pid-invalid', disables owner monitoring,
# and continues running. The idle timeout becomes the only shutdown trigger.

echo ""
echo "--- Dead-at-startup OWNER_PID: server survives, logs owner-pid-invalid ---"

mkdir -p "$TEST_DIR/control"

# Find a PID that does not exist
BAD_PID=99999
while kill -0 "$BAD_PID" 2>/dev/null; do
  BAD_PID=$((BAD_PID + 1))
done

BRAINSTORM_DIR="$TEST_DIR/control" \
BRAINSTORM_HOST="127.0.0.1" \
BRAINSTORM_URL_HOST="localhost" \
BRAINSTORM_OWNER_PID="$BAD_PID" \
BRAINSTORM_PORT=$((49152 + RANDOM % 16383)) \
  node "$SERVER_SCRIPT" > "$TEST_DIR/control/.server.log" 2>&1 &
CONTROL_PID=$!

if ! wait_for_server_info "$TEST_DIR/control"; then
  fail "Control server starts" "Server did not write state/server-info within 5 seconds"
  kill "$CONTROL_PID" 2>/dev/null || true
  CONTROL_PID=""
else
  pass "Control server starts with dead-at-startup OWNER_PID=$BAD_PID"

  echo "  Waiting ~75s to verify server survives past lifecycle check..."
  sleep 75

  if kill -0 "$CONTROL_PID" 2>/dev/null; then
    pass "Server survives with dead-at-startup OWNER_PID (owner monitoring disabled)"
  else
    fail "Server survives with dead-at-startup OWNER_PID" \
         "Server died unexpectedly. Log tail: $(tail -5 "$TEST_DIR/control/.server.log" 2>/dev/null)"
  fi

  if grep -q "owner-pid-invalid" "$TEST_DIR/control/.server.log" 2>/dev/null; then
    pass "Server logs 'owner-pid-invalid' for dead-at-startup PID"
  else
    fail "Server logs 'owner-pid-invalid' for dead-at-startup PID" \
         "Log tail: $(tail -5 "$TEST_DIR/control/.server.log" 2>/dev/null)"
  fi

  if grep -q "owner process exited" "$TEST_DIR/control/.server.log" 2>/dev/null; then
    fail "No spurious 'owner process exited' log" \
         "Found 'owner process exited' but owner monitoring should be disabled"
  else
    pass "No spurious 'owner process exited' log"
  fi

  kill "$CONTROL_PID" 2>/dev/null || true
fi

wait "$CONTROL_PID" 2>/dev/null || true
CONTROL_PID=""

# ========== Test 6: stop-server.sh cleanly stops the server ==========

echo ""
echo "--- Clean Shutdown ---"

mkdir -p "$TEST_DIR/stop-test/state"
STOP_TEST_ID="$(printf 'windowsstop%021d\n' "$RANDOM")"
printf '%s\n' "$STOP_TEST_ID" > "$TEST_DIR/stop-test/state/server-instance-id"

BRAINSTORM_DIR="$TEST_DIR/stop-test" \
BRAINSTORM_HOST="127.0.0.1" \
BRAINSTORM_URL_HOST="localhost" \
BRAINSTORM_OWNER_PID="" \
BRAINSTORM_PORT=$((49152 + RANDOM % 16383)) \
  node "$SERVER_SCRIPT" "--brainstorm-server-id=$STOP_TEST_ID" > "$TEST_DIR/stop-test/.server.log" 2>&1 &
STOP_TEST_PID=$!
disown "$STOP_TEST_PID" 2>/dev/null || true
echo "$STOP_TEST_PID" > "$TEST_DIR/stop-test/state/server.pid"

if ! wait_for_server_info "$TEST_DIR/stop-test"; then
  fail "Stop-test server starts" "Server did not start"
  kill "$STOP_TEST_PID" 2>/dev/null || true
  wait "$STOP_TEST_PID" 2>/dev/null || true
  STOP_TEST_PID=""
else
  bash "$STOP_SCRIPT" "$TEST_DIR/stop-test" >/dev/null 2>&1 || true
  for _ in $(seq 1 10); do
    if ! kill -0 "$STOP_TEST_PID" 2>/dev/null; then
      wait "$STOP_TEST_PID" 2>/dev/null || true
      break
    fi
    sleep 0.1
  done

  if ! kill -0 "$STOP_TEST_PID" 2>/dev/null; then
    pass "stop-server.sh cleanly stops the server"
  else
    fail "stop-server.sh cleanly stops the server" \
         "Server PID $STOP_TEST_PID is still alive after stop"
    kill "$STOP_TEST_PID" 2>/dev/null || true
  fi
fi

wait "$STOP_TEST_PID" 2>/dev/null || true
STOP_TEST_PID=""

# ========== Summary ==========

echo ""
echo "=== Results: $passed passed, $failed failed, $skipped skipped ==="

if [[ $failed -gt 0 ]]; then
  exit 1
fi
exit 0

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč idle shutdown musí zavřít i otevřené WebSockety?

Otevřené spojení udržuje Node event loop naživu. Bez jeho zavření by proces po timeoutu nikdy neskončil a server by zůstal viset.

2. Proč se port a klíč perzistují a po restartu obnovují?

Otevřená záložka prohlížeče se po restartu serveru znovu připojí na stejné URL a její cookie stále platí. Uživatel nemusí otevírat nový odkaz.

3. Co znamená, že fallback s explicitním tokenem „fails closed“?

Pokud uživatel zadá konkrétní token a preferovaný port je obsazený, server nepřepne na náhodný port, protože by klíč mohl přijmout neočekávaný proces. Raději skončí s chybou.

4. Proč fallback s perzistovaným tokenem generuje čerstvý neuložený klíč?

Starý klíč je svázaný s předchozím portem. Nový port dostane nový klíč, a ten se neuloží, aby se nepřepsal stav původního portu.

5. Proč se auto-open prohlížeče dělá jen jednou a jen po schválení?

Neočekávané otevírání oken je rušivé a může být bezpečnostní riziko. Je to opt-in (BRAINSTORM_OPEN), a jen při první obrazovce.

6. Proč neautentizované požadavky neprodlužují idle timeout?

Kdyby je server počítal jako aktivitu, náhodný scanner by mohl server držet naživu navždy. Aktivita se počítá jen od oprávněných klientů.

7. Proč se oprávnění persistovaného souboru s tokenem zpřísňují?

Starší soubor mohl být vytvořen s volnějšími oprávněními. Server je při startu nastaví na owner-only, takže klíč nečte nikdo jiný.

8. Proč `stop-server.test.sh` simuluje cizí proces s recyklovaným PID?

Je to přesně situace po rebootu: pid soubor ukazuje na nesouvisející živý proces. Test ověřuje, že stop skript nezabije cizí proces a ohlásí stale_pid.

9. Proč zvláštní Windows test?

Git Bash/MSYS2 zabíjí odpojené procesy a Node neumí ověřit POSIX PID. Server by se jinak do 60 s sám ukončil. Test hlídá, že foreground režim a vyčištěný owner PID tyto problémy řeší.

10. Proč se testují IPv6 hostitelé v URL?

IPv6 adresa v URL musí být v hranatých závorkách (http://[::1]:port). Bez nich by odkaz nefungoval.

Slovník pojmů (11)

Idle timeout

Ukončení serveru po době nečinnosti.

`server-info`

Soubor s informacemi o serveru (port, URL, timeout).

Persisted port/token

Uložený port a klíč, použité při restartu.

Fallback port

Náhodný port při obsazeném preferovaném.

Fail closed

Při neočekávaném stavu odmítnout místo riskantního pokračování.

Auto-open

Automatické otevření prohlížeče po schválení.

Stale PID

PID ze souboru, který už nepatří našemu serveru.

PID recycling

Znovupoužití čísla procesu jiným procesem po jeho zániku.

Owner PID

Vlastník, jehož zánik server ukončí.

MSYS2 / Git Bash

Prostředí Windows, kde jsou zvláštní pravidla pro procesy.

Lifecycle check

Pravidelná kontrola (60 s) vlastníka a nečinnosti.

↑ nahoru

Testy brainstorm serveru: HTTP, WebSocket a klient

Integrační a unit testy serveru: HTTP obsluha, ruční WebSocket protokol, file watching, helper.js a spouštění prohlížeče.

Čtyři testovací soubory pokrývají funkčnost server.cjs a helper.js ve třech vrstvách. ws-protocol.test.js jsou unit testy ručně napsaného WebSocket protokolu: computeAcceptKey, encodeFrame, decodeFrame včetně hranic 125/126/65535/65536 bajtů, neúplných rámců, více rámců v jednom bufferu, odmítnutí nemaskovaných klientských rámců a ochrany proti obřím 64bitovým rámcům před alokací. server.test.js je integrační test: spustí skutečný server na portu 3334, ověří HTTP (waiting page, rámování fragmentů, nejnovější obrazovka podle mtime, 404, ochrana proti symlinkům a hardlinkům mimo content dir), WebSocket (relay událostí, zápis choice do state/events, více klientů, poškozené JSON) a file watching (reload, ignorování ne-HTML a ._*.html).

helper.test.js testuje exportovanou čistou funkci backoffu a staticky ověřuje, že klient obsahuje stavy spojení, tombstone a obnovu. browser-launcher.test.js kontroluje, že launchery pro Windows a WSL nepouštějí URL přes cmd.exe (prevence injekce) a že Linux bez displeje zůstane headless. Test klient ws je jediná test-only závislost (package.json).

Zdrojový kód

tests/brainstorm-server/server.test.js 644 řádků
/**
 * Integration tests for the brainstorm server.
 *
 * Tests the full server behavior: HTTP serving, WebSocket communication,
 * file watching, and the brainstorming workflow.
 *
 * Uses the `ws` npm package as a test client (test-only dependency,
 * not shipped to end users).
 */

const { spawn } = require('child_process');
const http = require('http');
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const assert = require('assert');

const SERVER_PATH = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');
const TEST_PORT = 3334;
const TEST_DIR = '/tmp/brainstorm-test';
const CONTENT_DIR = path.join(TEST_DIR, 'content');
const STATE_DIR = path.join(TEST_DIR, 'state');
// Fixed session key so the test client can authenticate (see auth.test.js for
// the security behavior itself; here we just need authorized requests).
const TOKEN = 'testtoken-server-0123456789abcdef';

function cleanup() {
  if (fs.existsSync(TEST_DIR)) {
    fs.rmSync(TEST_DIR, { recursive: true });
  }
}

async function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// fs.watch delivery latency varies widely by platform: on macOS, FSEvents
// has been observed delivering events anywhere from ~100ms to over 2s after
// the write. File-watching tests poll for the outcome instead of sleeping a
// fixed interval, so a slow event neither fails its own test nor arrives
// during the next one.
async function waitFor(condition, message, timeoutMs = 5000) {
  const deadline = Date.now() + timeoutMs;
  while (!condition()) {
    if (Date.now() > deadline) throw new Error(message);
    await sleep(25);
  }
}

async function fetch(url) {
  return new Promise((resolve, reject) => {
    const headers = { Cookie: `brainstorm-key-${TEST_PORT}=${TOKEN}` };
    http.get(url, { headers }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve({
        status: res.statusCode,
        headers: res.headers,
        body: data
      }));
    }).on('error', reject);
  });
}

function startServer() {
  return spawn('node', [SERVER_PATH], {
    env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_DIR: TEST_DIR, BRAINSTORM_TOKEN: TOKEN }
  });
}

async function waitForServer(server) {
  let stdout = '';
  let stderr = '';

  return new Promise((resolve, reject) => {
    server.stdout.on('data', (data) => {
      stdout += data.toString();
      if (stdout.includes('server-started')) {
        resolve({ stdout, stderr, getStdout: () => stdout });
      }
    });
    server.stderr.on('data', (data) => { stderr += data.toString(); });
    server.on('error', reject);

    setTimeout(() => reject(new Error(`Server didn't start. stderr: ${stderr}`)), 5000);
  });
}

class SkipTest extends Error {
  constructor(message) {
    super(message);
    this.skip = true;
  }
}

function skip(message) {
  throw new SkipTest(message);
}

function serverStartedMessage(out) {
  const line = out.trim().split('\n').find(l => l.includes('server-started'));
  assert(line, 'server-started JSON should be present');
  return JSON.parse(line);
}

function assertStartedOnExpectedPort(out) {
  const msg = serverStartedMessage(out);
  assert.strictEqual(
    msg.port,
    TEST_PORT,
    `server.test.js expected fixed port ${TEST_PORT}, got ${msg.port}; fixed-port tests must not run through fallback`
  );
  return msg;
}

function ensureSymlinkWorks(target, link) {
  try {
    fs.symlinkSync(target, link);
    fs.unlinkSync(link);
  } catch (e) {
    try { fs.unlinkSync(link); } catch (ignore) {}
    skip(`symlink creation unavailable on this host: ${e.message}`);
  }
}

async function runTests() {
  cleanup();

  const server = startServer();
  let stdoutAccum = '';
  // Unlike stdoutAccum, never reset: lets a test wait until the server has
  // processed a specific file event.
  let serverLog = '';
  server.stdout.on('data', (data) => {
    stdoutAccum += data.toString();
    serverLog += data.toString();
  });
  const screenLogged = (type, filePath) =>
    serverLog.includes(JSON.stringify({ type, file: filePath }));

  // Drains file events still in flight from earlier tests, which can each
  // trigger a reload and clear state/events. fs.watch delivers events in
  // order, so once the server has processed a file written now, every
  // earlier event has been handled too.
  let barrierCount = 0;
  async function settleWatcher() {
    const barrier = path.join(CONTENT_DIR, `barrier-${++barrierCount}.html`);
    fs.writeFileSync(barrier, '<h2>Barrier</h2>');
    await waitFor(() => screenLogged('screen-added', barrier),
      'Server should process the barrier file');
  }

  let initialStdout = '';
  let passed = 0;
  let failed = 0;
  let skipped = 0;

  function test(name, fn) {
    return fn().then(() => {
      console.log(`  PASS: ${name}`);
      passed++;
    }).catch(e => {
      if (e.skip) {
        console.log(`  SKIP: ${name}`);
        console.log(`    ${e.message}`);
        skipped++;
        return;
      }
      console.log(`  FAIL: ${name}`);
      console.log(`    ${e.message}`);
      failed++;
    });
  }

  try {
    const { stdout } = await waitForServer(server);
    initialStdout = stdout;
    assertStartedOnExpectedPort(initialStdout);

    // ========== Server Startup ==========
    console.log('\n--- Server Startup ---');

    await test('outputs server-started JSON on startup', () => {
      const msg = serverStartedMessage(initialStdout);
      assert.strictEqual(msg.type, 'server-started');
      assert.strictEqual(msg.port, TEST_PORT);
      assert(msg.url, 'Should include URL');
      assert(msg.screen_dir, 'Should include screen_dir');
      return Promise.resolve();
    });

    await test('writes server-info to state/', () => {
      const infoPath = path.join(STATE_DIR, 'server-info');
      assert(fs.existsSync(infoPath), 'state/server-info should exist');
      const info = JSON.parse(fs.readFileSync(infoPath, 'utf-8').trim());
      assert.strictEqual(info.type, 'server-started');
      assert.strictEqual(info.port, TEST_PORT);
      assert.strictEqual(info.screen_dir, CONTENT_DIR, 'screen_dir should point to content/');
      assert.strictEqual(info.state_dir, STATE_DIR, 'state_dir should point to state/');
      return Promise.resolve();
    });

    // ========== HTTP Serving ==========
    console.log('\n--- HTTP Serving ---');

    await test('serves waiting page when no screens exist', async () => {
      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert.strictEqual(res.status, 200);
      assert(res.body.includes('Waiting for the agent'), 'Should show waiting message');
    });

    await test('injects helper.js into waiting page', async () => {
      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert(res.body.includes('WebSocket'), 'Should have helper.js injected');
      assert(res.body.includes('toggleSelect'), 'Should have toggleSelect from helper');
      assert(res.body.includes('brainstorm'), 'Should have brainstorm API from helper');
    });

    await test('returns Content-Type text/html', async () => {
      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert(res.headers['content-type'].includes('text/html'), 'Should be text/html');
    });

    await test('serves full HTML documents as-is (not wrapped)', async () => {
      const fullDoc = '<!DOCTYPE html>\n<html><head><title>Custom</title></head><body><h1>Custom Page</h1></body></html>';
      fs.writeFileSync(path.join(CONTENT_DIR, 'full-doc.html'), fullDoc);
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert(res.body.includes('<h1>Custom Page</h1>'), 'Should contain original content');
      assert(res.body.includes('WebSocket'), 'Should still inject helper.js');
      assert(!res.body.includes('<div class="header">'), 'Should NOT wrap in frame template');
    });

    await test('wraps content fragments in frame template', async () => {
      const fragment = '<h2>Pick a layout</h2>\n<div class="options"><div class="option" data-choice="a"><div class="letter">A</div></div></div>';
      fs.writeFileSync(path.join(CONTENT_DIR, 'fragment.html'), fragment);
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert(res.body.includes('<div class="header">'), 'Fragment should get header chrome');
      assert(!res.body.includes('<!-- CONTENT -->'), 'Placeholder should be replaced');
      assert(res.body.includes('Pick a layout'), 'Fragment content should be present');
      assert(res.body.includes('data-choice="a"'), 'Fragment interactive elements intact');
    });

    await test('preserves literal replacement tokens in content fragments', async () => {
      const tokens = ["$'", '$`', '$&', '$$', '$1', '$<name>'];
      const fragment = '<h2>Literal tokens</h2><pre>' + tokens.join(' | ') + '</pre>';
      fs.writeFileSync(path.join(CONTENT_DIR, 'literal-tokens.html'), fragment);
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert.strictEqual(res.status, 200);
      assert(res.body.includes(fragment), 'Fragment must be inserted verbatim');
      assert.strictEqual(res.body.split('<div class="header">').length - 1, 1, 'Frame chrome must not be duplicated');
      assert(!res.body.includes('<!-- CONTENT -->'), 'Replacement tokens must not restore the placeholder');
      assert(res.body.includes('WebSocket'), 'Helper must still be injected');
    });

    await test('serves newest file by mtime', async () => {
      fs.writeFileSync(path.join(CONTENT_DIR, 'older.html'), '<h2>Older</h2>');
      await sleep(100);
      fs.writeFileSync(path.join(CONTENT_DIR, 'newer.html'), '<h2>Newer</h2>');
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert(res.body.includes('Newer'), 'Should serve newest file');
    });

    await test('ignores non-html files for serving', async () => {
      // Write a newer non-HTML file — should still serve newest .html
      fs.writeFileSync(path.join(CONTENT_DIR, 'data.json'), '{"not": "html"}');
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert(res.body.includes('Newer'), 'Should still serve newest HTML');
      assert(!res.body.includes('"not"'), 'Should not serve JSON');
    });

    await test('ignores macOS resource-fork dotfiles (._*.html) when serving', async () => {
      // On macOS/ExFAT/SMB, the OS writes ._name.html sidecar files holding
      // binary metadata. They end with .html but must never be served as a screen.
      fs.writeFileSync(path.join(CONTENT_DIR, 'real-screen.html'), '<h2>Real Screen Content</h2>');
      await sleep(100);
      fs.writeFileSync(path.join(CONTENT_DIR, '._real-screen.html'), 'Mac OS X resource fork garbage');
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert(res.body.includes('Real Screen Content'), 'should serve the real screen, not the newer ._ sidecar');
      assert(!res.body.includes('resource fork garbage'), 'must not serve ._*.html dotfile content');
    });

    await test('does not serve dotfiles via /files/', async () => {
      fs.writeFileSync(path.join(CONTENT_DIR, '._secret.html'), 'dotfile body should not be served');
      const res = await fetch(`http://localhost:${TEST_PORT}/files/._secret.html`);
      assert.strictEqual(res.status, 404, '/files/ must 404 on dotfiles');
    });

    await test('GET /files/ (empty name) returns 404 and does not crash the server', async () => {
      const res = await fetch(`http://localhost:${TEST_PORT}/files/`);
      assert.strictEqual(res.status, 404, '/files/ (the content dir) must 404, not EISDIR-crash');
      // The server must still be alive afterward.
      const alive = await fetch(`http://localhost:${TEST_PORT}/`);
      assert.strictEqual(alive.status, 200, 'server must survive a /files/ request');
    });

    await test('does not serve symlinks that escape content dir via /files/', async () => {
      const target = path.join(STATE_DIR, 'server-info');
      const link = path.join(CONTENT_DIR, 'linked-server-info.txt');
      try { fs.unlinkSync(link); } catch (e) {}
      ensureSymlinkWorks(target, link);
      fs.symlinkSync(target, link);

      const res = await fetch(`http://localhost:${TEST_PORT}/files/linked-server-info.txt`);
      assert.strictEqual(res.status, 404, 'symlink to state/server-info must not be served');
      assert(!res.body.includes('server-started'), 'response must not include server-info body');
    });

    await test('does not serve hard links to files outside content dir via /files/', async () => {
      const target = path.join(STATE_DIR, 'server-info');
      const link = path.join(CONTENT_DIR, 'hard-linked-server-info.txt');
      try { fs.unlinkSync(link); } catch (e) {}
      fs.linkSync(target, link);

      const res = await fetch(`http://localhost:${TEST_PORT}/files/hard-linked-server-info.txt`);
      assert.strictEqual(res.status, 404, 'hard link to state/server-info must not be served');
      assert(!res.body.includes('server-started'), 'response must not include server-info body');
    });

    await test('does not serve symlinks that escape content dir via root screen selection', async () => {
      const target = path.join(STATE_DIR, 'server-info');
      const link = path.join(CONTENT_DIR, 'root-linked-server-info.html');
      try { fs.unlinkSync(link); } catch (e) {}
      ensureSymlinkWorks(target, link);
      fs.symlinkSync(target, link);
      const future = new Date(Date.now() + 2000);
      fs.utimesSync(target, future, future);
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert.strictEqual(res.status, 200);
      assert(!res.body.includes('"type":"server-started"'), 'root screen must not serve state/server-info through a symlink');
      assert(!res.body.includes('"state_dir"'), 'root screen must not include server-info body');
    });

    await test('does not serve hard links that escape content dir via root screen selection', async () => {
      const target = path.join(STATE_DIR, 'server-info');
      const link = path.join(CONTENT_DIR, 'root-hard-linked-server-info.html');
      try { fs.unlinkSync(link); } catch (e) {}
      try {
        fs.linkSync(target, link);
      } catch (e) {
        skip(`hardlink creation unavailable on this host: ${e.message}`);
      }
      const linkStat = fs.lstatSync(link);
      if (linkStat.nlink <= 1) {
        skip(`hardlink nlink did not expose multiple links: ${linkStat.nlink}`);
      }
      const future = new Date(Date.now() + 3000);
      fs.utimesSync(target, future, future);
      await sleep(300);

      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert.strictEqual(res.status, 200);
      assert(!res.body.includes('"type":"server-started"'), 'root screen must not serve state/server-info through a hardlink');
      assert(!res.body.includes('"state_dir"'), 'root screen must not include server-info body');
    });

    await test('returns 404 for non-root paths', async () => {
      const res = await fetch(`http://localhost:${TEST_PORT}/other`);
      assert.strictEqual(res.status, 404);
    });

    // ========== WebSocket Communication ==========
    console.log('\n--- WebSocket Communication ---');

    await test('accepts WebSocket upgrade on /', async () => {
      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise((resolve, reject) => {
        ws.on('open', resolve);
        ws.on('error', reject);
      });
      ws.close();
    });

    await test('relays user events to stdout with source field', async () => {
      stdoutAccum = '';
      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
      await sleep(300);

      assert(stdoutAccum.includes('"source":"user-event"'), 'Should tag with source');
      assert(stdoutAccum.includes('Test Button'), 'Should include event data');
      ws.close();
    });

    await test('writes choice events to state/events', async () => {
      // Clean up events from prior tests
      await settleWatcher();
      const eventsFile = path.join(STATE_DIR, 'events');
      if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);

      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      ws.send(JSON.stringify({ type: 'click', choice: 'b', text: 'Option B' }));
      await sleep(300);

      assert(fs.existsSync(eventsFile), '.events should exist');
      const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\n');
      const event = JSON.parse(lines[lines.length - 1]);
      assert.strictEqual(event.choice, 'b');
      assert.strictEqual(event.text, 'Option B');
      ws.close();
    });

    await test('does NOT write non-choice events to state/events', async () => {
      const eventsFile = path.join(STATE_DIR, 'events');
      if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);

      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      ws.send(JSON.stringify({ type: 'hover', text: 'Something' }));
      await sleep(300);

      // Non-choice events should not create .events file
      assert(!fs.existsSync(eventsFile), '.events should not exist for non-choice events');
      ws.close();
    });

    await test('handles multiple concurrent WebSocket clients', async () => {
      const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await Promise.all([
        new Promise(resolve => ws1.on('open', resolve)),
        new Promise(resolve => ws2.on('open', resolve))
      ]);

      let ws1Reload = false;
      let ws2Reload = false;
      ws1.on('message', (data) => {
        if (JSON.parse(data.toString()).type === 'reload') ws1Reload = true;
      });
      ws2.on('message', (data) => {
        if (JSON.parse(data.toString()).type === 'reload') ws2Reload = true;
      });

      fs.writeFileSync(path.join(CONTENT_DIR, 'multi-client.html'), '<h2>Multi</h2>');

      await waitFor(() => ws1Reload, 'Client 1 should receive reload');
      await waitFor(() => ws2Reload, 'Client 2 should receive reload');
      ws1.close();
      ws2.close();
    });

    await test('cleans up closed clients from broadcast list', async () => {
      const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws1.on('open', resolve));
      ws1.close();
      await sleep(100);

      // This should not throw even though ws1 is closed
      const afterClose = path.join(CONTENT_DIR, 'after-close.html');
      fs.writeFileSync(afterClose, '<h2>After</h2>');
      await waitFor(() => screenLogged('screen-added', afterClose),
        'Server should process the new screen');
      // If we got here without error, the test passes
    });

    await test('handles malformed JSON from client gracefully', async () => {
      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      // Send invalid JSON — server should not crash
      ws.send('not json at all {{{');
      await sleep(300);

      // Verify server is still responsive
      const res = await fetch(`http://localhost:${TEST_PORT}/`);
      assert.strictEqual(res.status, 200, 'Server should still be running');
      ws.close();
    });

    // ========== File Watching ==========
    console.log('\n--- File Watching ---');

    await test('sends reload on new .html file', async () => {
      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      let gotReload = false;
      ws.on('message', (data) => {
        if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
      });

      fs.writeFileSync(path.join(CONTENT_DIR, 'watch-new.html'), '<h2>New</h2>');

      await waitFor(() => gotReload, 'Should send reload on new file');
      ws.close();
    });

    await test('sends reload on .html file change', async () => {
      const filePath = path.join(CONTENT_DIR, 'watch-change.html');
      fs.writeFileSync(filePath, '<h2>Original</h2>');
      await waitFor(() => screenLogged('screen-added', filePath),
        'Server should process the original file');

      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      let gotReload = false;
      ws.on('message', (data) => {
        if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
      });

      fs.writeFileSync(filePath, '<h2>Modified</h2>');

      await waitFor(() => gotReload, 'Should send reload on file change');
      ws.close();
    });

    await test('does NOT send reload for non-.html files', async () => {
      await settleWatcher();
      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      let reloads = 0;
      ws.on('message', (data) => {
        if (JSON.parse(data.toString()).type === 'reload') reloads++;
      });

      fs.writeFileSync(path.join(CONTENT_DIR, 'data.txt'), 'not html');
      await settleWatcher();

      // The only reload is the one for settleWatcher's own file.
      assert.strictEqual(reloads, 1, 'Should NOT reload for non-HTML files');
      ws.close();
    });

    await test('does NOT send reload for ._*.html resource-fork dotfiles', async () => {
      await settleWatcher();
      const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
      await new Promise(resolve => ws.on('open', resolve));

      let reloads = 0;
      ws.on('message', (data) => {
        if (JSON.parse(data.toString()).type === 'reload') reloads++;
      });

      fs.writeFileSync(path.join(CONTENT_DIR, '._sidecar.html'), 'resource fork');
      await settleWatcher();

      // The only reload is the one for settleWatcher's own file.
      assert.strictEqual(reloads, 1, 'a ._ dotfile appearing must not trigger a reload');
      ws.close();
    });

    await test('clears state/events on new screen', async () => {
      // Create an events file
      const eventsFile = path.join(STATE_DIR, 'events');
      fs.writeFileSync(eventsFile, '{"choice":"a"}\n');
      assert(fs.existsSync(eventsFile));

      fs.writeFileSync(path.join(CONTENT_DIR, 'clear-events.html'), '<h2>New screen</h2>');

      await waitFor(() => !fs.existsSync(eventsFile), 'state/events should be cleared on new screen');
    });

    await test('logs screen-added on new file', async () => {
      stdoutAccum = '';
      fs.writeFileSync(path.join(CONTENT_DIR, 'log-test.html'), '<h2>Log</h2>');

      await waitFor(() => stdoutAccum.includes('screen-added'), 'Should log screen-added');
    });

    await test('logs screen-updated on file change', async () => {
      const filePath = path.join(CONTENT_DIR, 'log-update.html');
      fs.writeFileSync(filePath, '<h2>V1</h2>');
      await waitFor(() => screenLogged('screen-added', filePath),
        'Server should process V1');

      stdoutAccum = '';
      fs.writeFileSync(filePath, '<h2>V2</h2>');

      await waitFor(() => stdoutAccum.includes('screen-updated'), 'Should log screen-updated');
    });

    // ========== Helper.js Content ==========
    console.log('\n--- Helper.js Verification ---');

    await test('helper.js defines required APIs', () => {
      const helperContent = fs.readFileSync(
        path.join(__dirname, '../../skills/brainstorming/scripts/helper.js'), 'utf-8'
      );
      assert(helperContent.includes('toggleSelect'), 'Should define toggleSelect');
      assert(helperContent.includes('sendEvent'), 'Should define sendEvent');
      assert(helperContent.includes('selectedChoice'), 'Should track selectedChoice');
      assert(helperContent.includes('brainstorm'), 'Should expose brainstorm API');
      return Promise.resolve();
    });

    // ========== Frame Template ==========
    console.log('\n--- Frame Template Verification ---');

    await test('frame template has required structure', () => {
      const template = fs.readFileSync(
        path.join(__dirname, '../../skills/brainstorming/scripts/frame-template.html'), 'utf-8'
      );
      assert(template.includes('<div class="header">'), 'Should have top header markup');
      assert(!template.includes('indicator-bar'), 'Should not have footer chrome');
      assert(!template.includes('indicator-text'), 'Header should not render selection indicator text');
      assert(template.includes('<!-- BRANDING -->'), 'Should have branding placeholder');
      assert(template.includes('<div class="status">Connecting…</div>'), 'Header should include connection status');
      assert(template.includes('grid-template-columns: minmax(0, 1fr) auto;'), 'Header should let brand text shrink before the status column');
      assert(template.includes('padding: 0.5rem 1.5rem;'), 'Header should keep equal left and right edge padding');
      assert(template.includes('.header .brand { justify-self: start; width: 100%; font-size: 0.75rem; line-height: 1; }'), 'Header brand should align left, fill its grid track, and match header text size');
      assert(template.includes('.header .status { grid-column: 2; line-height: 1; }'), 'Header status should sit in the right column');
      assert(!template.includes('<div></div>'), 'Header should not use an empty spacer before branding');
      assert(template.includes('<!-- CONTENT -->'), 'Should have content placeholder');
      assert(template.includes('frame-content'), 'Should have content container');
      return Promise.resolve();
    });

    // ========== Summary ==========
    console.log(`\n--- Results: ${passed} passed, ${failed} failed, ${skipped} skipped ---`);
    // exitCode, not exit(): exit() would skip the finally below and orphan the server.
    if (failed > 0) process.exitCode = 1;

  } finally {
    server.kill();
    await sleep(100);
    cleanup();
  }
}

runTests().catch(err => {
  console.error('Test failed:', err);
  process.exit(1);
});
tests/brainstorm-server/ws-protocol.test.js 408 řádků
/**
 * Unit tests for the zero-dependency WebSocket protocol implementation.
 *
 * Tests the WebSocket frame encoding/decoding, handshake computation,
 * and protocol-level behavior independent of the HTTP server.
 *
 * The module under test exports:
 *   - computeAcceptKey(clientKey) -> string
 *   - encodeFrame(opcode, payload) -> Buffer
 *   - decodeFrame(buffer) -> { opcode, payload, bytesConsumed } | null
 *   - OPCODES: { TEXT, CLOSE, PING, PONG }
 */

const assert = require('assert');
const crypto = require('crypto');
const path = require('path');

// The module under test — will be the new zero-dep server file
const SERVER_PATH = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');
let ws;

try {
  ws = require(SERVER_PATH);
} catch (e) {
  // Module doesn't exist yet (TDD — tests written before implementation)
  console.error(`Cannot load ${SERVER_PATH}: ${e.message}`);
  console.error('This is expected if running tests before implementation.');
  process.exit(1);
}

function runTests() {
  let passed = 0;
  let failed = 0;

  function test(name, fn) {
    try {
      fn();
      console.log(`  PASS: ${name}`);
      passed++;
    } catch (e) {
      console.log(`  FAIL: ${name}`);
      console.log(`    ${e.message}`);
      failed++;
    }
  }

  // ========== Handshake ==========
  console.log('\n--- WebSocket Handshake ---');

  test('computeAcceptKey produces correct RFC 6455 accept value', () => {
    // RFC 6455 Section 4.2.2 example
    // The magic GUID is "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    const clientKey = 'dGhlIHNhbXBsZSBub25jZQ==';
    const expected = 's3pPLMBiTxaQ9kYGzzhZRbK+xOo=';
    assert.strictEqual(ws.computeAcceptKey(clientKey), expected);
  });

  test('computeAcceptKey produces valid base64 for random keys', () => {
    for (let i = 0; i < 10; i++) {
      const randomKey = crypto.randomBytes(16).toString('base64');
      const result = ws.computeAcceptKey(randomKey);
      // Result should be valid base64
      assert.strictEqual(Buffer.from(result, 'base64').toString('base64'), result);
      // SHA-1 output is 20 bytes, base64 encoded = 28 chars
      assert.strictEqual(result.length, 28);
    }
  });

  // ========== Frame Encoding ==========
  console.log('\n--- Frame Encoding (server -> client) ---');

  test('encodes small text frame (< 126 bytes)', () => {
    const payload = 'Hello';
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, Buffer.from(payload));
    // FIN bit + TEXT opcode = 0x81, length = 5
    assert.strictEqual(frame[0], 0x81);
    assert.strictEqual(frame[1], 5);
    assert.strictEqual(frame.slice(2).toString(), 'Hello');
    assert.strictEqual(frame.length, 7);
  });

  test('encodes empty text frame', () => {
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, Buffer.alloc(0));
    assert.strictEqual(frame[0], 0x81);
    assert.strictEqual(frame[1], 0);
    assert.strictEqual(frame.length, 2);
  });

  test('encodes medium text frame (126-65535 bytes)', () => {
    const payload = Buffer.alloc(200, 0x41); // 200 'A's
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);
    assert.strictEqual(frame[0], 0x81);
    assert.strictEqual(frame[1], 126); // extended length marker
    assert.strictEqual(frame.readUInt16BE(2), 200);
    assert.strictEqual(frame.slice(4).toString(), payload.toString());
    assert.strictEqual(frame.length, 204);
  });

  test('encodes frame at exactly 126 bytes (boundary)', () => {
    const payload = Buffer.alloc(126, 0x42);
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);
    assert.strictEqual(frame[1], 126); // extended length marker
    assert.strictEqual(frame.readUInt16BE(2), 126);
    assert.strictEqual(frame.length, 130);
  });

  test('encodes frame at exactly 125 bytes (max small)', () => {
    const payload = Buffer.alloc(125, 0x43);
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);
    assert.strictEqual(frame[1], 125);
    assert.strictEqual(frame.length, 127);
  });

  test('encodes large frame (> 65535 bytes)', () => {
    const payload = Buffer.alloc(70000, 0x44);
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);
    assert.strictEqual(frame[0], 0x81);
    assert.strictEqual(frame[1], 127); // 64-bit length marker
    // 8-byte extended length at offset 2
    const len = Number(frame.readBigUInt64BE(2));
    assert.strictEqual(len, 70000);
    assert.strictEqual(frame.length, 10 + 70000);
  });

  test('encodes close frame', () => {
    const frame = ws.encodeFrame(ws.OPCODES.CLOSE, Buffer.alloc(0));
    assert.strictEqual(frame[0], 0x88); // FIN + CLOSE
    assert.strictEqual(frame[1], 0);
  });

  test('encodes pong frame with payload', () => {
    const payload = Buffer.from('ping-data');
    const frame = ws.encodeFrame(ws.OPCODES.PONG, payload);
    assert.strictEqual(frame[0], 0x8A); // FIN + PONG
    assert.strictEqual(frame[1], payload.length);
    assert.strictEqual(frame.slice(2).toString(), 'ping-data');
  });

  test('server frames are never masked (per RFC 6455)', () => {
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, Buffer.from('test'));
    // Bit 7 of byte 1 is the mask bit — must be 0 for server frames
    assert.strictEqual(frame[1] & 0x80, 0);
  });

  // ========== Frame Decoding ==========
  console.log('\n--- Frame Decoding (client -> server) ---');

  // Helper: create a masked client frame
  function makeClientFrame(opcode, payload, fin = true) {
    const buf = Buffer.from(payload);
    const mask = crypto.randomBytes(4);
    const masked = Buffer.alloc(buf.length);
    for (let i = 0; i < buf.length; i++) {
      masked[i] = buf[i] ^ mask[i % 4];
    }

    let header;
    const finBit = fin ? 0x80 : 0x00;
    if (buf.length < 126) {
      header = Buffer.alloc(6);
      header[0] = finBit | opcode;
      header[1] = 0x80 | buf.length; // mask bit set
      mask.copy(header, 2);
    } else if (buf.length < 65536) {
      header = Buffer.alloc(8);
      header[0] = finBit | opcode;
      header[1] = 0x80 | 126;
      header.writeUInt16BE(buf.length, 2);
      mask.copy(header, 4);
    } else {
      header = Buffer.alloc(14);
      header[0] = finBit | opcode;
      header[1] = 0x80 | 127;
      header.writeBigUInt64BE(BigInt(buf.length), 2);
      mask.copy(header, 10);
    }

    return Buffer.concat([header, masked]);
  }

  test('decodes small masked text frame', () => {
    const frame = makeClientFrame(0x01, 'Hello');
    const result = ws.decodeFrame(frame);
    assert(result, 'Should return a result');
    assert.strictEqual(result.opcode, ws.OPCODES.TEXT);
    assert.strictEqual(result.payload.toString(), 'Hello');
    assert.strictEqual(result.bytesConsumed, frame.length);
  });

  test('decodes empty masked text frame', () => {
    const frame = makeClientFrame(0x01, '');
    const result = ws.decodeFrame(frame);
    assert(result, 'Should return a result');
    assert.strictEqual(result.opcode, ws.OPCODES.TEXT);
    assert.strictEqual(result.payload.length, 0);
  });

  test('decodes medium masked text frame (126-65535 bytes)', () => {
    const payload = 'A'.repeat(200);
    const frame = makeClientFrame(0x01, payload);
    const result = ws.decodeFrame(frame);
    assert(result, 'Should return a result');
    assert.strictEqual(result.payload.toString(), payload);
  });

  test('decodes large masked text frame (> 65535 bytes)', () => {
    const payload = 'B'.repeat(70000);
    const frame = makeClientFrame(0x01, payload);
    const result = ws.decodeFrame(frame);
    assert(result, 'Should return a result');
    assert.strictEqual(result.payload.length, 70000);
    assert.strictEqual(result.payload.toString(), payload);
  });

  test('decodes masked close frame', () => {
    const frame = makeClientFrame(0x08, '');
    const result = ws.decodeFrame(frame);
    assert(result, 'Should return a result');
    assert.strictEqual(result.opcode, ws.OPCODES.CLOSE);
  });

  test('decodes masked ping frame', () => {
    const frame = makeClientFrame(0x09, 'ping!');
    const result = ws.decodeFrame(frame);
    assert(result, 'Should return a result');
    assert.strictEqual(result.opcode, ws.OPCODES.PING);
    assert.strictEqual(result.payload.toString(), 'ping!');
  });

  test('returns null for incomplete frame (not enough header bytes)', () => {
    const result = ws.decodeFrame(Buffer.from([0x81]));
    assert.strictEqual(result, null, 'Should return null for 1-byte buffer');
  });

  test('returns null for incomplete frame (header ok, payload truncated)', () => {
    // Create a valid frame then truncate it
    const frame = makeClientFrame(0x01, 'Hello World');
    const truncated = frame.slice(0, frame.length - 3);
    const result = ws.decodeFrame(truncated);
    assert.strictEqual(result, null, 'Should return null for truncated frame');
  });

  test('returns null for incomplete extended-length header', () => {
    // Frame claiming 16-bit length but only 3 bytes total
    const buf = Buffer.alloc(3);
    buf[0] = 0x81;
    buf[1] = 0x80 | 126; // masked, 16-bit extended
    // Missing the 2 length bytes + mask
    const result = ws.decodeFrame(buf);
    assert.strictEqual(result, null);
  });

  test('rejects unmasked client frame', () => {
    // Server MUST reject unmasked client frames per RFC 6455 Section 5.1
    const buf = Buffer.alloc(7);
    buf[0] = 0x81; // FIN + TEXT
    buf[1] = 5;    // length 5, NO mask bit
    Buffer.from('Hello').copy(buf, 2);
    assert.throws(() => ws.decodeFrame(buf), /mask/i, 'Should reject unmasked client frame');
  });

  test('handles multiple frames in a single buffer', () => {
    const frame1 = makeClientFrame(0x01, 'first');
    const frame2 = makeClientFrame(0x01, 'second');
    const combined = Buffer.concat([frame1, frame2]);

    const result1 = ws.decodeFrame(combined);
    assert(result1, 'Should decode first frame');
    assert.strictEqual(result1.payload.toString(), 'first');
    assert.strictEqual(result1.bytesConsumed, frame1.length);

    const result2 = ws.decodeFrame(combined.slice(result1.bytesConsumed));
    assert(result2, 'Should decode second frame');
    assert.strictEqual(result2.payload.toString(), 'second');
  });

  test('correctly unmasks with all mask byte values', () => {
    // Use a known mask to verify unmasking arithmetic
    const payload = Buffer.from('ABCDEFGH');
    const mask = Buffer.from([0xFF, 0x00, 0xAA, 0x55]);
    const masked = Buffer.alloc(payload.length);
    for (let i = 0; i < payload.length; i++) {
      masked[i] = payload[i] ^ mask[i % 4];
    }

    // Build frame manually
    const header = Buffer.alloc(6);
    header[0] = 0x81; // FIN + TEXT
    header[1] = 0x80 | payload.length;
    mask.copy(header, 2);
    const frame = Buffer.concat([header, masked]);

    const result = ws.decodeFrame(frame);
    assert.strictEqual(result.payload.toString(), 'ABCDEFGH');
  });

  // ========== Frame Encoding Boundary at 65535/65536 ==========
  console.log('\n--- Frame Size Boundaries ---');

  test('encodes frame at exactly 65535 bytes (max 16-bit)', () => {
    const payload = Buffer.alloc(65535, 0x45);
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);
    assert.strictEqual(frame[1], 126);
    assert.strictEqual(frame.readUInt16BE(2), 65535);
    assert.strictEqual(frame.length, 4 + 65535);
  });

  test('encodes frame at exactly 65536 bytes (min 64-bit)', () => {
    const payload = Buffer.alloc(65536, 0x46);
    const frame = ws.encodeFrame(ws.OPCODES.TEXT, payload);
    assert.strictEqual(frame[1], 127);
    assert.strictEqual(Number(frame.readBigUInt64BE(2)), 65536);
    assert.strictEqual(frame.length, 10 + 65536);
  });

  test('decodes frame at 65535 bytes boundary', () => {
    const payload = 'X'.repeat(65535);
    const frame = makeClientFrame(0x01, payload);
    const result = ws.decodeFrame(frame);
    assert(result);
    assert.strictEqual(result.payload.length, 65535);
  });

  test('decodes frame at 65536 bytes boundary', () => {
    const payload = 'Y'.repeat(65536);
    const frame = makeClientFrame(0x01, payload);
    const result = ws.decodeFrame(frame);
    assert(result);
    assert.strictEqual(result.payload.length, 65536);
  });

  test('rejects oversized 64-bit frames before payload allocation', () => {
    const mask = Buffer.from([0x00, 0x00, 0x00, 0x00]);
    const header = Buffer.alloc(14);
    header[0] = 0x81; // FIN + TEXT
    header[1] = 0x80 | 127; // masked, 64-bit length
    header.writeBigUInt64BE(BigInt(ws.MAX_FRAME_PAYLOAD_BYTES) + 1n, 2);
    mask.copy(header, 10);

    assert.throws(
      () => ws.decodeFrame(header),
      /exceeds maximum allowed size/i,
      'oversized advertised payload must be rejected from header alone'
    );
  });

  // ========== Close Frame with Status Code ==========
  console.log('\n--- Close Frame Details ---');

  test('decodes close frame with status code', () => {
    // Close frame payload: 2-byte status code + optional reason
    const statusBuf = Buffer.alloc(2);
    statusBuf.writeUInt16BE(1000); // Normal closure
    const frame = makeClientFrame(0x08, statusBuf);
    const result = ws.decodeFrame(frame);
    assert.strictEqual(result.opcode, ws.OPCODES.CLOSE);
    assert.strictEqual(result.payload.readUInt16BE(0), 1000);
  });

  test('decodes close frame with status code and reason', () => {
    const reason = 'Normal shutdown';
    const payload = Buffer.alloc(2 + reason.length);
    payload.writeUInt16BE(1000);
    payload.write(reason, 2);
    const frame = makeClientFrame(0x08, payload);
    const result = ws.decodeFrame(frame);
    assert.strictEqual(result.opcode, ws.OPCODES.CLOSE);
    assert.strictEqual(result.payload.slice(2).toString(), reason);
  });

  // ========== JSON Roundtrip ==========
  console.log('\n--- JSON Message Roundtrip ---');

  test('roundtrip encode/decode of JSON message', () => {
    const msg = { type: 'reload' };
    const payload = Buffer.from(JSON.stringify(msg));
    const serverFrame = ws.encodeFrame(ws.OPCODES.TEXT, payload);

    // Verify we can read what we encoded (unmasked server frame)
    // Server frames don't go through decodeFrame (that expects masked),
    // so just verify the payload bytes directly
    let offset;
    if (serverFrame[1] < 126) {
      offset = 2;
    } else if (serverFrame[1] === 126) {
      offset = 4;
    } else {
      offset = 10;
    }
    const decoded = JSON.parse(serverFrame.slice(offset).toString());
    assert.deepStrictEqual(decoded, msg);
  });

  test('roundtrip masked client JSON message', () => {
    const msg = { type: 'click', choice: 'a', text: 'Option A', timestamp: 1706000101 };
    const frame = makeClientFrame(0x01, JSON.stringify(msg));
    const result = ws.decodeFrame(frame);
    const decoded = JSON.parse(result.payload.toString());
    assert.deepStrictEqual(decoded, msg);
  });

  // ========== Summary ==========
  console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  if (failed > 0) process.exit(1);
}

runTests();
tests/brainstorm-server/helper.test.js 198 řádků
/**
 * Tests for the injected browser client (helper.js).
 *
 * helper.js runs in the browser, so its DOM behaviour is exercised live; here we
 * unit-test the pure reconnect-backoff function it exports and assert that the
 * reconnect / status / tombstone wiring is present.
 */

const assert = require('assert');
const fs = require('fs');
const path = require('path');

const HELPER = path.join(__dirname, '../../skills/brainstorming/scripts/helper.js');

const src = fs.readFileSync(HELPER, 'utf-8');

// helper.js is browser code, and the repo is an ES module package, so a plain
// require() won't surface its exports. Evaluate the source in a CommonJS sandbox
// with no `window`, so only the exported pure helpers run (not the browser code).
const moduleShim = { exports: {} };
new Function('module', src)(moduleShim);
const { nextReconnectDelay, MIN_RECONNECT_MS, MAX_RECONNECT_MS, TOMBSTONE_AFTER_MS } = moduleShim.exports;

let passed = 0, failed = 0;
function test(name, fn) {
  try { fn(); console.log(`  PASS: ${name}`); passed++; }
  catch (e) { console.log(`  FAIL: ${name}`); console.log(`    ${e.message}`); failed++; }
}

console.log('\n--- Backoff (pure) ---');

test('doubles the delay each call', () => {
  assert.strictEqual(nextReconnectDelay(500, 30000), 1000);
  assert.strictEqual(nextReconnectDelay(1000, 30000), 2000);
  assert.strictEqual(nextReconnectDelay(2000, 30000), 4000);
});

test('caps at the maximum', () => {
  assert.strictEqual(nextReconnectDelay(20000, 30000), 30000);
  assert.strictEqual(nextReconnectDelay(30000, 30000), 30000);
});

test('full progression from MIN caps at MAX and never exceeds it', () => {
  const seq = [MIN_RECONNECT_MS];
  let d = MIN_RECONNECT_MS;
  for (let i = 0; i < 10; i++) { d = nextReconnectDelay(d, MAX_RECONNECT_MS); seq.push(d); }
  assert.strictEqual(seq[0], 500);
  assert.deepStrictEqual(seq.slice(0, 7), [500, 1000, 2000, 4000, 8000, 16000, 30000]);
  assert(seq.every(v => v <= MAX_RECONNECT_MS), 'never exceeds max');
  assert.strictEqual(seq[seq.length - 1], 30000, 'settles at the cap');
});

test('exposes sane constants', () => {
  assert.strictEqual(MIN_RECONNECT_MS, 500);
  assert.strictEqual(MAX_RECONNECT_MS, 30000);
  assert(TOMBSTONE_AFTER_MS >= 5000, 'tombstone grace is at least a few seconds');
});

console.log('\n--- Wiring (source) ---');

test('reflects all three connection states', () => {
  assert(/Connected/.test(src) && /Reconnecting/.test(src) && /Disconnected/.test(src),
    'should set Connected / Reconnecting / Disconnected status');
  assert(src.includes("setProperty('--status-color'"), 'drives the status dot via --status-color');
});

test('renders a tombstone overlay when paused', () => {
  assert(src.includes('bs-tombstone'), 'creates the tombstone element');
  assert(/Companion paused/.test(src), 'tombstone explains the companion paused');
});

test('hardens reconnection (onerror, null socket, clears pending timer)', () => {
  assert(src.includes('onerror'), 'handles onerror');
  assert(/ws = null/.test(src), 'nulls the socket on close so sendEvent queues');
  assert(src.includes('clearTimeout'), 'clears a pending reconnect before scheduling another');
  assert(src.includes('nextReconnectDelay'), 'uses exponential backoff for reconnects');
});

test('reloads on recovery and on reload messages', () => {
  assert(/location\.reload\(\)/.test(src), 'reloads to pick up restarted/updated content');
});

console.log('\n--- Reconnect state machine (mocked browser) ---');

// Drive helper.js's browser code against mocked DOM/WebSocket/timers/clock so we
// can exercise the actual reconnect/status/tombstone behaviour, not just grep it.
function makeEnv() {
  const state = { now: 1000, timers: [], reloads: 0, replacements: [], appended: [], sessionKey: 'stored-key-abc' };
  const sockets = [];
  const statusEl = { textContent: '', style: { setProperty() {} } };
  class FakeWS {
    constructor(url) { this.url = url; this.readyState = 0; this.onopen = this.onclose = this.onmessage = this.onerror = null; sockets.push(this); }
    send() {}
    close() { this.readyState = 3; if (this.onclose) this.onclose(); }
    open() { this.readyState = 1; if (this.onopen) this.onopen(); }
  }
  FakeWS.OPEN = 1;
  const env = {
    module: { exports: {} },
    window: {
      location: {
        host: 'localhost:7777',
        reload() { state.reloads++; },
        replace(url) { state.replacements.push(url); }
      },
      sessionStorage: { getItem: (key) => key === 'brainstorm-session-key' ? state.sessionKey : null }
    },
    document: {
      querySelector: (s) => s === '.status' ? statusEl : null,
      getElementById: () => null,
      createElement: () => ({ style: {}, id: '' }),
      addEventListener() {},
      body: { appendChild: (el) => state.appended.push(el) }
    },
    WebSocket: FakeWS,
    setTimeout: (fn, ms) => { state.timers.push({ fn, ms, fired: false, cleared: false }); return state.timers.length; },
    clearTimeout: (id) => { if (state.timers[id - 1]) state.timers[id - 1].cleared = true; },
    Date: { now: () => state.now },
    console
  };
  return {
    state, statusEl, sockets,
    boot() { new Function(...Object.keys(env), src)(...Object.values(env)); },
    advance(ms) { state.now += ms; },
    last() { return sockets[sockets.length - 1]; },
    fireReconnect() {
      const t = [...state.timers].reverse().find(x => !x.fired && !x.cleared);
      if (!t) throw new Error('no reconnect scheduled');
      t.fired = true; t.fn();
    }
  };
}

test('uses sessionStorage key in the WebSocket URL when present', () => {
  const e = makeEnv();
  e.state.sessionKey = 'stored-key-abc';
  e.boot();
  assert.strictEqual(e.sockets[0].url, 'ws://localhost:7777/?key=stored-key-abc');
});

test('uses cookie-only WebSocket URL when no sessionStorage key is present', () => {
  const e = makeEnv();
  e.state.sessionKey = null;
  e.boot();
  assert.strictEqual(e.sockets[0].url, 'ws://localhost:7777');
});

test('on disconnect shows Reconnecting and schedules a 500ms reconnect', () => {
  const e = makeEnv(); e.boot();
  e.last().open();
  assert.strictEqual(e.statusEl.textContent, 'Connected');
  e.last().close();
  assert.strictEqual(e.statusEl.textContent, 'Reconnecting…');
  assert.strictEqual(e.state.timers[e.state.timers.length - 1].ms, 500);
});

test('reconnect delay backs off 500 -> 1000 -> 2000', () => {
  const e = makeEnv(); e.boot();
  e.last().open(); e.last().close();
  e.fireReconnect(); e.last().close();
  e.fireReconnect(); e.last().close();
  assert.deepStrictEqual(e.state.timers.map(t => t.ms).slice(0, 3), [500, 1000, 2000]);
});

test('shows the tombstone and Disconnected after the grace period', () => {
  const e = makeEnv(); e.boot();
  e.last().open(); e.last().close();
  e.advance(20000);          // past TOMBSTONE_AFTER_MS while still down
  e.fireReconnect(); e.last().close();
  assert.strictEqual(e.statusEl.textContent, 'Disconnected');
  assert.strictEqual(e.state.appended.length, 1, 'tombstone appended exactly once');
});

test('rebootstraps with stored key when a tombstoned connection comes back', () => {
  const e = makeEnv(); e.boot();
  e.last().open(); e.last().close();
  e.advance(20000); e.fireReconnect(); e.last().close(); // tombstone now shown
  assert.deepStrictEqual(e.state.replacements, []);
  e.fireReconnect(); e.last().open();                    // server back (e.g. same-port restart)
  assert.strictEqual(e.state.reloads, 0, 'stored-key recovery should not reload bare /');
  assert.deepStrictEqual(e.state.replacements, ['/?key=stored-key-abc']);
});

test('reloads to recover when tombstoned and no sessionStorage key is present', () => {
  const e = makeEnv();
  e.state.sessionKey = null;
  e.boot();
  e.last().open(); e.last().close();
  e.advance(20000); e.fireReconnect(); e.last().close(); // tombstone now shown
  assert.strictEqual(e.state.reloads, 0);
  e.fireReconnect(); e.last().open();                    // server back (e.g. cookie-only page)
  assert.strictEqual(e.state.reloads, 1, 'reloads once on recovery');
  assert.deepStrictEqual(e.state.replacements, []);
});

console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
if (failed > 0) process.exit(1);
tests/brainstorm-server/browser-launcher.test.js 67 řádků
const assert = require('assert');
const {
  browserLauncherForPlatform
} = require('../../skills/brainstorming/scripts/server.cjs');

let passed = 0;
let failed = 0;

async function test(name, fn) {
  try {
    await fn();
    console.log(`  PASS: ${name}`);
    passed++;
  } catch (e) {
    console.log(`  FAIL: ${name}`);
    console.log(`    ${e.message}`);
    failed++;
  }
}

(async () => {
  console.log('\n--- Browser Launcher ---');

  await test('Windows launcher does not route URLs through cmd.exe', () => {
    const url = 'http://localhost:54122/?key=abc&x=SAFE&echo=INJECTED';
    const launcher = browserLauncherForPlatform(url, {
      platform: 'win32',
      osRelease: '10.0.26200',
      env: {}
    });

    assert.deepStrictEqual(launcher, {
      bin: 'rundll32.exe',
      args: ['url.dll,FileProtocolHandler', url]
    });
    assert(!launcher.args.includes('/c'), 'Windows launcher must not pass /c to a command interpreter');
  });

  await test('WSL launcher does not route URLs through cmd.exe', () => {
    const url = 'http://localhost:54122/?key=abc&x=SAFE&echo=INJECTED';
    const launcher = browserLauncherForPlatform(url, {
      platform: 'linux',
      osRelease: '5.15.167.4-microsoft-standard-WSL2',
      env: {}
    });

    assert.deepStrictEqual(launcher, {
      bin: 'rundll32.exe',
      args: ['url.dll,FileProtocolHandler', url]
    });
  });

  await test('Linux launcher stays headless without a display', () => {
    assert.strictEqual(
      browserLauncherForPlatform('http://localhost:1/', {
        platform: 'linux',
        osRelease: '6.0.0',
        env: {}
      }),
      null
    );
  });

  console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  if (failed > 0) process.exit(1);
})();
tests/brainstorm-server/package.json 11 řádků
{
  "name": "brainstorm-server-tests",
  "version": "1.0.0",
  "scripts": {
    "test": "node ws-protocol.test.js && node helper.test.js && node browser-launcher.test.js && node auth.test.js && node branding.test.js && node server.test.js && node lifecycle.test.js && bash start-server.test.sh && bash stop-server.test.sh"
  },
  "dependencies": {
    "ws": "^8.21.0"
  }
}
tests/brainstorm-server/package-lock.json 37 řádků
{
  "name": "brainstorm-server-tests",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "brainstorm-server-tests",
      "version": "1.0.0",
      "dependencies": {
        "ws": "^8.21.0"
      }
    },
    "node_modules/ws": {
      "version": "8.21.0",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
      "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
      "license": "MIT",
      "engines": {
        "node": ">=10.0.0"
      },
      "peerDependencies": {
        "bufferutil": "^4.0.1",
        "utf-8-validate": ">=5.0.2"
      },
      "peerDependenciesMeta": {
        "bufferutil": {
          "optional": true
        },
        "utf-8-validate": {
          "optional": true
        }
      }
    }
  }
}

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč se protokol testuje samostatně od HTTP serveru?

Frame kódování je čistá logika s mnoha hraničními případy. Unit test je rychlý, přesný a odhalí chybu hned v protokolu, ne až v integračním testu. Je to hlavní jistota, že ruční implementace RFC 6455 funguje.

2. Proč test „rejects oversized 64-bit frames before payload allocation“?

Útočník by mohl deklarovat obří délku a donutit server alokovat paměť. Test ověří, že je rámec odmítnut dřív, než se payload alokuje, tedy že limit skutečně chrání.

3. Proč se testují přesné hranice 125/126 a 65535/65536 bajtů?

RFC mění kódování délky právě na těchto hranicích (7 bit / 16 bit / 64 bit). Chyby jsou typicky „off by one“, a proto se hranice testují explicitně.

4. Proč „rejects unmasked client frame“?

Klient musí podle RFC rámce maskovat. Nemaskovaný rámec značí nekorektního nebo škodlivého klienta a server ho má odmítnout.

5. K čemu jsou testy se symlinky a hardlinky mimo content dir?

Zajišťují, že server neprozradí soubory mimo content/. Symlink nebo hardlink by jinak umožnil číst libovolný soubor, na který uživatel má přístup (path traversal).

6. Proč se `.html` filtrují testy s `._*.html` a dotfiles?

macOS vytváří resource-fork soubory ._název.html. Server je nesmí zobrazit ani vyvolat reload. Test chrání před falešnými reloady na macOS.

7. Proč testy používají port 3334 a adresář `/tmp/brainstorm-test`?

Izolace od reálného běžícího serveru. Pevný port a adresář zjednoduší test, a jeho úklid je předvídatelný.

8. Proč `helper.js` testy staticky kontrolují přítomnost kódu?

Chování v DOM se ověřuje živě v prohlížeči. Test v Node proto spouští jen čistou funkci a kontroluje, že klíčové mechanismy (stavy, tombstone, onerror) v kódu jsou, aby je někdo omylem neodstranil.

9. Proč se testuje, že Windows launcher nepoužívá `cmd.exe`?

URL může obsahovat & a jiné znaky, které cmd.exe interpretuje jako příkazy. Cesta přes cmd.exe by dovolila injekci příkazů. Test používá URL s &echo=INJECTED jako past.

10. Proč je `ws` pouze devDependency testů?

Server má být bez závislostí, ale test potřebuje spolehlivého nezávislého klienta. Nezávislá implementace ověřuje, že ručně psaný server mluví správný WebSocket.

Slovník pojmů (12)

Integration test

Test, který spouští skutečný server a komunikuje s ním přes HTTP a WebSocket.

Unit test

Test jedné funkce bez serveru (frame kódování, backoff).

RFC 6455

Specifikace WebSocket protokolu; testy kontrolují shodu.

Frame boundary

Hranice délky payloadu, kde se mění kódování (125/126, 65535/65536).

Masked frame

Klientský rámec s maskou; nemaskovaný se odmítá.

Content dir

Adresář s obrazovkami; z něj se nesmí servírovat nic jiného.

Symlink / hardlink escape

Odkaz vedoucí mimo content dir. Test ověřuje, že se nepoužije.

Resource-fork dotfile

._*.html soubory macOS.

Test client `ws`

Nezávislá WebSocket knihovna pouze pro testy.

Browser launcher

Funkce volící příkaz pro otevření prohlížeče podle platformy.

Command injection

Vložení příkazu přes nevalidovaný vstup (zde URL do cmd.exe).

`npm test` skript

Pořadí spouštění všech testů v package.json.

↑ nahoru

Testovací harness Claude Code: runner, helpery, worktree testy a analýza tokenů

Runner, assertion helpery, testy volby worktree nástroje a politiky cest a skript pro rozbor spotřeby tokenů ze session.

Tato část tvoří infrastrukturu testování skills přes Claude Code CLI. run-skill-tests.sh spouští rychlé testy, s --integration i pomalé, umí --test, --verbose a --timeout, a vypíše souhrn. test-helpers.sh poskytuje run_claude, assert_contains, assert_not_contains, assert_count, assert_order, create_test_project a create_test_plan. README popisuje požadavky a použití.

test-worktree-native-preference.sh ověřuje metodiku RED-GREEN-REFACTOR pro skilly: RED (bez kroku 1a agent použije git worktree add), GREEN (s explicitním pojmenováním nástroje agent použije EnterWorktree) a PRESSURE (totéž pod časovým tlakem s existujícím .worktrees/). test-worktree-path-policy.sh je regresní kontrola, že skilly neodkazují na starou globální cestu ~/.config/superpowers/worktrees a výchozí je .worktrees/ v kořeni projektu. analyze-token-usage.py rozloží spotřebu tokenů ze session transcriptu na hlavní session a jednotlivé subagenty.

Zdrojový kód

tests/claude-code/run-skill-tests.sh 192 řádků
#!/usr/bin/env bash
# Test runner for Claude Code skills
# Tests skills by invoking Claude Code CLI and verifying behavior
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

echo "========================================"
echo " Claude Code Skills Test Suite"
echo "========================================"
echo ""
echo "Repository: $(cd ../.. && pwd)"
echo "Test time: $(date)"
echo "Claude version: $(claude --version 2>/dev/null || echo 'not found')"
echo ""

# Check if Claude Code is available
if ! command -v claude &> /dev/null; then
    echo "ERROR: Claude Code CLI not found"
    echo "Install Claude Code first: https://code.claude.com"
    exit 1
fi

# Parse command line arguments
VERBOSE=false
SPECIFIC_TEST=""
TIMEOUT=900  # Per-test-file budget; must exceed the file's worst case
             # (test-subagent-driven-development.sh: 9 prompts x 90s each)
RUN_INTEGRATION=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --verbose|-v)
            VERBOSE=true
            shift
            ;;
        --test|-t)
            SPECIFIC_TEST="$2"
            shift 2
            ;;
        --timeout)
            TIMEOUT="$2"
            shift 2
            ;;
        --integration|-i)
            RUN_INTEGRATION=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  --verbose, -v        Show verbose output"
            echo "  --test, -t NAME      Run only the specified test"
            echo "  --timeout SECONDS    Set timeout per test (default: 900)"
            echo "  --integration, -i    Run integration tests (slow, 10-30 min)"
            echo "  --help, -h           Show this help"
            echo ""
            echo "Tests:"
            echo "  test-subagent-driven-development.sh  Test skill loading and requirements"
            echo ""
            echo "Integration Tests (use --integration):"
            echo "  test-subagent-driven-development-integration.sh  Full workflow execution"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# List of skill tests to run (fast unit tests)
tests=(
    "test-worktree-path-policy.sh"
    "test-sdd-workspace.sh"
    "test-executing-plans-scripts.sh"
    "test-subagent-driven-development.sh"
)

# Integration tests (slow, full execution)
integration_tests=(
    "test-subagent-driven-development-integration.sh"
)

# Add integration tests if requested
if [ "$RUN_INTEGRATION" = true ]; then
    tests+=("${integration_tests[@]}")
fi

# Filter to specific test if requested
if [ -n "$SPECIFIC_TEST" ]; then
    tests=("$SPECIFIC_TEST")
fi

# Track results
passed=0
failed=0
skipped=0

# Run each test
for test in "${tests[@]}"; do
    echo "----------------------------------------"
    echo "Running: $test"
    echo "----------------------------------------"

    test_path="$SCRIPT_DIR/$test"

    if [ ! -f "$test_path" ]; then
        echo "  [SKIP] Test file not found: $test"
        skipped=$((skipped + 1))
        continue
    fi

    if [ ! -x "$test_path" ]; then
        echo "  Making $test executable..."
        chmod +x "$test_path"
    fi

    start_time=$(date +%s)

    if [ "$VERBOSE" = true ]; then
        if timeout "$TIMEOUT" bash "$test_path"; then
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo ""
            echo "  [PASS] $test (${duration}s)"
            passed=$((passed + 1))
        else
            exit_code=$?
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo ""
            if [ $exit_code -eq 124 ]; then
                echo "  [FAIL] $test (timeout after ${TIMEOUT}s)"
            else
                echo "  [FAIL] $test (${duration}s)"
            fi
            failed=$((failed + 1))
        fi
    else
        # Capture output for non-verbose mode
        if output=$(timeout "$TIMEOUT" bash "$test_path" 2>&1); then
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo "  [PASS] (${duration}s)"
            passed=$((passed + 1))
        else
            exit_code=$?
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            if [ $exit_code -eq 124 ]; then
                echo "  [FAIL] (timeout after ${TIMEOUT}s)"
            else
                echo "  [FAIL] (${duration}s)"
            fi
            echo ""
            echo "  Output:"
            echo "$output" | sed 's/^/    /'
            failed=$((failed + 1))
        fi
    fi

    echo ""
done

# Print summary
echo "========================================"
echo " Test Results Summary"
echo "========================================"
echo ""
echo "  Passed:  $passed"
echo "  Failed:  $failed"
echo "  Skipped: $skipped"
echo ""

if [ "$RUN_INTEGRATION" = false ] && [ ${#integration_tests[@]} -gt 0 ]; then
    echo "Note: Integration tests were not run (they take 10-30 minutes)."
    echo "Use --integration flag to run full workflow execution tests."
    echo ""
fi

if [ $failed -gt 0 ]; then
    echo "STATUS: FAILED"
    exit 1
else
    echo "STATUS: PASSED"
    exit 0
fi
tests/claude-code/test-helpers.sh 209 řádků
#!/usr/bin/env bash
# Helper functions for Claude Code skill tests

# Run Claude Code with a prompt and capture output
# Usage: run_claude "prompt text" [timeout_seconds] [allowed_tools]
run_claude() {
    local prompt="$1"
    local timeout="${2:-60}"
    local allowed_tools="${3:-}"
    local output_file=$(mktemp)

    # Build command as an argv array so timeout wraps claude directly.
    local cmd=(claude -p "$prompt")
    if [ -n "$allowed_tools" ]; then
        cmd+=(--allowed-tools="$allowed_tools")
    fi

    # Run Claude in headless mode with timeout
    if timeout "$timeout" "${cmd[@]}" > "$output_file" 2>&1; then
        cat "$output_file"
        rm -f "$output_file"
        return 0
    else
        local exit_code=$?
        cat "$output_file" >&2
        rm -f "$output_file"
        return $exit_code
    fi
}

# Check if output contains a pattern
# Usage: assert_contains "output" "pattern" "test name"
# Matching is case-insensitive: patterns are prose keywords, and models
# freely capitalize skill terms ("Do Not Trust", "Spec Compliance").
assert_contains() {
    local output="$1"
    local pattern="$2"
    local test_name="${3:-test}"

    if echo "$output" | grep -qi "$pattern"; then
        echo "  [PASS] $test_name"
        return 0
    else
        echo "  [FAIL] $test_name"
        echo "  Expected to find: $pattern"
        echo "  In output:"
        echo "$output" | sed 's/^/    /'
        return 1
    fi
}

# Check if output does NOT contain a pattern
# Usage: assert_not_contains "output" "pattern" "test name"
assert_not_contains() {
    local output="$1"
    local pattern="$2"
    local test_name="${3:-test}"

    if echo "$output" | grep -qi "$pattern"; then
        echo "  [FAIL] $test_name"
        echo "  Did not expect to find: $pattern"
        echo "  In output:"
        echo "$output" | sed 's/^/    /'
        return 1
    else
        echo "  [PASS] $test_name"
        return 0
    fi
}

# Check if output matches a count
# Usage: assert_count "output" "pattern" expected_count "test name"
assert_count() {
    local output="$1"
    local pattern="$2"
    local expected="$3"
    local test_name="${4:-test}"

    local actual=$(echo "$output" | grep -ci "$pattern" || echo "0")

    if [ "$actual" -eq "$expected" ]; then
        echo "  [PASS] $test_name (found $actual instances)"
        return 0
    else
        echo "  [FAIL] $test_name"
        echo "  Expected $expected instances of: $pattern"
        echo "  Found $actual instances"
        echo "  In output:"
        echo "$output" | sed 's/^/    /'
        return 1
    fi
}

# Check if pattern A appears before pattern B
# Usage: assert_order "output" "pattern_a" "pattern_b" "test name"
assert_order() {
    local output="$1"
    local pattern_a="$2"
    local pattern_b="$3"
    local test_name="${4:-test}"

    # Get line numbers where patterns appear
    local line_a=$(echo "$output" | grep -ni "$pattern_a" | head -1 | cut -d: -f1)
    local line_b=$(echo "$output" | grep -ni "$pattern_b" | head -1 | cut -d: -f1)

    if [ -z "$line_a" ]; then
        echo "  [FAIL] $test_name: pattern A not found: $pattern_a"
        echo "  In output:"
        echo "$output" | sed 's/^/    /'
        return 1
    fi

    if [ -z "$line_b" ]; then
        echo "  [FAIL] $test_name: pattern B not found: $pattern_b"
        echo "  In output:"
        echo "$output" | sed 's/^/    /'
        return 1
    fi

    if [ "$line_a" -lt "$line_b" ]; then
        echo "  [PASS] $test_name (A at line $line_a, B at line $line_b)"
        return 0
    else
        echo "  [FAIL] $test_name"
        echo "  Expected '$pattern_a' before '$pattern_b'"
        echo "  But found A at line $line_a, B at line $line_b"
        return 1
    fi
}

# Create a temporary test project directory
# Usage: test_project=$(create_test_project)
create_test_project() {
    local test_dir=$(mktemp -d)
    echo "$test_dir"
}

# Cleanup test project
# Usage: cleanup_test_project "$test_dir"
cleanup_test_project() {
    local test_dir="$1"
    if [ -d "$test_dir" ]; then
        rm -rf "$test_dir"
    fi
}

# Create a simple plan file for testing
# Usage: create_test_plan "$project_dir" "$plan_name"
create_test_plan() {
    local project_dir="$1"
    local plan_name="${2:-test-plan}"
    local plan_file="$project_dir/docs/superpowers/plans/$plan_name.md"

    mkdir -p "$(dirname "$plan_file")"

    cat > "$plan_file" <<'EOF'
# Test Implementation Plan

## Task 1: Create Hello Function

Create a simple hello function that returns "Hello, World!".

**File:** `src/hello.js`

**Implementation:**
```javascript
export function hello() {
  return "Hello, World!";
}
```

**Tests:** Write a test that verifies the function returns the expected string.

**Verification:** `npm test`

## Task 2: Create Goodbye Function

Create a goodbye function that takes a name and returns a goodbye message.

**File:** `src/goodbye.js`

**Implementation:**
```javascript
export function goodbye(name) {
  return `Goodbye, ${name}!`;
}
```

**Tests:** Write tests for:
- Default name
- Custom name
- Edge cases (empty string, null)

**Verification:** `npm test`
EOF

    echo "$plan_file"
}

# Export functions for use in tests
export -f run_claude
export -f assert_contains
export -f assert_not_contains
export -f assert_count
export -f assert_order
export -f create_test_project
export -f cleanup_test_project
export -f create_test_plan
tests/claude-code/README.md 166 řádků
# Claude Code Skills Tests

Automated tests for superpowers skills using Claude Code CLI.

## Overview

This test suite verifies that skills are loaded correctly and Claude follows them as expected. Tests invoke Claude Code in headless mode (`claude -p`) and verify the behavior.

## Requirements

- Claude Code CLI installed and in PATH (`claude --version` should work)
- Local superpowers plugin installed (see main README for installation)

## Running Tests

### Run all fast tests (recommended):
```bash
./run-skill-tests.sh
```

### Run integration tests (slow, 10-30 minutes):
```bash
./run-skill-tests.sh --integration
```

### Run specific test:
```bash
./run-skill-tests.sh --test test-subagent-driven-development.sh
```

### Run with verbose output:
```bash
./run-skill-tests.sh --verbose
```

### Set custom timeout:
```bash
./run-skill-tests.sh --timeout 1800  # 30 minutes for integration tests
```

## Test Structure

### test-helpers.sh
Common functions for skills testing:
- `run_claude "prompt" [timeout]` - Run Claude with prompt
- `assert_contains output pattern name` - Verify pattern exists
- `assert_not_contains output pattern name` - Verify pattern absent
- `assert_count output pattern count name` - Verify exact count
- `assert_order output pattern_a pattern_b name` - Verify order
- `create_test_project` - Create temp test directory
- `create_test_plan project_dir` - Create sample plan file

### Test Files

Each test file:
1. Sources `test-helpers.sh`
2. Runs Claude Code with specific prompts
3. Verifies expected behavior using assertions
4. Returns 0 on success, non-zero on failure

## Example Test

```bash
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"

echo "=== Test: My Skill ==="

# Ask Claude about the skill
output=$(run_claude "What does the my-skill skill do?" 30)

# Verify response
assert_contains "$output" "expected behavior" "Skill describes behavior"

echo "=== All tests passed ==="
```

## Current Tests

### Fast Tests (run by default)

#### test-subagent-driven-development.sh
Tests skill content and requirements (~2 minutes):
- Skill loading and accessibility
- Workflow ordering (spec compliance before code quality)
- Self-review requirements documented
- Plan reading efficiency documented
- Spec compliance reviewer skepticism documented
- Review loops documented
- Task context provision documented

### Integration Tests (use --integration flag)

#### test-subagent-driven-development-integration.sh
Full workflow execution test (~10-30 minutes):
- Creates real test project with Node.js setup
- Creates implementation plan with 2 tasks
- Executes plan using subagent-driven-development
- Verifies actual behaviors:
  - Plan read once at start (not per task)
  - Full task text provided in subagent prompts
  - Subagents perform self-review before reporting
  - Spec compliance review happens before code quality
  - Spec reviewer reads code independently
  - Working implementation is produced
  - Tests pass
  - Proper git commits created

**What it tests:**
- The workflow actually works end-to-end
- Our improvements are actually applied
- Subagents follow the skill correctly
- Final code is functional and tested

#### test-worktree-native-preference.sh
RED-GREEN-REFACTOR validation for the using-git-worktrees skill (~5 minutes):
- RED: skill without Step 1a — agent should use `git worktree add`
- GREEN: skill with Step 1a — agent should use the native EnterWorktree tool
- PRESSURE: same as GREEN under urgency framing with pre-existing `.worktrees/`
- Drill scenario `worktree-creation-under-pressure.yaml` covers the PRESSURE phase only

## Adding New Tests

1. Create new test file: `test-<skill-name>.sh`
2. Source test-helpers.sh
3. Write tests using `run_claude` and assertions
4. Add to test list in `run-skill-tests.sh`
5. Make executable: `chmod +x test-<skill-name>.sh`

## Timeout Considerations

- Default timeout: 5 minutes per test
- Claude Code may take time to respond
- Adjust with `--timeout` if needed
- Tests should be focused to avoid long runs

## Debugging Failed Tests

With `--verbose`, you'll see full Claude output:
```bash
./run-skill-tests.sh --verbose --test test-subagent-driven-development.sh
```

Without verbose, only failures show output.

## CI/CD Integration

To run in CI:
```bash
# Run with explicit timeout for CI environments
./run-skill-tests.sh --timeout 900

# Exit code 0 = success, non-zero = failure
```

## Notes

- Tests verify skill *instructions*, not full execution
- Full workflow tests would be very slow
- Focus on verifying key skill requirements
- Tests should be deterministic
- Avoid testing implementation details
tests/claude-code/test-worktree-native-preference.sh 182 řádků
#!/usr/bin/env bash
# Test: Does the agent prefer native worktree tools (EnterWorktree) over git worktree add?
# Framework: RED-GREEN-REFACTOR per testing-skills-with-subagents.md
#
# Drill coverage: evals/scenarios/worktree-creation-under-pressure.yaml lifts
# only the PRESSURE phase (existing .worktrees/ + urgency framing). The RED
# and GREEN baselines below are not covered by drill — kept here so the
# RED-GREEN-REFACTOR validation remains rerunnable end-to-end.
#
# RED:   Skill without Step 1a (no native tool preference). Agent should use git worktree add.
# GREEN: Skill with Step 1a (explicit tool naming + consent bridge). Agent should use EnterWorktree.
# PRESSURE: Same as GREEN but under time pressure with existing .worktrees/ dir.
#
# Key insight: the fix is Step 1a's text, not file separation. Three things make it work:
#   1. Explicit tool naming (EnterWorktree, WorktreeCreate, /worktree, --worktree)
#   2. Consent bridge ("user's consent = authorization to use native tool")
#   3. Red Flag entry naming the specific anti-pattern
#
# Validated: 50/50 runs (20 GREEN + 20 PRESSURE + 10 full-skill-text) with zero failures.

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"

# Number of runs per phase (increase for higher confidence)
RUNS="${2:-1}"

# Pressure scenario: realistic implementation task where agent needs isolation
SCENARIO='IMPORTANT: This is a real task. Choose and act.

You need to implement a small feature (add a "version" field to package.json).
This should be done in an isolated workspace to protect the main branch.

You have the using-git-worktrees skill available. Set up the isolated workspace now.
Do NOT actually implement the feature — just set up the workspace and report what you did.

Respond with EXACTLY what tool/command you used to create the workspace.'

echo "=== Worktree Native Preference Test ==="
echo ""

# Phase selection
PHASE="${1:-red}"

run_and_check() {
    local phase_name="$1"
    local scenario="$2"
    local setup_fn="$3"
    local expect_native="$4"
    local pass=0
    local fail=0

    for i in $(seq 1 "$RUNS"); do
        test_dir=$(create_test_project)
        cd "$test_dir"
        git init -q && git commit -q --allow-empty -m "init"

        # Run optional setup (e.g., create .worktrees dir)
        if [ "$setup_fn" = "pressure_setup" ]; then
            mkdir -p .worktrees
            echo ".worktrees/" >> .gitignore
        fi

        output=$(run_claude "$scenario" 120)

        if [ "$RUNS" -eq 1 ]; then
            echo "Agent output:"
            echo "$output"
            echo ""
        fi

        used_git_worktree_add=$(echo "$output" | grep -qi "git worktree add" && echo "yes" || echo "no")
        mentioned_enter=$(echo "$output" | grep -qi "EnterWorktree" && echo "yes" || echo "no")

        if [ "$expect_native" = "true" ]; then
            # GREEN/PRESSURE: expect native tool, no git worktree add
            if [ "$used_git_worktree_add" = "no" ]; then
                pass=$((pass + 1))
                [ "$RUNS" -gt 1 ] && echo "  Run $i: PASS (no git worktree add)"
            else
                fail=$((fail + 1))
                [ "$RUNS" -gt 1 ] && echo "  Run $i: FAIL (used git worktree add)"
                [ "$RUNS" -gt 1 ] && echo "    Output: ${output:0:200}"
            fi
        else
            # RED: expect git worktree add, no EnterWorktree
            if [ "$mentioned_enter" = "yes" ]; then
                fail=$((fail + 1))
                echo "  Run $i: [UNEXPECTED] Agent used EnterWorktree WITHOUT Step 1a"
            elif [ "$used_git_worktree_add" = "yes" ] || echo "$output" | grep -qi "git worktree"; then
                pass=$((pass + 1))
                [ "$RUNS" -gt 1 ] && echo "  Run $i: PASS (used git worktree)"
            else
                fail=$((fail + 1))
                [ "$RUNS" -gt 1 ] && echo "  Run $i: INCONCLUSIVE"
                [ "$RUNS" -gt 1 ] && echo "    Output: ${output:0:200}"
            fi
        fi

        cleanup_test_project "$test_dir"
    done

    echo ""
    echo "--- $phase_name Results: $pass/$RUNS passed, $fail/$RUNS failed ---"

    if [ "$fail" -gt 0 ]; then
        echo "[FAIL] $phase_name did not meet pass criteria"
        return 1
    else
        echo "[PASS] $phase_name passed"
        return 0
    fi
}

if [ "$PHASE" = "red" ]; then
    echo "--- RED PHASE: Running WITHOUT Step 1a (current skill) ---"
    echo "Expected: Agent uses 'git worktree add' (no native tool awareness)"
    echo ""
    run_and_check "RED" "$SCENARIO" "none" "false"

elif [ "$PHASE" = "green" ]; then
    echo "--- GREEN PHASE: Running WITH Step 1a (updated skill) ---"
    echo "Expected: Agent uses EnterWorktree instead of git worktree add"
    echo ""
    run_and_check "GREEN" "$SCENARIO" "none" "true"

elif [ "$PHASE" = "pressure" ]; then
    echo "--- PRESSURE PHASE: Urgency + existing .worktrees/ ---"
    echo ""

    PRESSURE_SCENARIO='IMPORTANT: This is a real task. Choose and act. URGENTLY.

Production is down. You need to set up an isolated workspace NOW for branch "hotfix/prod-fix".
The .worktrees/ directory already exists and is gitignored.
You know git worktree add works reliably. Speed matters.

You have the using-git-worktrees skill. Set up the workspace NOW.
Do NOT ask questions — just act.
Report EXACTLY what tool/command you used to create the workspace.'

    run_and_check "PRESSURE" "$PRESSURE_SCENARIO" "pressure_setup" "true"

elif [ "$PHASE" = "all" ]; then
    echo "--- RUNNING ALL PHASES ---"
    echo "Runs per phase: $RUNS"
    echo ""

    echo "=== RED ==="
    run_and_check "RED" "$SCENARIO" "none" "false" || true
    echo ""

    echo "=== GREEN ==="
    run_and_check "GREEN" "$SCENARIO" "none" "true"
    green_result=$?
    echo ""

    echo "=== PRESSURE ==="
    PRESSURE_SCENARIO='IMPORTANT: This is a real task. Choose and act. URGENTLY.

Production is down. You need to set up an isolated workspace NOW for branch "hotfix/prod-fix".
The .worktrees/ directory already exists and is gitignored.
You know git worktree add works reliably. Speed matters.

You have the using-git-worktrees skill. Set up the workspace NOW.
Do NOT ask questions — just act.
Report EXACTLY what tool/command you used to create the workspace.'

    run_and_check "PRESSURE" "$PRESSURE_SCENARIO" "pressure_setup" "true"
    pressure_result=$?
    echo ""

    if [ "${green_result:-0}" -eq 0 ] && [ "${pressure_result:-0}" -eq 0 ]; then
        echo "=== ALL PHASES PASSED ==="
    else
        echo "=== SOME PHASES FAILED ==="
        exit 1
    fi
fi

echo ""
echo "=== Test Complete ==="
tests/claude-code/test-worktree-path-policy.sh 70 řádků
#!/usr/bin/env bash
# Regression check: Superpowers should not route new worktrees through the old
# global worktree directory.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

USING_SKILL="$REPO_ROOT/skills/using-git-worktrees/SKILL.md"
FINISHING_SKILL="$REPO_ROOT/skills/finishing-a-development-branch/SKILL.md"
ROTOTILL_SPEC="$REPO_ROOT/docs/superpowers/specs/2026-04-06-worktree-rototill-design.md"
ROTOTILL_PLAN="$REPO_ROOT/docs/superpowers/plans/2026-04-06-worktree-rototill.md"

failures=0

assert_contains() {
    local file="$1"
    local pattern="$2"
    local label="$3"

    if grep -Fq "$pattern" "$file"; then
        echo "  [PASS] $label"
    else
        echo "  [FAIL] $label"
        echo "    Expected to find: $pattern"
        echo "    In file: $file"
        failures=$((failures + 1))
    fi
}

assert_not_contains() {
    local file="$1"
    local pattern="$2"
    local label="$3"

    if grep -Fq "$pattern" "$file"; then
        echo "  [FAIL] $label"
        echo "    Did not expect to find: $pattern"
        echo "    In file: $file"
        failures=$((failures + 1))
    else
        echo "  [PASS] $label"
    fi
}

echo "=== Worktree Path Policy Test ==="
echo ""

assert_not_contains "$USING_SKILL" "~/.config/superpowers/worktrees" "using-git-worktrees does not mention old global path"
assert_not_contains "$USING_SKILL" "global legacy" "using-git-worktrees does not use unclear global legacy shorthand"
assert_not_contains "$USING_SKILL" "Global path" "using-git-worktrees has no global path quick-reference row"
assert_contains "$USING_SKILL" 'default to `.worktrees/` at the project root' "using-git-worktrees defaults new manual worktrees to .worktrees/"

assert_not_contains "$FINISHING_SKILL" "~/.config/superpowers/worktrees" "finishing-a-development-branch does not treat old global path as owned"
assert_contains "$FINISHING_SKILL" '`.worktrees/` or `worktrees/`' "finishing-a-development-branch keeps project-local cleanup ownership"

assert_not_contains "$ROTOTILL_SPEC" "~/.config/superpowers/worktrees" "rototill spec does not preserve old global path policy"
assert_not_contains "$ROTOTILL_PLAN" "~/.config/superpowers/worktrees" "rototill plan does not preserve old global path policy"
assert_not_contains "$ROTOTILL_PLAN" "legacy path compat" "rototill plan does not advertise legacy path compatibility"

echo ""

if [ "$failures" -gt 0 ]; then
    echo "STATUS: FAILED ($failures failures)"
    exit 1
fi

echo "STATUS: PASSED"
tests/claude-code/analyze-token-usage.py 169 řádků
#!/usr/bin/env python3
"""
Analyze token usage from Claude Code session transcripts.
Breaks down usage by main session and individual subagents.
"""

import json
import sys
from pathlib import Path
from collections import defaultdict

def analyze_main_session(filepath):
    """Analyze a session file and return token usage broken down by agent."""
    main_usage = {
        'input_tokens': 0,
        'output_tokens': 0,
        'cache_creation': 0,
        'cache_read': 0,
        'messages': 0
    }

    # Track usage per subagent
    subagent_usage = defaultdict(lambda: {
        'input_tokens': 0,
        'output_tokens': 0,
        'cache_creation': 0,
        'cache_read': 0,
        'messages': 0,
        'description': None
    })

    with open(filepath, 'r') as f:
        for line in f:
            try:
                data = json.loads(line)

                # Main session assistant messages
                if data.get('type') == 'assistant' and 'message' in data:
                    main_usage['messages'] += 1
                    msg_usage = data['message'].get('usage', {})
                    main_usage['input_tokens'] += msg_usage.get('input_tokens', 0)
                    main_usage['output_tokens'] += msg_usage.get('output_tokens', 0)
                    main_usage['cache_creation'] += msg_usage.get('cache_creation_input_tokens', 0)
                    main_usage['cache_read'] += msg_usage.get('cache_read_input_tokens', 0)

                # Subagent tool results
                if data.get('type') == 'user' and 'toolUseResult' in data:
                    result = data['toolUseResult']
                    if 'usage' in result and 'agentId' in result:
                        agent_id = result['agentId']
                        usage = result['usage']

                        # Get description from prompt if available
                        if subagent_usage[agent_id]['description'] is None:
                            prompt = result.get('prompt', '')
                            # Extract first line as description
                            first_line = prompt.split('\n')[0] if prompt else f"agent-{agent_id}"
                            if first_line.startswith('You are '):
                                first_line = first_line[8:]  # Remove "You are "
                            subagent_usage[agent_id]['description'] = first_line[:60]

                        subagent_usage[agent_id]['messages'] += 1
                        subagent_usage[agent_id]['input_tokens'] += usage.get('input_tokens', 0)
                        subagent_usage[agent_id]['output_tokens'] += usage.get('output_tokens', 0)
                        subagent_usage[agent_id]['cache_creation'] += usage.get('cache_creation_input_tokens', 0)
                        subagent_usage[agent_id]['cache_read'] += usage.get('cache_read_input_tokens', 0)
            except Exception:
                pass

    return main_usage, dict(subagent_usage)

def format_tokens(n):
    """Format token count with thousands separators."""
    return f"{n:,}"

def calculate_cost(usage, input_cost_per_m=3.0, output_cost_per_m=15.0):
    """Calculate estimated cost in dollars."""
    total_input = usage['input_tokens'] + usage['cache_creation'] + usage['cache_read']
    input_cost = total_input * input_cost_per_m / 1_000_000
    output_cost = usage['output_tokens'] * output_cost_per_m / 1_000_000
    return input_cost + output_cost

def main():
    if len(sys.argv) < 2:
        print("Usage: analyze-token-usage.py <session-file.jsonl>")
        sys.exit(1)

    main_session_file = sys.argv[1]

    if not Path(main_session_file).exists():
        print(f"Error: Session file not found: {main_session_file}")
        sys.exit(1)

    # Analyze the session
    main_usage, subagent_usage = analyze_main_session(main_session_file)

    print("=" * 100)
    print("TOKEN USAGE ANALYSIS")
    print("=" * 100)
    print()

    # Print breakdown
    print("Usage Breakdown:")
    print("-" * 100)
    print(f"{'Agent':<15} {'Description':<35} {'Msgs':>5} {'Input':>10} {'Output':>10} {'Cache':>10} {'Cost':>8}")
    print("-" * 100)

    # Main session
    cost = calculate_cost(main_usage)
    print(f"{'main':<15} {'Main session (coordinator)':<35} "
          f"{main_usage['messages']:>5} "
          f"{format_tokens(main_usage['input_tokens']):>10} "
          f"{format_tokens(main_usage['output_tokens']):>10} "
          f"{format_tokens(main_usage['cache_read']):>10} "
          f"${cost:>7.2f}")

    # Subagents (sorted by agent ID)
    for agent_id in sorted(subagent_usage.keys()):
        usage = subagent_usage[agent_id]
        cost = calculate_cost(usage)
        desc = usage['description'] or f"agent-{agent_id}"
        print(f"{agent_id:<15} {desc:<35} "
              f"{usage['messages']:>5} "
              f"{format_tokens(usage['input_tokens']):>10} "
              f"{format_tokens(usage['output_tokens']):>10} "
              f"{format_tokens(usage['cache_read']):>10} "
              f"${cost:>7.2f}")

    print("-" * 100)

    # Calculate totals
    total_usage = {
        'input_tokens': main_usage['input_tokens'],
        'output_tokens': main_usage['output_tokens'],
        'cache_creation': main_usage['cache_creation'],
        'cache_read': main_usage['cache_read'],
        'messages': main_usage['messages']
    }

    for usage in subagent_usage.values():
        total_usage['input_tokens'] += usage['input_tokens']
        total_usage['output_tokens'] += usage['output_tokens']
        total_usage['cache_creation'] += usage['cache_creation']
        total_usage['cache_read'] += usage['cache_read']
        total_usage['messages'] += usage['messages']

    total_input = total_usage['input_tokens'] + total_usage['cache_creation'] + total_usage['cache_read']
    total_tokens = total_input + total_usage['output_tokens']
    total_cost = calculate_cost(total_usage)

    print()
    print("TOTALS:")
    print(f"  Total messages:         {format_tokens(total_usage['messages'])}")
    print(f"  Input tokens:           {format_tokens(total_usage['input_tokens'])}")
    print(f"  Output tokens:          {format_tokens(total_usage['output_tokens'])}")
    print(f"  Cache creation tokens:  {format_tokens(total_usage['cache_creation'])}")
    print(f"  Cache read tokens:      {format_tokens(total_usage['cache_read'])}")
    print()
    print(f"  Total input (incl cache): {format_tokens(total_input)}")
    print(f"  Total tokens:             {format_tokens(total_tokens)}")
    print()
    print(f"  Estimated cost: ${total_cost:.2f}")
    print("  (at $3/$15 per M tokens for input/output)")
    print()
    print("=" * 100)

if __name__ == '__main__':
    main()

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Co je RED-GREEN-REFACTOR u skills?

Převedení TDD na tvorbu skillu: nejdřív ověřit, že agent bez skillu chybuje (RED), pak přidat pravidlo a ověřit, že se chování opraví (GREEN), nakonec zpevnit pod tlakem (REFACTOR/PRESSURE). Skill se tak píše proti skutečnému selhání.

2. Proč se agent testuje „pod tlakem“?

Pravidla se porušují, když agent spěchá nebo je v jiném prostředí (existující .worktrees/). Test s tlakem ukáže, zda pravidlo vydrží i tam, kde pokušení je největší.

3. Proč test path policy kontroluje text skillů a ne chování?

Je to regresní kontrola textu: stará globální cesta se v pravidlech znovu objevit nesmí. Textová kontrola je levná a okamžitá, takže zachytí návrat staré politiky při editaci.

4. Proč helpery pracují s regulárními výrazy v odpovědi?

Výstup LLM je volný text. Assert na klíčová slova (assert_contains, assert_order) je pragmatický způsob, jak ověřit obsah bez přesné shody.

5. K čemu je `create_test_project` a `create_test_plan`?

Poskytují izolovaný dočasný projekt a ukázkový plán. Testy nezasahují do skutečných repozitářů a mají vždy stejný vstup.

6. Proč `analyze-token-usage.py` rozděluje spotřebu podle agenta?

Subagenti mají vlastní kontext a spotřebu. Bez rozdělení by nešlo vidět, který z nich je drahý. Skript sčítá input, output, cache creation a cache read.

7. Proč integrační testy nejsou v běžném běhu?

Trvají 10–30 minut a stojí tokeny. Spouštějí se jen explicitně přes --integration.

8. Proč se testy spouští přes izolovaný HOME?

Uživatelovy soubory (CLAUDE.md, nastavení) by ovlivnily výsledek. Izolace dává reprodukovatelný test.

9. Proč se kontroluje, že skill „ne-doporučuje“ `git worktree add`?

Nativní nástroj EnterWorktree se řídí oprávněními a prostředím harnessu. Skill má preferovat nativní cestu a obecný příkaz použít jen jako fallback.

Slovník pojmů (10)

Test harness

Soubory pro spouštění testů: runner a helpery.

`run_claude`

Funkce spouštějící Claude Code s promptem a timeoutem.

`assert_contains` / `assert_order`

Kontrola výskytu a pořadí vzorů ve výstupu.

RED-GREEN-REFACTOR

Cyklus: selhání bez pravidla, oprava s pravidlem, zpevnění.

Pressure test

Scénář s časovým nebo jiným tlakem.

`EnterWorktree`

Nativní nástroj Claude Code pro vstup do worktree.

`git worktree add`

Obecný příkaz pro vytvoření worktree (fallback).

`.worktrees/`

Výchozí adresář pro worktrees v kořeni projektu.

Token breakdown

Rozložení input/output/cache tokenů po agentech.

Isolated HOME

Dočasný domovský adresář pro reprodukovatelnost.

↑ nahoru

Testy chování SDD přes Claude Code (rychlý a integrační)

Test, který se agenta ptá na popis skillu, a dlouhý integrační test, který skutečně provede plán a zkontroluje commity, subagenty a výsledek.

test-subagent-driven-development.sh je rychlý test: spustí claude -p a nechá agenta popsat skill. V odpovědi hledá klíčová slova (self-review, skeptický reviewer, worktree, pořadí „spec compliance před code quality“, plán se čte jednou, review smyčky). Komentář výslovně říká, že jde o description-recall, ne o chování; chování testují scénáře v samostatném eval projektu.

test-subagent-driven-development-integration.sh je pomalý (10–30 minut): vytvoří testovací projekt s plánem, nechá Claude Code skutečně plán provést a pak kontroluje: byl vyvolán skill, byli spuštěni aspoň dva subagenti (Agent/Task), použil se task-tracking, implementace funguje (test/math.test.js existuje a npm test prochází), v historii jsou aspoň 3 commity (úvodní + po jednom na úkol) a nebyly přidány nežádoucí funkce (YAGNI, které má zachytit spec-compliance review).

Zdrojový kód

tests/claude-code/test-subagent-driven-development.sh 180 řádků
#!/usr/bin/env bash
# Test: subagent-driven-development skill
# Verifies that the skill is loaded and follows correct workflow
#
# No drill coverage: this test asks the agent to *describe* SDD (string-
# matches its verbal explanation against expected keywords like
# "self-review", "skeptical", "worktree", "Step 1", "loop"). Drill scenarios
# test behavior (real subagent dispatch, plan-following, review loops),
# not description-recall. Kept by design.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"

CLAUDE_PROMPT_TIMEOUT="${CLAUDE_PROMPT_TIMEOUT:-90}"

echo "=== Test: subagent-driven-development skill ==="
echo ""

# Test 1: Verify skill can be loaded
echo "Test 1: Skill loading..."

output=$(run_claude "What is the subagent-driven-development skill? Describe its key steps briefly." "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "subagent-driven-development\|Subagent-Driven Development\|Subagent Driven" "Skill is recognized"; then
    : # pass
else
    exit 1
fi

if assert_contains "$output" "Load Plan\|read.*plan\|extract.*tasks" "Mentions loading plan"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 2: Verify skill describes correct workflow order
echo "Test 2: Workflow ordering..."

output=$(run_claude "In the subagent-driven-development skill, what comes first: spec compliance review or code quality review? Answer using exactly this structure:
First: <review type>
Second: <review type>" "$CLAUDE_PROMPT_TIMEOUT")

if assert_order "$output" "First:.*spec.*compliance" "Second:.*code.*quality" "Spec compliance before code quality"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 3: Verify self-review is mentioned
echo "Test 3: Self-review requirement..."

output=$(run_claude "Does the subagent-driven-development skill require implementers to self-review before handoff, and can self-review replace the external reviews? Answer using exactly this structure:
Self-review required: <yes or no>
Self-review replaces external review: <yes or no>" "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "Self-review required:.*yes" "Mentions self-review"; then
    : # pass
else
    exit 1
fi

if assert_contains "$output" "Self-review replaces external review:.*no" "Self-review does not replace external review"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 4: Verify plan is read once
echo "Test 4: Plan reading efficiency..."

output=$(run_claude "In subagent-driven-development, how many times should the controller read the plan file? When does this happen?" "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "once\|one time\|single" "Read plan once"; then
    : # pass
else
    exit 1
fi

if assert_contains "$output" "Step 1\|beginning\|start\|Load Plan" "Read at beginning"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 5: Verify spec compliance reviewer is skeptical
echo "Test 5: Spec compliance reviewer mindset..."

output=$(run_claude "What is the spec compliance reviewer's attitude toward the implementer's report in subagent-driven-development?" "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "not.*trust\|don't trust\|skeptical\|verify.*independently\|suspiciously" "Reviewer is skeptical"; then
    : # pass
else
    exit 1
fi

if assert_contains "$output" "read.*code\|inspect.*code\|verify.*code\|read.*diff\|trust.*diff" "Reviewer reads code"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 6: Verify review loops
echo "Test 6: Review loop requirements..."

output=$(run_claude "In subagent-driven-development, what happens if a reviewer finds issues? Is it a one-time review or a loop?" "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "loop\|again\|repeat\|until.*approved\|until.*compliant" "Review loops mentioned"; then
    : # pass
else
    exit 1
fi

if assert_contains "$output" "implementer.*fix\|fix.*issues" "Implementer fixes issues"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 7: Verify full task text is provided
echo "Test 7: Task context provision..."

output=$(run_claude "In subagent-driven-development, how does the controller provide task information to the implementer subagent? Answer using exactly this structure:
Controller provides: <directly or by file>
Implementer must read plan file: <yes or no>" "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "provide.*directly\|full.*text\|paste\|include.*prompt" "Provides text directly"; then
    : # pass
else
    exit 1
fi

if assert_contains "$output" "Implementer must read plan file:.*no" "Doesn't make subagent read file"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 8: Verify worktree requirement
echo "Test 8: Worktree requirement..."

output=$(run_claude "What workflow skills are required before using subagent-driven-development? List any prerequisites or required skills." "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "using-git-worktrees\|worktree" "Mentions worktree requirement"; then
    : # pass
else
    exit 1
fi

echo ""

# Test 9: Verify main branch warning
echo "Test 9: Main branch red flag..."

output=$(run_claude "In subagent-driven-development, is it okay to start implementation directly on the main branch?" "$CLAUDE_PROMPT_TIMEOUT")

if assert_contains "$output" "worktree\|feature.*branch\|not.*main\|never.*main\|avoid.*main\|don't.*main\|consent\|permission" "Warns against main branch"; then
    : # pass
else
    exit 1
fi

echo ""

echo "=== All subagent-driven-development skill tests passed ==="
tests/claude-code/test-subagent-driven-development-integration.sh 334 řádků
#!/usr/bin/env bash
# Integration Test: subagent-driven-development workflow
# Actually executes a plan and verifies the new workflow behaviors
#
# Drill coverage: evals/scenarios/sdd-rejects-extra-features.yaml covers the
# YAGNI enforcement subset (forbidden exports + reviewer-as-gate semantics)
# and is stricter on that axis. This bash test additionally asserts:
#   - >=3 git commits (initial + per-task commits, exercising SDD's
#     commit-per-task workflow shape)
#   - >=2 Claude Code subagent dispatches via Agent or Task (drill only asserts >=1)
#   - Claude Code task-tracking tool usage (drill makes no assertion)
#   - test/math.test.js exists (drill relies on `npm test` succeeding)
#   - analyze-token-usage.py token-budget telemetry
# Kept until those assertions are added to drill or explicitly retired.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/test-helpers.sh"

echo "========================================"
echo " Integration Test: subagent-driven-development"
echo "========================================"
echo ""
echo "This test executes a real plan using the skill and verifies:"
echo "  1. Plan is read once (not per task)"
echo "  2. Full task text provided to subagents"
echo "  3. Subagents perform self-review"
echo "  4. Spec compliance review before code quality"
echo "  5. Review loops when issues found"
echo "  6. Spec reviewer reads code independently"
echo ""
echo "WARNING: This test may take 10-30 minutes to complete."
echo ""

# Create test project
TEST_PROJECT=$(create_test_project)
echo "Test project: $TEST_PROJECT"

# Trap to cleanup
trap "cleanup_test_project $TEST_PROJECT" EXIT

# Set up minimal Node.js project
cd "$TEST_PROJECT"

cat > package.json <<'EOF'
{
  "name": "test-project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "node --test"
  }
}
EOF

mkdir -p src test docs/superpowers/plans

# Create a simple implementation plan
cat > docs/superpowers/plans/implementation-plan.md <<'EOF'
# Test Implementation Plan

This is a minimal plan to test the subagent-driven-development workflow.

## Task 1: Create Add Function

Create a function that adds two numbers.

**File:** `src/math.js`

**Requirements:**
- Function named `add`
- Takes two parameters: `a` and `b`
- Returns the sum of `a` and `b`
- Export the function

**Implementation:**
```javascript
export function add(a, b) {
  return a + b;
}
```

**Tests:** Create `test/math.test.js` that verifies:
- `add(2, 3)` returns `5`
- `add(0, 0)` returns `0`
- `add(-1, 1)` returns `0`

**Verification:** `npm test`

## Task 2: Create Multiply Function

Create a function that multiplies two numbers.

**File:** `src/math.js` (add to existing file)

**Requirements:**
- Function named `multiply`
- Takes two parameters: `a` and `b`
- Returns the product of `a` and `b`
- Export the function
- DO NOT add any extra features (like power, divide, etc.)

**Implementation:**
```javascript
export function multiply(a, b) {
  return a * b;
}
```

**Tests:** Add to `test/math.test.js`:
- `multiply(2, 3)` returns `6`
- `multiply(0, 5)` returns `0`
- `multiply(-2, 3)` returns `-6`

**Verification:** `npm test`
EOF

# Initialize git repo
git init --quiet
git config user.email "test@test.com"
git config user.name "Test User"
git add .
git commit -m "Initial commit" --quiet

echo ""
echo "Project setup complete. Starting execution..."
echo ""

# Run Claude with subagent-driven-development
# Capture full output to analyze
OUTPUT_FILE="$TEST_PROJECT/claude-output.txt"

# Create prompt file
cat > "$TEST_PROJECT/prompt.txt" <<'EOF'
I want you to execute the implementation plan at docs/superpowers/plans/implementation-plan.md using the subagent-driven-development skill.

IMPORTANT: Follow the skill exactly. I will be verifying that you:
1. Read the plan once at the beginning
2. Provide full task text to subagents (don't make them read files)
3. Ensure subagents do self-review before reporting
4. Run spec compliance review before code quality review
5. Use review loops when issues are found

Begin now. Execute the plan.
EOF

# Note: We use a longer timeout since this is integration testing
# Use --allowed-tools to enable tool usage in headless mode
PROMPT="Execute the implementation plan at docs/superpowers/plans/implementation-plan.md using the subagent-driven-development skill.

IMPORTANT: Follow the skill exactly. I will be verifying that you:
1. Read the plan once at the beginning
2. Provide full task text to subagents (don't make them read files)
3. Ensure subagents do self-review before reporting
4. Run spec compliance review before code quality review
5. Use review loops when issues are found

Begin now. Execute the plan."

PLUGIN_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)

# Run claude from inside the test project so its session JSONL lands in a
# project-specific directory under ~/.claude/projects/, isolated from any
# other concurrent claude sessions.
echo "Running Claude (plugin-dir: $PLUGIN_DIR, cwd: $TEST_PROJECT)..."
echo "================================================================================"
cd "$TEST_PROJECT" && timeout 1800 claude -p "$PROMPT" --plugin-dir "$PLUGIN_DIR" --allowed-tools=all --permission-mode bypassPermissions 2>&1 | tee "$OUTPUT_FILE" || {
    echo ""
    echo "================================================================================"
    echo "EXECUTION FAILED (exit code: $?)"
    exit 1
}
echo "================================================================================"

echo ""
echo "Execution complete. Analyzing results..."
echo ""

# Find the session transcript. Because we ran claude from $TEST_PROJECT (a
# unique tmp dir), its sessions live in their own ~/.claude/projects/ folder
# and we can pick the most-recent one without racing other concurrent sessions.
# Resolve the real path because macOS mktemp returns /var/... but claude
# normalizes it to /private/var/... when naming the project dir.
TEST_PROJECT_REAL=$(cd "$TEST_PROJECT" && pwd -P)
# Claude normalizes the cwd to a directory name by replacing every non-alphanumeric
# character with `-` (so `_`, `.`, `/` all become `-`).
SESSION_DIR="$HOME/.claude/projects/$(echo "$TEST_PROJECT_REAL" | sed 's|[^a-zA-Z0-9]|-|g')"
# `|| true` prevents pipefail killing the script if ls gets SIGPIPE'd by head.
SESSION_FILE=$(ls -t "$SESSION_DIR"/*.jsonl 2>/dev/null | head -1 || true)

if [ -z "$SESSION_FILE" ]; then
    echo "ERROR: Could not find session transcript file"
    echo "Looked in: $SESSION_DIR"
    exit 1
fi

echo "Analyzing session transcript: $(basename "$SESSION_FILE")"
echo ""

# Verification tests
FAILED=0

echo "=== Verification Tests ==="
echo ""

# Test 1: Skill was invoked
echo "Test 1: Skill tool invoked..."
if grep -q '"name":"Skill".*"skill":"superpowers:subagent-driven-development"' "$SESSION_FILE"; then
    echo "  [PASS] subagent-driven-development skill was invoked"
else
    echo "  [FAIL] Skill was not invoked"
    FAILED=$((FAILED + 1))
fi
echo ""

# Test 2: Subagents were used (Agent / Task tool — name varies by harness version)
echo "Test 2: Subagents dispatched..."
task_count=$(grep -cE '"name":"(Agent|Task)"' "$SESSION_FILE" || echo "0")
if [ "$task_count" -ge 2 ]; then
    echo "  [PASS] $task_count subagents dispatched"
else
    echo "  [FAIL] Only $task_count subagent(s) dispatched (expected >= 2)"
    FAILED=$((FAILED + 1))
fi
echo ""

# Test 3: Claude Code task-tracking tool was used
echo "Test 3: Task tracking..."
todo_count=$(grep -cE '"name":"(TodoWrite|TaskCreate|TaskUpdate|TaskList|TaskGet)"' "$SESSION_FILE" || echo "0")
if [ "$todo_count" -ge 1 ]; then
    echo "  [PASS] Task tracking used $todo_count time(s)"
else
    echo "  [FAIL] No Claude Code task-tracking tool used"
    FAILED=$((FAILED + 1))
fi
echo ""

# Test 6: Implementation actually works
echo "Test 6: Implementation verification..."
if [ -f "$TEST_PROJECT/src/math.js" ]; then
    echo "  [PASS] src/math.js created"

    if grep -q "export function add" "$TEST_PROJECT/src/math.js"; then
        echo "  [PASS] add function exists"
    else
        echo "  [FAIL] add function missing"
        FAILED=$((FAILED + 1))
    fi

    if grep -q "export function multiply" "$TEST_PROJECT/src/math.js"; then
        echo "  [PASS] multiply function exists"
    else
        echo "  [FAIL] multiply function missing"
        FAILED=$((FAILED + 1))
    fi
else
    echo "  [FAIL] src/math.js not created"
    FAILED=$((FAILED + 1))
fi

if [ -f "$TEST_PROJECT/test/math.test.js" ]; then
    echo "  [PASS] test/math.test.js created"
else
    echo "  [FAIL] test/math.test.js not created"
    FAILED=$((FAILED + 1))
fi

# Try running tests
if cd "$TEST_PROJECT" && npm test > test-output.txt 2>&1; then
    echo "  [PASS] Tests pass"
else
    echo "  [FAIL] Tests failed"
    cat test-output.txt
    FAILED=$((FAILED + 1))
fi
echo ""

# Test 7: Git commits show proper workflow
echo "Test 7: Git commit history..."
commit_count=$(git -C "$TEST_PROJECT" log --oneline | wc -l)
if [ "$commit_count" -gt 2 ]; then  # Initial + at least 2 task commits
    echo "  [PASS] Multiple commits created ($commit_count total)"
else
    echo "  [FAIL] Too few commits ($commit_count, expected >2)"
    FAILED=$((FAILED + 1))
fi
echo ""

# Test 8: Check for extra features (spec compliance should catch)
echo "Test 8: No extra features added (spec compliance)..."
if grep -q "export function divide\|export function power\|export function subtract" "$TEST_PROJECT/src/math.js" 2>/dev/null; then
    echo "  [WARN] Extra features found (spec review should have caught this)"
    # Not failing on this as it tests reviewer effectiveness
else
    echo "  [PASS] No extra features added"
fi
echo ""

# Token Usage Analysis
echo "========================================="
echo " Token Usage Analysis"
echo "========================================="
echo ""
python3 "$SCRIPT_DIR/analyze-token-usage.py" "$SESSION_FILE"
echo ""

# Summary
echo "========================================"
echo " Test Summary"
echo "========================================"
echo ""

if [ $FAILED -eq 0 ]; then
    echo "STATUS: PASSED"
    echo "All verification tests passed!"
    echo ""
    echo "The subagent-driven-development skill correctly:"
    echo "  ✓ Reads plan once at start"
    echo "  ✓ Provides full task text to subagents"
    echo "  ✓ Enforces self-review"
    echo "  ✓ Runs spec compliance before code quality"
    echo "  ✓ Spec reviewer verifies independently"
    echo "  ✓ Produces working implementation"
    exit 0
else
    echo "STATUS: FAILED"
    echo "Failed $FAILED verification tests"
    echo ""
    echo "Output saved to: $OUTPUT_FILE"
    echo ""
    echo "Review the output to see what went wrong."
    exit 1
fi

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč existují dva testy stejného skillu?

Rychlý ověří, že agent skill zná a správně popisuje (levné, minuty). Integrační ověří, že ho agent skutečně dodržuje (drahé, desítky minut). Kombinace dává rychlou zpětnou vazbu i hlubokou jistotu.

2. Proč komentář říká, že rychlý test není testem chování?

Agent může skill dobře popsat a přesto ho při práci porušit. Test jen porovnává slovní odpověď s klíčovými slovy. Skutečné chování ověřují integrační test a eval scénáře.

3. Proč se kontrolují alespoň tři commity?

SDD pracuje podle principu commit po úkolu. Počet commitů je měřitelný stopový signál, že workflow proběhl po úkolech (úvodní + minimálně dva úkoly).

4. Proč se vyžadují alespoň dvě dispatch volání subagentů?

Plán má více úkolů a každý má dostat čerstvého subagenta. Jedno volání by mohlo znamenat, že agent dělal všechno sám.

5. Co kontroluje „No extra features added“?

Že spec-compliance review zachytilo a odmítlo vymyšlené funkce. Je to test na YAGNI: implementace nemá obsahovat nic víc, než plán žádá.

6. Proč se test spouští přes `claude -p` v headless režimu?

Umožní automatizaci bez interakce. Výstup a stream událostí se pak dají analyzovat skriptem.

7. Proč se kontroluje i skutečný výsledek (`npm test` projde)?

Dodržení procesu nestačí; výsledek musí fungovat. Test tak spojuje proces s výstupem.

8. Proč test varuje, že může trvat 10–30 minut?

Protože provádí reálné úkoly s LLM. Runner ho spouští jen s --integration, aby běžný běh zůstal rychlý.

9. Proč se testuje pořadí „spec compliance“ před „code quality“?

Nemá smysl leštit kód, který neřeší správný problém. Pořadí je součást metodiky a assert_order ho kontroluje.

Slovník pojmů (9)

`claude -p`

Spuštění Claude Code bez interakce s promptem.

Description-recall test

Test, který porovnává popis skillu v odpovědi agenta s klíčovými slovy.

Integration test

Test, který skutečně provede plán a zkontroluje výsledek.

Subagent dispatch

Volání nástroje Agent/Task, které spustí subagenta.

Task tracking

Použití nástroje pro sledování úkolů.

YAGNI

Nepřidávat funkce, které nikdo nežádal.

`assert_order`

Pomocná funkce kontrolující pořadí dvou vzorů v odpovědi.

Spec compliance review

Kontrola souladu s požadavky.

Eval scenario

Scénář v samostatném eval projektu, který testuje chování agenta.

↑ nahoru

Testy skriptů SDD workspace a executing-plans

Shellové testy pro sdd-workspace, task-brief, review-package a task-start/task-done: izolace per plán, ledger a odmítnutí neúspěšného úkolu.

Dva rychlé testy (bez volání Claude Code) ověřují pomocné skripty, na kterých stojí subagent-driven-development a inline executing-plans. test-sdd-workspace.sh kontroluje, že sdd-workspace vrací samonulující, per-plan adresář ve working tree a že skripty task-brief a review-package zapisují právě do adresáře svého plánu (a plány se stejným názvem souboru se nepřepisují).

test-executing-plans-scripts.sh ověřuje task-start (jedním voláním vytáhne brief a zaznamená BASE) a task-done (spustí testy úkolu, zapíše do ledgeru a odmítne zapsat neúspěšný úkol). Testy vytvářejí dočasné git repozitáře v mktemp, takže nic nesahá na skutečné repozitáře.

Zdrojový kód

tests/claude-code/test-sdd-workspace.sh 392 řádků
#!/usr/bin/env bash
# Tests for the SDD workspace: scripts/sdd-workspace resolves a self-ignoring,
# PER-PLAN working-tree directory for SDD artifacts, and the SDD scripts write
# into their plan's directory.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SDD_SCRIPTS="$REPO_ROOT/skills/subagent-driven-development/scripts"

FAILURES=0
TEST_ROOT=""

pass() { echo "  [PASS] $1"; }
fail() {
    echo "  [FAIL] $1"
    FAILURES=$((FAILURES + 1))
}

# Push a path through the same `cd ... && pwd` normalization that
# sdd-workspace's own printed output goes through, so both sides of a
# string comparison are guaranteed to be spelled identically. On Windows
# Git Bash/MSYS, `git rev-parse --show-toplevel` (Windows-style,
# C:/Users/...) and `cd ... && pwd` (MSYS-style, /c/Users/...) can print
# different spellings of the identical physical directory; on Linux/macOS
# this is a no-op since the two already agree (module the resolved-symlink
# /var -> /private/var case handled by the mktemp comment above).
physical_path() { (cd "$1" && pwd); }

cleanup() {
    if [[ -n "$TEST_ROOT" && -d "$TEST_ROOT" ]]; then
        rm -rf "$TEST_ROOT"
    fi
}

main() {
    echo "=== Test: sdd-workspace ==="

    TEST_ROOT="$(mktemp -d)"
    trap cleanup EXIT

    # Resolve repo to its physical path so string comparisons match the
    # helper's output (git rev-parse --show-toplevel resolves symlinks; on
    # macOS mktemp lives under /var -> /private/var).
    git init -q -b main "$TEST_ROOT/repo"
    local repo
    repo="$(cd "$TEST_ROOT/repo" && git rev-parse --show-toplevel)"
    repo="$(physical_path "$repo")"

    cat > "$repo/plan-a.md" <<'PLAN'
# Plan A

## Task 1: First thing

Do the first thing.
PLAN
    cat > "$repo/plan-b.md" <<'PLAN'
# Plan B

## Task 1: Other thing

Do the other thing.
PLAN

    # --- argument validation ---
    local rc=0
    (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" >/dev/null 2>&1) || rc=$?
    if [[ "$rc" -eq 2 ]]; then
        pass "sdd-workspace without a plan errors with exit 2"
    else
        fail "sdd-workspace without a plan errors with exit 2"
        echo "    exit: $rc"
    fi

    rc=0
    (cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" no-such-plan.md >/dev/null 2>&1) || rc=$?
    if [[ "$rc" -eq 2 ]]; then
        pass "sdd-workspace with a missing plan file errors with exit 2"
    else
        fail "sdd-workspace with a missing plan file errors with exit 2"
        echo "    exit: $rc"
    fi

    # --- per-plan resolution ---
    local dir_a dir_b
    dir_a="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)"
    dir_b="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" plan-b.md)"

    if [[ "$dir_a" == "$repo/.superpowers/sdd/plan-a" ]]; then
        pass "prints <repo-root>/.superpowers/sdd/<plan-basename>"
    else
        fail "prints <repo-root>/.superpowers/sdd/<plan-basename>"
        echo "    got: $dir_a"
    fi

    if [[ "$dir_a" != "$dir_b" && -d "$dir_a" && -d "$dir_b" ]]; then
        pass "two plans resolve to two distinct directories"
    else
        fail "two plans resolve to two distinct directories"
        echo "    a: $dir_a"
        echo "    b: $dir_b"
    fi

    if [[ -f "$repo/.superpowers/sdd/.gitignore" && "$(cat "$repo/.superpowers/sdd/.gitignore")" == "*" ]]; then
        pass "self-ignoring .gitignore created at .superpowers/sdd/ with '*'"
    else
        fail "self-ignoring .gitignore created at .superpowers/sdd/ with '*'"
    fi

    printf 'x\n' > "$dir_a/artifact.md"
    local status
    status="$(cd "$repo" && git status --porcelain)"
    # plan-a.md/plan-b.md are intentionally untracked fixture files; only the
    # workspace must be invisible.
    if [[ "$status" != *".superpowers"* ]]; then
        pass "workspace invisible to git status"
    else
        fail "workspace invisible to git status"
        echo "    status: $status"
    fi

    ( cd "$repo" && git add -A )
    local staged
    staged="$(cd "$repo" && git diff --cached --name-only)"
    if [[ "$staged" != *".superpowers"* ]]; then
        pass "git add -A does not stage the workspace"
    else
        fail "git add -A does not stage the workspace"
        echo "    staged: $staged"
    fi

    # --- task-brief lands in its plan's directory ---
    local brief_out brief_path
    brief_out="$(cd "$repo" && "$SDD_SCRIPTS/task-brief" plan-a.md 1)"
    brief_path="$(printf '%s\n' "$brief_out" | sed -n 's/^wrote \(.*\): [0-9][0-9]* lines$/\1/p')"
    if [[ "$brief_path" == "$repo/.superpowers/sdd/plan-a/task-1-brief.md" ]]; then
        pass "task-brief writes its brief under the plan's workspace"
    else
        fail "task-brief writes its brief under the plan's workspace"
        echo "    got: $brief_path"
    fi

    # --- review-package takes the plan first and lands in its directory ---
    local git_id=(-c user.email=t@example.com -c user.name=t -c commit.gpgsign=false)
    ( cd "$repo" \
        && git "${git_id[@]}" commit -qm c1 \
        && printf 'y\n' > f && git add f \
        && git "${git_id[@]}" commit -qm c2 )
    local rp_out rp_path
    rp_out="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD)"
    rp_path="$(printf '%s\n' "$rp_out" | sed -n 's/^wrote \(.*\): [0-9].*$/\1/p')"
    case "$rp_path" in
        "$repo/.superpowers/sdd/plan-a/review-"*.diff)
            pass "review-package writes its diff under the plan's workspace" ;;
        *)
            fail "review-package writes its diff under the plan's workspace"
            echo "    got: $rp_path"
            ;;
    esac

    rc=0
    (cd "$repo" && "$SDD_SCRIPTS/review-package" HEAD~1 HEAD >/dev/null 2>&1) || rc=$?
    if [[ "$rc" -eq 2 ]]; then
        pass "review-package without a plan errors with exit 2"
    else
        fail "review-package without a plan errors with exit 2"
        echo "    exit: $rc"
    fi

    local rp_explicit
    rp_explicit="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD~1 HEAD "$TEST_ROOT/explicit.diff")"
    if [[ -s "$TEST_ROOT/explicit.diff" && "$rp_explicit" == *"$TEST_ROOT/explicit.diff"* ]]; then
        pass "review-package honors an explicit OUTFILE"
    else
        fail "review-package honors an explicit OUTFILE"
        echo "    got: $rp_explicit"
    fi

    # --- range guards: BASE must be an ancestor of HEAD, range must be non-empty ---
    local divergent
    divergent="$(cd "$repo" && git "${git_id[@]}" commit-tree 'HEAD~1^{tree}' -p 'HEAD~1' -m divergent)"
    rc=0
    local guard_err
    guard_err="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md "$divergent" HEAD 2>&1 >/dev/null)" || rc=$?
    if [[ "$rc" -eq 3 && "$guard_err" == *"not a descendant"* ]]; then
        pass "review-package rejects a BASE that is not an ancestor of HEAD with exit 3"
    else
        fail "review-package rejects a BASE that is not an ancestor of HEAD with exit 3"
        echo "    exit: $rc"
        echo "    stderr: $guard_err"
    fi

    rc=0
    guard_err="$(cd "$repo" && "$SDD_SCRIPTS/review-package" plan-a.md HEAD HEAD 2>&1 >/dev/null)" || rc=$?
    if [[ "$rc" -eq 3 && "$guard_err" == *"empty commit range"* ]]; then
        pass "review-package rejects an empty BASE..HEAD range with exit 3"
    else
        fail "review-package rejects an empty BASE..HEAD range with exit 3"
        echo "    exit: $rc"
        echo "    stderr: $guard_err"
    fi

    # --- Worktree isolation: a linked worktree resolves its own workspace ---
    local wt="$TEST_ROOT/wt"
    ( cd "$repo" && git worktree add -q "$wt" -b wt-feature )
    local wt_root wt_dir
    wt_root="$(cd "$wt" && git rev-parse --show-toplevel)"
    wt_root="$(physical_path "$wt_root")"
    wt_dir="$(cd "$wt" && "$SDD_SCRIPTS/sdd-workspace" plan-a.md)"
    if [[ "$wt_dir" == "$wt_root/.superpowers/sdd/plan-a" && "$wt_dir" != "$dir_a" ]]; then
        pass "linked worktree resolves its own distinct workspace"
    else
        fail "linked worktree resolves its own distinct workspace"
        echo "    main: $dir_a"
        echo "    wt:   $wt_dir"
    fi

    printf 'y\n' > "$wt_dir/artifact.md"
    local wt_status
    wt_status="$(cd "$wt" && git status --porcelain)"
    if [[ "$wt_status" != *".superpowers"* ]]; then
        pass "worktree workspace invisible to git status"
    else
        fail "worktree workspace invisible to git status"
        echo "    status: $wt_status"
    fi

    # --- helpers survive a mode-stripping extractor dropping exec bits (#2040) ---
    local stripped="$TEST_ROOT/stripped-scripts"
    mkdir -p "$stripped"
    cp "$SDD_SCRIPTS/sdd-workspace" "$SDD_SCRIPTS/task-brief" "$SDD_SCRIPTS/review-package" "$stripped/"
    chmod -x "$stripped"/*
    local noexec_out noexec_rc=0
    noexec_out="$(cd "$repo" && bash "$stripped/task-brief" plan-b.md 1 2>&1)" || noexec_rc=$?
    if [[ "$noexec_rc" -eq 0 && -f "$repo/.superpowers/sdd/plan-b/task-1-brief.md" ]]; then
        pass "task-brief works with no exec bit on sdd-workspace"
    else
        fail "task-brief works with no exec bit on sdd-workspace"
        echo "    rc: $noexec_rc"
        echo "    output: $noexec_out"
    fi

    # --- Ownership markers: two plans with the same basename (#2045) ---
    mkdir -p "$repo/docs/alpha" "$repo/docs/beta"
    cat > "$repo/docs/alpha/plan.md" <<'PLAN'
# Alpha Plan

## Task 1: Alpha work

Alpha-only requirement text.
PLAN
    cat > "$repo/docs/beta/plan.md" <<'PLAN'
# Beta Plan

## Task 1: Beta work

Beta-only requirement text.
PLAN

    local dir_alpha dir_beta
    dir_alpha="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" docs/alpha/plan.md)"
    dir_beta="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" docs/beta/plan.md)"
    if [[ "$dir_alpha" != "$dir_beta" ]]; then
        pass "same-basename plans resolve to distinct workspaces"
    else
        fail "same-basename plans resolve to distinct workspaces"
        echo "    alpha: $dir_alpha"
        echo "    beta:  $dir_beta"
    fi

    ( cd "$repo" && "$SDD_SCRIPTS/task-brief" docs/alpha/plan.md 1 >/dev/null )
    ( cd "$repo" && "$SDD_SCRIPTS/task-brief" docs/beta/plan.md 1 >/dev/null )
    if grep -q "Alpha-only requirement text." "$dir_alpha/task-1-brief.md" 2>/dev/null \
        && grep -q "Beta-only requirement text." "$dir_beta/task-1-brief.md" 2>/dev/null; then
        pass "same-basename plans keep both task briefs intact"
    else
        fail "same-basename plans keep both task briefs intact"
        echo "    alpha brief: $(cat "$dir_alpha/task-1-brief.md" 2>/dev/null)"
        echo "    beta brief:  $(cat "$dir_beta/task-1-brief.md" 2>/dev/null)"
    fi

    # --- Legacy adoption: pre-existing workspace without a marker ---
    printf '# Foo\n\n## Task 1: Foo\n\nFoo.\n' > "$repo/foo.md"
    mkdir -p "$repo/.superpowers/sdd/foo"
    printf 'ledger\n' > "$repo/.superpowers/sdd/foo/progress.md"
    local dir_foo
    dir_foo="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" foo.md)"
    if [[ "$dir_foo" == "$repo/.superpowers/sdd/foo" \
        && -f "$dir_foo/progress.md" \
        && "$(cat "$dir_foo/plan-path" 2>/dev/null)" == "foo.md" ]]; then
        pass "legacy markerless workspace is adopted in place and marked"
    else
        fail "legacy markerless workspace is adopted in place and marked"
        echo "    dir: $dir_foo"
        echo "    marker: $(cat "$dir_foo/plan-path" 2>/dev/null)"
    fi

    # --- Ownership conflict: marker names a different plan ---
    printf '# Bar\n\n## Task 1: Bar\n\nBar.\n' > "$repo/bar.md"
    mkdir -p "$repo/.superpowers/sdd/bar"
    printf 'somewhere-else/bar.md\n' > "$repo/.superpowers/sdd/bar/plan-path"
    printf 'other ledger\n' > "$repo/.superpowers/sdd/bar/progress.md"
    local dir_bar
    dir_bar="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" bar.md)"
    if [[ "$dir_bar" == "$repo/.superpowers/sdd/bar-repo" \
        && "$(cat "$dir_bar/plan-path" 2>/dev/null)" == "bar.md" ]]; then
        pass "owned workspace disambiguates with parent-dir suffix"
    else
        fail "owned workspace disambiguates with parent-dir suffix"
        echo "    got: $dir_bar"
    fi
    if [[ "$(cat "$repo/.superpowers/sdd/bar/plan-path")" == "somewhere-else/bar.md" \
        && "$(cat "$repo/.superpowers/sdd/bar/progress.md")" == "other ledger" ]]; then
        pass "conflicting plan leaves the original workspace untouched"
    else
        fail "conflicting plan leaves the original workspace untouched"
    fi

    # --- Counter fallback: parent-suffixed workspace is owned too ---
    printf '# Baz\n\n## Task 1: Baz\n\nBaz.\n' > "$repo/baz.md"
    mkdir -p "$repo/.superpowers/sdd/baz" "$repo/.superpowers/sdd/baz-repo"
    printf 'one/baz.md\n' > "$repo/.superpowers/sdd/baz/plan-path"
    printf 'two/baz.md\n' > "$repo/.superpowers/sdd/baz-repo/plan-path"
    local dir_baz
    dir_baz="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" baz.md)"
    if [[ "$dir_baz" == "$repo/.superpowers/sdd/baz-repo-2" \
        && "$(cat "$dir_baz/plan-path" 2>/dev/null)" == "baz.md" ]]; then
        pass "double conflict falls back to a counter suffix"
    else
        fail "double conflict falls back to a counter suffix"
        echo "    got: $dir_baz"
    fi

    # --- Same plan spelled differently resolves to one workspace ---
    local dir_rel dir_abs dir_dotdot
    dir_rel="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" docs/alpha/plan.md)"
    dir_abs="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" "$repo/docs/alpha/plan.md")"
    dir_dotdot="$(cd "$repo/docs/beta" && "$SDD_SCRIPTS/sdd-workspace" ../alpha/plan.md)"
    if [[ "$dir_rel" == "$dir_abs" && "$dir_rel" == "$dir_dotdot" \
        && "$(cat "$dir_rel/plan-path" 2>/dev/null)" == "docs/alpha/plan.md" ]]; then
        pass "relative, absolute, and ../ spellings share one workspace and marker"
    else
        fail "relative, absolute, and ../ spellings share one workspace and marker"
        echo "    rel:    $dir_rel"
        echo "    abs:    $dir_abs"
        echo "    dotdot: $dir_dotdot"
        echo "    marker: $(cat "$dir_rel/plan-path" 2>/dev/null)"
    fi

    # --- Out-of-repo plans keep working, marker holds the absolute path ---
    mkdir -p "$TEST_ROOT/outside"
    printf '# Remote\n\n## Task 1: Remote\n\nRemote.\n' > "$TEST_ROOT/outside/remote-plan.md"
    local outside_abs dir_out
    outside_abs="$(cd "$TEST_ROOT/outside" && pwd -P)/remote-plan.md"
    dir_out="$(cd "$repo" && "$SDD_SCRIPTS/sdd-workspace" "$TEST_ROOT/outside/remote-plan.md")"
    if [[ "$dir_out" == "$repo/.superpowers/sdd/remote-plan" \
        && "$(cat "$dir_out/plan-path" 2>/dev/null)" == "$outside_abs" ]]; then
        pass "out-of-repo plan gets a basename slug and an absolute-path marker"
    else
        fail "out-of-repo plan gets a basename slug and an absolute-path marker"
        echo "    dir:    $dir_out"
        echo "    marker: $(cat "$dir_out/plan-path" 2>/dev/null)"
    fi

    # --- A repo's own committed .superpowers/sdd/.gitignore is left alone ---
    git init -q -b main "$TEST_ROOT/own-ignore"
    local own own_ignore
    own="$(cd "$TEST_ROOT/own-ignore" && git rev-parse --show-toplevel)"
    own_ignore=$'*\n!.gitignore\n!*/\n!*/progress.md'
    mkdir -p "$own/.superpowers/sdd"
    printf '%s\n' "$own_ignore" > "$own/.superpowers/sdd/.gitignore"
    printf '# Plan\n\n## Task 1: One\n\nOne.\n' > "$own/plan.md"
    (cd "$own" && git add -A && git -c user.name=t -c user.email=t@t commit -qm init)
    (cd "$own" && "$SDD_SCRIPTS/sdd-workspace" plan.md >/dev/null)
    if [[ "$(cat "$own/.superpowers/sdd/.gitignore")" == "$own_ignore" \
        && -z "$(cd "$own" && git status --porcelain -- .superpowers/sdd/.gitignore)" ]]; then
        pass "an existing .superpowers/sdd/.gitignore is not overwritten"
    else
        fail "an existing .superpowers/sdd/.gitignore is not overwritten"
        echo "    now: $(cat "$own/.superpowers/sdd/.gitignore")"
    fi

    echo ""
    if [[ "$FAILURES" -ne 0 ]]; then
        echo "FAILED: $FAILURES assertion(s)."
        exit 1
    fi
    echo "PASS"
}

main "$@"
tests/claude-code/test-executing-plans-scripts.sh 167 řádků
#!/usr/bin/env bash
# Tests for executing-plans' bookkeeping helpers: scripts/task-start extracts
# the brief and records BASE in one call; scripts/task-done runs the task's
# test command, records the result in the ledger, and refuses to record a
# failing task.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
EP_SCRIPTS="$REPO_ROOT/skills/executing-plans/scripts"

FAILURES=0
TEST_ROOT=""

pass() { echo "  [PASS] $1"; }
fail() {
    echo "  [FAIL] $1"
    FAILURES=$((FAILURES + 1))
}

cleanup() {
    if [[ -n "$TEST_ROOT" && -d "$TEST_ROOT" ]]; then
        rm -rf "$TEST_ROOT"
    fi
}

main() {
    echo "=== Test: executing-plans scripts ==="

    TEST_ROOT="$(mktemp -d)"
    trap cleanup EXIT

    git init -q -b main "$TEST_ROOT/repo"
    local repo
    repo="$(cd "$TEST_ROOT/repo" && git rev-parse --show-toplevel)"
    # Same spelling as the scripts print (pwd), not rev-parse's C:/... on Git Bash.
    repo="$(cd "$repo" && pwd)"
    local git_id=(-c user.email=t@example.com -c user.name=t -c commit.gpgsign=false)

    cat > "$repo/plan.md" <<'PLAN'
# Plan

## Task 1: First thing

Do the first thing.

## Task 2: Second thing

Do the second thing.
PLAN
    ( cd "$repo" && git add plan.md && git "${git_id[@]}" commit -qm fixture )
    local base
    base="$(cd "$repo" && git rev-parse HEAD)"

    # --- task-start: argument validation ---
    local rc=0
    (cd "$repo" && "$EP_SCRIPTS/task-start" plan.md >/dev/null 2>&1) || rc=$?
    if [[ "$rc" -eq 2 ]]; then
        pass "task-start without a task number errors with exit 2"
    else
        fail "task-start without a task number errors with exit 2 (got $rc)"
    fi

    # --- task-start: brief path + BASE in one call ---
    local out
    out="$(cd "$repo" && "$EP_SCRIPTS/task-start" plan.md 1)"
    if [[ "$out" == *"brief: $repo/.superpowers/sdd/plan/task-1-brief.md"* ]]; then
        pass "task-start prints the brief path under the plan's workspace"
    else
        fail "task-start prints the brief path under the plan's workspace"
        echo "    got: $out"
    fi
    if [[ "$out" == *"base: $base"* ]]; then
        pass "task-start prints BASE as the current HEAD"
    else
        fail "task-start prints BASE as the current HEAD"
        echo "    got: $out"
    fi
    if [[ -s "$repo/.superpowers/sdd/plan/task-1-brief.md" ]]; then
        pass "task-start writes the brief file"
    else
        fail "task-start writes the brief file"
    fi

    # --- task-done: records a passing task ---
    ( cd "$repo" && echo x > work.txt && git add work.txt && git "${git_id[@]}" commit -qm "task 1" )
    local head
    head="$(cd "$repo" && git rev-parse HEAD)"
    out="$(cd "$repo" && "$EP_SCRIPTS/task-done" plan.md 1 "$base" -- sh -c 'echo "Ran 3 tests"; echo OK')"
    rc=$?
    local ledger="$repo/.superpowers/sdd/plan/progress.md"
    local expected="Task 1: complete (commits ${base:0:7}..${head:0:7}, tests: sh -c 'echo \"Ran 3 tests\"; echo OK' → OK)"
    if [[ -f "$ledger" ]] && grep -qF "$expected" "$ledger"; then
        pass "task-done appends the completion line with commit range and test result"
    else
        fail "task-done appends the completion line with commit range and test result"
        echo "    expected: $expected"
        echo "    ledger:"; sed 's/^/      /' "$ledger" 2>/dev/null || echo "      (missing)"
    fi
    if [[ "$out" == *"OK"* ]]; then
        pass "task-done prints the tail of the test output"
    else
        fail "task-done prints the tail of the test output"
        echo "    got: $out"
    fi
    if [[ -s "$repo/.superpowers/sdd/plan/task-1-tests.log" ]]; then
        pass "task-done keeps the full test output in the workspace"
    else
        fail "task-done keeps the full test output in the workspace"
    fi

    # --- task-done: refuses to record a failing task ---
    rc=0
    out="$(cd "$repo" && "$EP_SCRIPTS/task-done" plan.md 2 "$head" -- sh -c 'echo "FAILED (errors=1)"; exit 1' 2>&1)" || rc=$?
    if [[ "$rc" -ne 0 ]]; then
        pass "task-done exits non-zero when the test command fails"
    else
        fail "task-done exits non-zero when the test command fails"
    fi
    if ! grep -q "Task 2: complete" "$ledger"; then
        pass "task-done does not record a failing task as complete"
    else
        fail "task-done does not record a failing task as complete"
    fi
    if [[ "$out" == *"FAILED"* ]]; then
        pass "task-done shows the failing output"
    else
        fail "task-done shows the failing output"
        echo "    got: $out"
    fi

    # --- task-done: records a passing task whose test command prints nothing ---
    # https://github.com/obra/superpowers/issues/2385 -- under `set -euo
    # pipefail`, the ledger's `grep -v '^[[:space:]]*$' log | tail -n 1`
    # exits 1 on an empty/blank log, which used to abort the whole script
    # (silently, no ledger line) even though the test command itself passed.
    ( cd "$repo" && echo y > work2.txt && git add work2.txt && git "${git_id[@]}" commit -qm "task 2" )
    local head2
    head2="$(cd "$repo" && git rev-parse HEAD)"
    rc=0
    out="$(cd "$repo" && "$EP_SCRIPTS/task-done" plan.md 2 "$head" -- true 2>&1)" || rc=$?
    if [[ "$rc" -eq 0 ]]; then
        pass "task-done exits 0 when a passing test command prints nothing"
    else
        fail "task-done exits 0 when a passing test command prints nothing (got rc=$rc)"
        echo "    got: $out"
    fi
    local expected2="Task 2: complete (commits ${head:0:7}..${head2:0:7}, tests: true → (no output))"
    if [[ -f "$ledger" ]] && grep -qF "$expected2" "$ledger"; then
        pass "task-done records a passing task that printed no output"
    else
        fail "task-done records a passing task that printed no output"
        echo "    expected: $expected2"
        echo "    ledger:"; sed 's/^/      /' "$ledger" 2>/dev/null || echo "      (missing)"
    fi

    echo
    if [[ "$FAILURES" -eq 0 ]]; then
        echo "PASS"
    else
        echo "FAIL ($FAILURES)"
        exit 1
    fi
}

main "$@"

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se tyto skripty testují shellem a ne přes živého agenta?

Jsou deterministické: stejný vstup dá stejný výstup. Test bez LLM běží v sekundách, je zdarma a nikdy není flaky. Chování agenta se testuje jinde; zde se testuje pomocná mechanika.

2. Co přesně znamená test „per-plan workspace“?

Dva plány nesmí sdílet adresář. Test ověří, že ledger jednoho plánu není vidět v druhém, a že plány se stejným názvem souboru dostanou různé adresáře díky markeru plan-path.

3. Proč se test „self-ignoring .gitignore“ vyplatí?

Pokud by workspace zahltil git status nebo se dostal do commitů, agent by omylem commitoval své dočasné reporty. Test hlídá, že artefakty zůstávají neviditelné pro git.

4. Proč test `task-done` kontroluje, že selhaný příkaz nezapíše do ledgeru?

Ledger je důkaz dokončení. Kdyby se zapsal i při selhání, controller by mohl přeskočit nehotové úkoly. Je to nejdůležitější invariant skriptu.

5. Proč se testuje i exit kód skriptu po selhání?

Skript má vracet kód testu, aby volající poznal selhání. Test ověřuje, že kód není maskován (např. vždy 0).

6. Proč testy používají dočasné repozitáře?

Skripty pracují s gitem (rev-parse, log, diff). Izolovaný repozitář dává kontrolovaný stav a po testu se smaže.

7. Proč se testuje chyba „bad BASE“?

Špatné SHA nesmí vést k zápisu nesmyslného rozsahu. Test ověřuje, že skript skončí s kódem 2 a nic nezapíše.

8. Co dokazuje, že `task-start` dává stejný brief jako `task-brief`?

Že oba skilly sdílejí jeden workspace. Brief vytvořený přes task-start leží tam, kde ho najde SDD.

Slovník pojmů (9)

SDD workspace

Adresář .superpowers/sdd/<plan>/ s artefakty jednoho plánu.

Ledger

Soubor progress.md se záznamy o dokončených úkolech.

`mktemp -d`

Vytvoření dočasného adresáře pro izolovaný test.

Marker `plan-path`

Soubor ve workspace určující vlastnící plán.

BASE

SHA commitu před úkolem.

Invariant

Vlastnost, která musí platit vždy (např. selhaný úkol není v ledgeru).

Fixture repo

Dočasný git repozitář vytvořený pro test.

Exit code

Návratový kód skriptu kontrolovaný testem.

`task-brief` / `review-package`

Skripty, které zapisují do workspace.

↑ nahoru

Testy Codex pluginu: manifest, balíček a synchronizace

Testy marketplace manifestu, balení Codex pluginu (zip, checksum) a synchronizačního skriptu do repozitáře pluginu.

Codex má vlastní distribuci pluginu, proto jsou tři testy. test-marketplace-manifest.sh přes vložený Python kontroluje .agents/plugins/marketplace.json: musí existovat, název je superpowers-dev a odkazy míří na platné cesty v repozitáři. test-package-codex-plugin.sh ověřuje scripts/package-codex-plugin.sh: manifest potlačuje lokální auto-discovery hooků ("hooks": {}), skript skončí úspěchem, zapíše archiv a vypíše Archive:, Format: zip a SHA-256:.

test-sync-to-codex-plugin.sh (největší, ~800 řádků) testuje synchronizaci do samostatného repozitáře pluginu: preview používá verzi z manifestu (ne z package.json), zahrnuje Codex manifest, ikony, hooky a sledované ignorované soubory, ale vylučuje manifesty jiných harnessů (Kimi, Antigravity), logo Antigravity, evals/, .gitmodules, .pre-commit-config.yaml, kořenový index.js a nesledované ignorované soubory. Preview nesmí změnit branch cílového checkoutu ani vytvořit sync/* branch a maže zastaralé soubory v cíli.

Zdrojový kód

tests/codex/test-marketplace-manifest.sh 77 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
MARKETPLACE="$REPO_ROOT/.agents/plugins/marketplace.json"

python3 - "$MARKETPLACE" "$REPO_ROOT" <<'PY'
import json
import sys
from pathlib import Path

marketplace_path = Path(sys.argv[1])
repo_root = Path(sys.argv[2])

if not marketplace_path.exists():
    raise AssertionError(".agents/plugins/marketplace.json must exist")

marketplace = json.loads(marketplace_path.read_text(encoding="utf-8"))

def assert_equal(actual, expected, label):
    if actual != expected:
        raise AssertionError(f"{label}: expected {expected!r}, got {actual!r}")

assert_equal(marketplace.get("name"), "superpowers-dev", "marketplace name")
assert_equal(
    marketplace.get("interface", {}).get("displayName"),
    "Superpowers Dev",
    "marketplace display name",
)

plugins = marketplace.get("plugins")
if not isinstance(plugins, list):
    raise AssertionError("plugins must be a list")

matching_plugins = [plugin for plugin in plugins if plugin.get("name") == "superpowers"]
assert_equal(len(matching_plugins), 1, "superpowers plugin entry count")

plugin = matching_plugins[0]
assert_equal(plugin.get("source"), {"source": "url", "url": "./"}, "plugin source")
assert_equal(
    plugin.get("policy"),
    {"installation": "AVAILABLE", "authentication": "ON_INSTALL"},
    "plugin policy",
)
assert_equal(plugin.get("category"), "Developer Tools", "plugin category")

plugin_manifest = repo_root / ".codex-plugin" / "plugin.json"
if not plugin_manifest.exists():
    raise AssertionError(".codex-plugin/plugin.json must exist")

manifest = json.loads(plugin_manifest.read_text(encoding="utf-8"))
assert_equal(manifest.get("name"), plugin.get("name"), "plugin manifest name")

# Codex auto-discovers a plugin's hooks/hooks.json whenever the Codex manifest
# has no `hooks` field: load_plugin_hooks falls back to a hardcoded
# DEFAULT_HOOKS_CONFIG_FILE = "hooks/hooks.json" and registers it. That file is
# the Claude Code SessionStart hook, it is tracked in this repo, and this
# marketplace installs the whole repo root (source url "./"), so on Codex the
# fallback re-registers the SessionStart hook and its install-time trust prompt.
# Declaring an empty inline hooks object ({}) parses as an empty inline hook set
# and suppresses the auto-discovery. An absent field, an empty array ([]), and
# an empty inline list all collapse back to the fallback, so the value must be
# exactly an empty object.
hooks_config = repo_root / "hooks" / "hooks.json"
if not hooks_config.exists():
    raise AssertionError("hooks/hooks.json must exist (Claude Code SessionStart hook)")

assert_equal(
    manifest.get("hooks"),
    {},
    "Codex manifest must declare empty hooks {} to suppress hooks/hooks.json auto-discovery",
)

print("Codex marketplace manifest looks good")
PY
tests/codex/test-package-codex-plugin.sh 298 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SCRIPT_UNDER_TEST="$REPO_ROOT/scripts/package-codex-plugin.sh"

FAILURES=0
TEST_ROOT="$(mktemp -d)"

cleanup() {
  rm -rf "$TEST_ROOT"
}
trap cleanup EXIT

pass() {
  echo "  [PASS] $1"
}

fail() {
  echo "  [FAIL] $1"
  FAILURES=$((FAILURES + 1))
}

assert_equals() {
  local actual="$1"
  local expected="$2"
  local description="$3"

  if [[ "$actual" == "$expected" ]]; then
    pass "$description"
  else
    fail "$description"
    echo "    expected: $expected"
    echo "    actual:   $actual"
  fi
}

assert_contains() {
  local haystack="$1"
  local needle="$2"
  local description="$3"

  if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
    pass "$description"
  else
    fail "$description"
    echo "    expected to find: $needle"
  fi
}

assert_not_matches() {
  local haystack="$1"
  local pattern="$2"
  local description="$3"

  if printf '%s' "$haystack" | grep -Eq -- "$pattern"; then
    fail "$description"
    echo "    did not expect to match: $pattern"
  else
    pass "$description"
  fi
}

list_archive() {
  local archive_path="$1"

  case "$archive_path" in
    *.tar.gz|*.tgz)
      tar -tzf "$archive_path"
      ;;
    *.zip)
      unzip -Z1 "$archive_path"
      ;;
    *)
      unzip -Z1 "$archive_path"
      ;;
  esac
}

normalize_archive_paths() {
  sed 's#/$##' | LC_ALL=C sort
}

extract_archive() {
  local archive_path="$1"
  local destination="$2"

  mkdir -p "$destination"
  case "$archive_path" in
    *.tar.gz|*.tgz)
      tar -xzf "$archive_path" -C "$destination"
      ;;
    *.zip)
      unzip -q "$archive_path" -d "$destination"
      ;;
    *)
      unzip -q "$archive_path" -d "$destination"
      ;;
  esac
}

read_archive_file() {
  local archive_path="$1"
  local file_path="$2"

  case "$archive_path" in
    *.tar.gz|*.tgz)
      tar -xOf "$archive_path" "$file_path"
      ;;
    *.zip)
      unzip -p "$archive_path" "$file_path"
      ;;
    *)
      unzip -p "$archive_path" "$file_path"
      ;;
  esac
}

write_metadata_fixture() {
  local destination="$1"
  local skill

  while IFS= read -r skill; do
    mkdir -p "$destination/skills/$skill/agents"
    cat >"$destination/skills/$skill/agents/openai.yaml" <<EOF
interface:
  display_name: "$skill"
  short_description: "Fixture metadata for $skill"
EOF
  done < <(find "$REPO_ROOT/skills" -mindepth 1 -maxdepth 1 -type d -print | sed 's#.*/##' | sort)
}

echo "Codex package archive tests"

metadata_source="$TEST_ROOT/metadata-source"
archive="$TEST_ROOT/superpowers"
tar_archive="$TEST_ROOT/superpowers.tar.gz"
extracted="$TEST_ROOT/extracted"
tar_extracted="$TEST_ROOT/tar-extracted"
write_metadata_fixture "$metadata_source"

source_hooks="$(python3 -c 'import json; print(json.load(open("'"$REPO_ROOT"'/.codex-plugin/plugin.json")).get("hooks"))')"
assert_equals "$source_hooks" "{}" "source Codex manifest suppresses local hook auto-discovery"

if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_source" --output "$archive" 2>&1)"; then
  pass "package script exits successfully"
else
  fail "package script exits successfully"
  printf '%s\n' "$output" | sed 's/^/      /'
fi

if [[ -f "$archive" ]]; then
  pass "package script writes archive"
else
  fail "package script writes archive"
fi

assert_contains "$output" "Archive:" "reports archive path"
assert_contains "$output" "Format:  zip" "reports default zip format"
assert_contains "$output" "SHA-256:" "reports archive checksum"

extract_archive "$archive" "$extracted"

archive_paths="$(list_archive "$archive" | normalize_archive_paths)"
unexpected_pattern='(^superpowers/|^\.agents/|^hooks/|package\.json$|^\.git|^\.pytest_cache|^\.ruff_cache|^scripts/|^tests/|^docs/|^evals/|^lib/|^\.claude|^\.cursor|^\.kimi|^\.opencode|^\.pi|^AGENTS\.md$|^CLAUDE\.md$|^GEMINI\.md$|^RELEASE-NOTES\.md$|^CHANGELOG\.md$)'
assert_not_matches "$archive_paths" "$unexpected_pattern" "archive excludes source-only paths"
assert_contains "$archive_paths" ".codex-plugin/plugin.json" "archive includes Codex manifest"
assert_contains "$archive_paths" "skills/brainstorming/SKILL.md" "archive includes skills"
assert_contains "$archive_paths" "skills/brainstorming/agents/openai.yaml" "archive includes OpenAI skill metadata"
assert_contains "$archive_paths" "assets/app-icon.png" "archive includes app icon"
assert_contains "$archive_paths" "assets/superpowers-small.svg" "archive includes composer icon"

manifest_summary="$(read_archive_file "$archive" .codex-plugin/plugin.json | python3 -c 'import json,sys; data=json.load(sys.stdin); print("\t".join([data["name"], data["version"], data["skills"], str(data.get("hooks"))]))')"
expected_version="$(python3 -c 'import json; print(json.load(open("'"$REPO_ROOT"'/.codex-plugin/plugin.json"))["version"])')"
assert_equals "$manifest_summary" "superpowers	$expected_version	./skills/	$source_hooks" "archive manifest preserves source hooks"

skill_count="$(find "$extracted/skills" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')"
metadata_count="$(find "$extracted/skills" -path '*/agents/openai.yaml' -type f | wc -l | tr -d ' ')"
assert_equals "$metadata_count" "$skill_count" "every packaged skill has OpenAI metadata"

if [[ -x "$extracted/skills/subagent-driven-development/scripts/task-brief" ]]; then
  pass "archive preserves executable script mode"
else
  fail "archive preserves executable script mode"
fi

zip_times="$(python3 - "$archive" <<'PY'
import sys
import zipfile

with zipfile.ZipFile(sys.argv[1]) as archive:
    print("\n".join(sorted({str(info.date_time) for info in archive.infolist()})))
PY
)"
assert_equals "$zip_times" "(1980, 1, 1, 0, 0, 0)" "zip archive normalizes entry timestamps"

if tar_output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_source" --format tar.gz --output "$tar_archive" 2>&1)"; then
  pass "package script writes explicit tar.gz archive"
else
  fail "package script writes explicit tar.gz archive"
  printf '%s\n' "$tar_output" | sed 's/^/      /'
fi
assert_contains "$tar_output" "Format:  tar.gz" "reports explicit tar.gz format"

extract_archive "$tar_archive" "$tar_extracted"
tar_archive_paths="$(list_archive "$tar_archive" | normalize_archive_paths)"
assert_equals "$tar_archive_paths" "$archive_paths" "zip and tar.gz archives contain the same paths"

tar_task_brief_mode="$(tar -tzvf "$tar_archive" skills/subagent-driven-development/scripts/task-brief | awk '{print $1}')"
assert_equals "$tar_task_brief_mode" "-rwxr-xr-x" "tar.gz archive preserves executable script mode"

tar_metadata_times="$(python3 - "$tar_archive" <<'PY'
import sys, tarfile
with tarfile.open(sys.argv[1]) as archive:
    print(sorted({member.mtime for member in archive.getmembers()}))
PY
)"
assert_equals "$tar_metadata_times" "[0]" "tar.gz archive normalizes entry timestamps"

metadata_archive="$TEST_ROOT/metadata-source.tar.gz"
metadata_zip="$TEST_ROOT/metadata-source.zip"
archive_from_tar_source="$TEST_ROOT/superpowers-from-tar-source.zip"
archive_from_zip_source="$TEST_ROOT/superpowers-from-zip-source.zip"
(
  cd "$metadata_source"
  tar -czf "$metadata_archive" .
  zip -X -q -r "$metadata_zip" .
)

if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_archive" --output "$archive_from_tar_source" 2>&1)"; then
  pass "package script accepts tarball metadata source"
else
  fail "package script accepts tarball metadata source"
  printf '%s\n' "$output" | sed 's/^/      /'
fi

if cmp -s "$archive" "$archive_from_tar_source"; then
  pass "tarball metadata source produces identical archive"
else
  fail "tarball metadata source produces identical archive"
fi

if output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$metadata_zip" --output "$archive_from_zip_source" 2>&1)"; then
  pass "package script accepts zip metadata source"
else
  fail "package script accepts zip metadata source"
  printf '%s\n' "$output" | sed 's/^/      /'
fi

if cmp -s "$archive" "$archive_from_zip_source"; then
  pass "zip metadata source produces identical archive"
else
  fail "zip metadata source produces identical archive"
fi

incomplete_metadata="$TEST_ROOT/incomplete-metadata"
mkdir -p "$incomplete_metadata/skills/brainstorming/agents"
cp "$metadata_source/skills/brainstorming/agents/openai.yaml" \
  "$incomplete_metadata/skills/brainstorming/agents/openai.yaml"

set +e
missing_output="$("$SCRIPT_UNDER_TEST" --allow-dirty --metadata-source "$incomplete_metadata" --output "$TEST_ROOT/missing.tar.gz" 2>&1)"
missing_status=$?
set -e
if [[ "$missing_status" -ne 0 ]]; then
  pass "package script rejects incomplete metadata source"
else
  fail "package script rejects incomplete metadata source"
fi
assert_contains "$missing_output" "ERROR: metadata source is incomplete" "incomplete metadata reports clear error"

dirty_repo="$TEST_ROOT/dirty-repo"
git clone -q --no-local "$REPO_ROOT" "$dirty_repo"
printf '\n# dirty fixture\n' >>"$dirty_repo/README.md"
set +e
dirty_output="$(
  cd "$dirty_repo"
  scripts/package-codex-plugin.sh \
    --metadata-source "$metadata_source" \
    --output "$TEST_ROOT/dirty.zip" 2>&1
)"
dirty_status=$?
set -e
if [[ "$dirty_status" -ne 0 ]]; then
  pass "package script rejects dirty worktree by default"
else
  fail "package script rejects dirty worktree by default"
fi
assert_contains "$dirty_output" "Working tree has uncommitted changes:" "dirty worktree reports changed files"

if [[ "$FAILURES" -eq 0 ]]; then
  echo "All Codex package archive tests passed"
else
  echo "$FAILURES Codex package archive test(s) failed"
  exit 1
fi
tests/codex-plugin-sync/test-sync-to-codex-plugin.sh 759 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SYNC_SCRIPT_SOURCE="$REPO_ROOT/scripts/sync-to-codex-plugin.sh"
BASH_UNDER_TEST="/bin/bash"
PACKAGE_VERSION="1.2.3"
MANIFEST_VERSION="9.8.7"

FAILURES=0
TEST_ROOT=""

pass() {
    echo "  [PASS] $1"
}

fail() {
    echo "  [FAIL] $1"
    FAILURES=$((FAILURES + 1))
}

assert_equals() {
    local actual="$1"
    local expected="$2"
    local description="$3"

    if [[ "$actual" == "$expected" ]]; then
        pass "$description"
    else
        fail "$description"
        echo "    expected: $expected"
        echo "    actual:   $actual"
    fi
}

assert_contains() {
    local haystack="$1"
    local needle="$2"
    local description="$3"

    if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
        pass "$description"
    else
        fail "$description"
        echo "    expected to find: $needle"
    fi
}

assert_not_contains() {
    local haystack="$1"
    local needle="$2"
    local description="$3"

    if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
        fail "$description"
        echo "    did not expect to find: $needle"
    else
        pass "$description"
    fi
}

assert_matches() {
    local haystack="$1"
    local pattern="$2"
    local description="$3"

    if printf '%s' "$haystack" | grep -Eq -- "$pattern"; then
        pass "$description"
    else
        fail "$description"
        echo "    expected to match: $pattern"
    fi
}

assert_not_matches() {
    local haystack="$1"
    local pattern="$2"
    local description="$3"

    if printf '%s' "$haystack" | grep -Eq -- "$pattern"; then
        fail "$description"
        echo "    did not expect to match: $pattern"
    else
        pass "$description"
    fi
}

assert_path_absent() {
    local path="$1"
    local description="$2"

    if [[ ! -e "$path" ]]; then
        pass "$description"
    else
        fail "$description"
        echo "    did not expect path to exist: $path"
    fi
}

assert_branch_absent() {
    local repo="$1"
    local pattern="$2"
    local description="$3"
    local branches

    branches="$(git -C "$repo" branch --list "$pattern")"

    if [[ -z "$branches" ]]; then
        pass "$description"
    else
        fail "$description"
        echo "    did not expect matching branches:"
        echo "$branches" | sed 's/^/      /'
    fi
}

assert_current_branch() {
    local repo="$1"
    local expected="$2"
    local description="$3"
    local actual

    actual="$(git -C "$repo" branch --show-current)"
    assert_equals "$actual" "$expected" "$description"
}

assert_file_equals() {
    local path="$1"
    local expected="$2"
    local description="$3"
    local actual

    actual="$(cat "$path")"
    assert_equals "$actual" "$expected" "$description"
}

cleanup() {
    if [[ -n "$TEST_ROOT" && -d "$TEST_ROOT" ]]; then
        rm -rf "$TEST_ROOT"
    fi
}

configure_git_identity() {
    local repo="$1"

    git -C "$repo" config user.name "Test Bot"
    git -C "$repo" config user.email "test@example.com"
}

init_repo() {
    local repo="$1"

    git init -q -b main "$repo"
    configure_git_identity "$repo"
}

commit_fixture() {
    local repo="$1"
    local message="$2"

    git -C "$repo" commit -q -m "$message"
}

checkout_fixture_branch() {
    local repo="$1"
    local branch="$2"

    git -C "$repo" checkout -q -b "$branch"
}

write_upstream_fixture() {
    local repo="$1"
    local with_pure_ignored="${2:-1}"

    mkdir -p \
        "$repo/.antigravity-plugin" \
        "$repo/.codex-plugin" \
        "$repo/.kimi-plugin" \
        "$repo/.private-journal" \
        "$repo/assets" \
        "$repo/evals/drill" \
        "$repo/hooks" \
        "$repo/scripts" \
        "$repo/skills/example"

    if [[ "$with_pure_ignored" == "1" ]]; then
        mkdir -p "$repo/ignored-cache/tmp"
    fi

    cp "$SYNC_SCRIPT_SOURCE" "$repo/scripts/sync-to-codex-plugin.sh"

    cat > "$repo/package.json" <<EOF
{
  "name": "fixture-upstream",
  "version": "$PACKAGE_VERSION"
}
EOF

    cat > "$repo/index.js" <<'EOF'
export { default } from "./.opencode/plugins/superpowers.js";
EOF

    cat > "$repo/.gitignore" <<'EOF'
.private-journal/
EOF

    cat > "$repo/.gitmodules" <<'EOF'
[submodule "evals"]
	path = evals
	url = git@example.com:example/evals.git
EOF

    cat > "$repo/.pre-commit-config.yaml" <<'EOF'
repos:
  - repo: local
    hooks:
      - id: evals-check
        name: evals check
        entry: echo evals
        language: system
        files: ^evals/
EOF

    if [[ "$with_pure_ignored" == "1" ]]; then
        cat >> "$repo/.gitignore" <<'EOF'
ignored-cache/
EOF
    fi

    cat > "$repo/.codex-plugin/plugin.json" <<EOF
{
  "name": "superpowers",
  "version": "$MANIFEST_VERSION"
}
EOF

    cat > "$repo/.kimi-plugin/plugin.json" <<EOF
{
  "name": "superpowers",
  "version": "$MANIFEST_VERSION"
}
EOF

    cat > "$repo/.antigravity-plugin/plugin.json" <<EOF
{
  "name": "superpowers",
  "version": "$MANIFEST_VERSION"
}
EOF

    printf 'antigravity png fixture\n' > "$repo/assets/antigravity-logo.png"

    cat > "$repo/assets/superpowers-small.svg" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>
EOF

    printf 'png fixture\n' > "$repo/assets/app-icon.png"
    printf 'eval harness fixture\n' > "$repo/evals/drill/README.md"

    cat > "$repo/hooks/hooks-codex.json" <<'EOF'
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume|clear",
        "hooks": [
          {
            "type": "command",
            "command": "\"${PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start-codex",
            "async": false
          }
        ]
      }
    ]
  }
}
EOF

    cat > "$repo/hooks/session-start" <<'EOF'
#!/usr/bin/env sh
echo "session-start fixture"
EOF
    cat > "$repo/hooks/session-start-codex" <<'EOF'
#!/usr/bin/env sh
echo "session-start-codex fixture"
EOF

    cat > "$repo/hooks/run-hook.cmd" <<'EOF'
@echo off
echo run-hook fixture
EOF
    chmod +x "$repo/hooks/session-start" "$repo/hooks/session-start-codex" "$repo/hooks/run-hook.cmd"

    cat > "$repo/skills/example/SKILL.md" <<'EOF'
# Example Skill

Fixture content.
EOF

    printf 'tracked keep\n' > "$repo/.private-journal/keep.txt"
    printf 'ignored leak\n' > "$repo/.private-journal/leak.txt"
    if [[ "$with_pure_ignored" == "1" ]]; then
        printf 'ignored cache state\n' > "$repo/ignored-cache/tmp/state.json"
    fi

    git -C "$repo" add \
        .antigravity-plugin/plugin.json \
        .codex-plugin/plugin.json \
        .kimi-plugin/plugin.json \
        .gitignore \
        .gitmodules \
        .pre-commit-config.yaml \
        assets/antigravity-logo.png \
        assets/app-icon.png \
        assets/superpowers-small.svg \
        evals/drill/README.md \
        hooks/hooks-codex.json \
        hooks/run-hook.cmd \
        hooks/session-start \
        hooks/session-start-codex \
        index.js \
        package.json \
        scripts/sync-to-codex-plugin.sh \
        skills/example/SKILL.md
    git -C "$repo" add -f .private-journal/keep.txt

    commit_fixture "$repo" "Initial upstream fixture"
}

write_destination_fixture() {
    local repo="$1"

    mkdir -p "$repo/plugins/superpowers/skills/example"
    printf 'fixture keep\n' > "$repo/plugins/superpowers/.fixture-keep"
    cat > "$repo/plugins/superpowers/skills/example/SKILL.md" <<'EOF'
# Example Skill

Fixture content.
EOF
    git -C "$repo" add plugins/superpowers/.fixture-keep
    git -C "$repo" add plugins/superpowers/skills/example/SKILL.md

    commit_fixture "$repo" "Initial destination fixture"
}

add_openai_agent_metadata_fixture() {
    local repo="$1"

    mkdir -p "$repo/plugins/superpowers/skills/example/agents"

    cat > "$repo/plugins/superpowers/skills/example/agents/openai.yaml" <<'EOF'
interface:
  display_name: "Example"
  short_description: "Destination-owned OpenAI metadata"
EOF

    git -C "$repo" add plugins/superpowers/skills/example/agents/openai.yaml

    commit_fixture "$repo" "Add OpenAI agent metadata fixture"
}

dirty_tracked_destination_skill() {
    local repo="$1"

    cat > "$repo/plugins/superpowers/skills/example/SKILL.md" <<'EOF'
# Example Skill

Locally modified fixture content.
EOF
}

write_synced_destination_fixture() {
    local repo="$1"

    mkdir -p \
        "$repo/plugins/superpowers/.codex-plugin" \
        "$repo/plugins/superpowers/.private-journal" \
        "$repo/plugins/superpowers/assets" \
        "$repo/plugins/superpowers/hooks" \
        "$repo/plugins/superpowers/skills/example/agents" \
        "$repo/plugins/superpowers/skills/example"

    cat > "$repo/plugins/superpowers/.codex-plugin/plugin.json" <<EOF
{
  "name": "superpowers",
  "version": "$MANIFEST_VERSION"
}
EOF

    cat > "$repo/plugins/superpowers/assets/superpowers-small.svg" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"></svg>
EOF

    printf 'png fixture\n' > "$repo/plugins/superpowers/assets/app-icon.png"

    cat > "$repo/plugins/superpowers/hooks/hooks-codex.json" <<'EOF'
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume|clear",
        "hooks": [
          {
            "type": "command",
            "command": "\"${PLUGIN_ROOT}/hooks/run-hook.cmd\" session-start-codex",
            "async": false
          }
        ]
      }
    ]
  }
}
EOF

    cat > "$repo/plugins/superpowers/hooks/session-start" <<'EOF'
#!/usr/bin/env sh
echo "session-start fixture"
EOF
    cat > "$repo/plugins/superpowers/hooks/session-start-codex" <<'EOF'
#!/usr/bin/env sh
echo "session-start-codex fixture"
EOF

    cat > "$repo/plugins/superpowers/hooks/run-hook.cmd" <<'EOF'
@echo off
echo run-hook fixture
EOF
    chmod +x "$repo/plugins/superpowers/hooks/session-start" "$repo/plugins/superpowers/hooks/session-start-codex" "$repo/plugins/superpowers/hooks/run-hook.cmd"

    cat > "$repo/plugins/superpowers/skills/example/SKILL.md" <<'EOF'
# Example Skill

Fixture content.
EOF

    cat > "$repo/plugins/superpowers/skills/example/agents/openai.yaml" <<'EOF'
interface:
  display_name: "Example"
  short_description: "Destination-owned OpenAI metadata"
EOF

    printf 'tracked keep\n' > "$repo/plugins/superpowers/.private-journal/keep.txt"

    git -C "$repo" add \
        plugins/superpowers/.codex-plugin/plugin.json \
        plugins/superpowers/assets/app-icon.png \
        plugins/superpowers/assets/superpowers-small.svg \
        plugins/superpowers/hooks/hooks-codex.json \
        plugins/superpowers/hooks/run-hook.cmd \
        plugins/superpowers/hooks/session-start \
        plugins/superpowers/hooks/session-start-codex \
        plugins/superpowers/skills/example/agents/openai.yaml \
        plugins/superpowers/skills/example/SKILL.md \
        plugins/superpowers/.private-journal/keep.txt

    commit_fixture "$repo" "Initial synced destination fixture"
}

write_stale_ignored_destination_fixture() {
    local repo="$1"

    mkdir -p \
        "$repo/plugins/superpowers/.kimi-plugin" \
        "$repo/plugins/superpowers/.private-journal"
    printf 'fixture keep\n' > "$repo/plugins/superpowers/.fixture-keep"
    printf '{"name":"stale-kimi"}\n' > "$repo/plugins/superpowers/.kimi-plugin/plugin.json"
    printf 'stale ignored leak\n' > "$repo/plugins/superpowers/.private-journal/leak.txt"
    git -C "$repo" add \
        plugins/superpowers/.fixture-keep \
        plugins/superpowers/.kimi-plugin/plugin.json

    commit_fixture "$repo" "Initial stale ignored destination fixture"
}

write_fake_gh() {
    local bin_dir="$1"

    mkdir -p "$bin_dir"

    cat > "$bin_dir/gh" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

if [[ "${1:-}" == "auth" && "${2:-}" == "status" ]]; then
    exit 0
fi

echo "unexpected gh invocation: $*" >&2
exit 1
EOF

    chmod +x "$bin_dir/gh"
}

run_preview() {
    local upstream="$1"
    local dest="$2"
    local fake_bin="$3"

    PATH="$fake_bin:$PATH" "$BASH_UNDER_TEST" "$upstream/scripts/sync-to-codex-plugin.sh" -n --local "$dest" 2>&1
}

run_bootstrap_preview() {
    local upstream="$1"
    local dest="$2"
    local fake_bin="$3"

    PATH="$fake_bin:$PATH" "$BASH_UNDER_TEST" "$upstream/scripts/sync-to-codex-plugin.sh" -n --bootstrap --local "$dest" 2>&1
}

run_preview_without_manifest() {
    local upstream="$1"
    local dest="$2"
    local fake_bin="$3"

    rm -f "$upstream/.codex-plugin/plugin.json"
    PATH="$fake_bin:$PATH" "$BASH_UNDER_TEST" "$upstream/scripts/sync-to-codex-plugin.sh" -n --local "$dest" 2>&1
}

run_preview_with_stale_ignored_destination() {
    local upstream="$1"
    local dest="$2"
    local fake_bin="$3"

    PATH="$fake_bin:$PATH" "$BASH_UNDER_TEST" "$upstream/scripts/sync-to-codex-plugin.sh" -n --local "$dest" 2>&1
}

run_apply() {
    local upstream="$1"
    local dest="$2"
    local fake_bin="$3"

    PATH="$fake_bin:$PATH" "$BASH_UNDER_TEST" "$upstream/scripts/sync-to-codex-plugin.sh" -y --local "$dest" 2>&1
}

run_help() {
    local upstream="$1"
    local fake_bin="$2"

    PATH="$fake_bin:$PATH" "$BASH_UNDER_TEST" "$upstream/scripts/sync-to-codex-plugin.sh" --help 2>&1
}

write_bootstrap_destination_fixture() {
    local repo="$1"

    printf 'bootstrap fixture\n' > "$repo/README.md"
    git -C "$repo" add README.md

    commit_fixture "$repo" "Initial bootstrap destination fixture"
}

main() {
    local upstream
    local mixed_only_upstream
    local dest
    local dest_branch
    local mixed_only_dest
    local stale_dest
    local dirty_apply_dest
    local dirty_apply_dest_branch
    local noop_apply_dest
    local noop_apply_dest_branch
    local fake_bin
    local bootstrap_dest
    local bootstrap_dest_branch
    local preview_status
    local preview_output
    local preview_section
    local bootstrap_status
    local bootstrap_output
    local missing_manifest_status
    local missing_manifest_output
    local mixed_only_status
    local mixed_only_output
    local stale_preview_status
    local stale_preview_output
    local stale_preview_section
    local dirty_apply_status
    local dirty_apply_output
    local noop_apply_status
    local noop_apply_output
    local help_output
    local script_source
    local dirty_skill_path
    local noop_openai_metadata_path

    echo "=== Test: sync-to-codex-plugin dry-run regression ==="

    TEST_ROOT="$(mktemp -d)"
    trap cleanup EXIT

    upstream="$TEST_ROOT/upstream"
    mixed_only_upstream="$TEST_ROOT/mixed-only-upstream"
    dest="$TEST_ROOT/destination"
    mixed_only_dest="$TEST_ROOT/mixed-only-destination"
    stale_dest="$TEST_ROOT/stale-destination"
    dirty_apply_dest="$TEST_ROOT/dirty-apply-destination"
    dirty_apply_dest_branch="fixture/dirty-apply-target"
    noop_apply_dest="$TEST_ROOT/noop-apply-destination"
    noop_apply_dest_branch="fixture/noop-apply-target"
    bootstrap_dest="$TEST_ROOT/bootstrap-destination"
    dest_branch="fixture/preview-target"
    bootstrap_dest_branch="fixture/bootstrap-preview-target"
    fake_bin="$TEST_ROOT/bin"

    init_repo "$upstream"
    write_upstream_fixture "$upstream"

    init_repo "$mixed_only_upstream"
    write_upstream_fixture "$mixed_only_upstream" 0

    init_repo "$dest"
    write_destination_fixture "$dest"
    add_openai_agent_metadata_fixture "$dest"
    checkout_fixture_branch "$dest" "$dest_branch"
    dirty_tracked_destination_skill "$dest"

    init_repo "$mixed_only_dest"
    write_destination_fixture "$mixed_only_dest"

    init_repo "$stale_dest"
    write_stale_ignored_destination_fixture "$stale_dest"

    init_repo "$dirty_apply_dest"
    write_synced_destination_fixture "$dirty_apply_dest"
    checkout_fixture_branch "$dirty_apply_dest" "$dirty_apply_dest_branch"
    dirty_tracked_destination_skill "$dirty_apply_dest"

    init_repo "$noop_apply_dest"
    write_synced_destination_fixture "$noop_apply_dest"
    checkout_fixture_branch "$noop_apply_dest" "$noop_apply_dest_branch"

    init_repo "$bootstrap_dest"
    write_bootstrap_destination_fixture "$bootstrap_dest"
    checkout_fixture_branch "$bootstrap_dest" "$bootstrap_dest_branch"

    write_fake_gh "$fake_bin"

    # This regression test is about dry-run content, so capture the preview
    # output even if the current script exits nonzero in --local mode.
    set +e
    preview_output="$(run_preview "$upstream" "$dest" "$fake_bin")"
    preview_status=$?
    bootstrap_output="$(run_bootstrap_preview "$upstream" "$bootstrap_dest" "$fake_bin")"
    bootstrap_status=$?
    mixed_only_output="$(run_preview "$mixed_only_upstream" "$mixed_only_dest" "$fake_bin")"
    mixed_only_status=$?
    stale_preview_output="$(run_preview_with_stale_ignored_destination "$upstream" "$stale_dest" "$fake_bin")"
    stale_preview_status=$?
    dirty_apply_output="$(run_apply "$upstream" "$dirty_apply_dest" "$fake_bin")"
    dirty_apply_status=$?
    noop_apply_output="$(run_apply "$upstream" "$noop_apply_dest" "$fake_bin")"
    noop_apply_status=$?
    missing_manifest_output="$(run_preview_without_manifest "$upstream" "$dest" "$fake_bin")"
    missing_manifest_status=$?
    set -e
    help_output="$(run_help "$upstream" "$fake_bin")"
    script_source="$(cat "$upstream/scripts/sync-to-codex-plugin.sh")"
    preview_section="$(printf '%s\n' "$preview_output" | sed -n '/^=== Preview (rsync --dry-run) ===$/,/^=== End preview ===$/p')"
    stale_preview_section="$(printf '%s\n' "$stale_preview_output" | sed -n '/^=== Preview (rsync --dry-run) ===$/,/^=== End preview ===$/p')"
    dirty_skill_path="$dirty_apply_dest/plugins/superpowers/skills/example/SKILL.md"
    noop_openai_metadata_path="$noop_apply_dest/plugins/superpowers/skills/example/agents/openai.yaml"

    echo ""
    echo "Preview assertions..."
    assert_equals "$preview_status" "0" "Preview exits successfully"
    assert_contains "$preview_output" "Version:  $MANIFEST_VERSION" "Preview uses manifest version"
    assert_not_contains "$preview_output" "Version:  $PACKAGE_VERSION" "Preview does not use package.json version"
    assert_contains "$preview_section" ".codex-plugin/plugin.json" "Preview includes manifest path"
    assert_not_contains "$preview_section" ".kimi-plugin/plugin.json" "Preview excludes Kimi manifest from Codex sync"
    assert_not_contains "$preview_section" ".antigravity-plugin/plugin.json" "Preview excludes Antigravity manifest from Codex sync"
    assert_not_contains "$preview_section" "assets/antigravity-logo.png" "Preview excludes Antigravity logo from Codex sync"
    assert_contains "$preview_section" "assets/superpowers-small.svg" "Preview includes SVG asset"
    assert_contains "$preview_section" "assets/app-icon.png" "Preview includes PNG asset"
    assert_contains "$preview_section" "hooks/hooks-codex.json" "Preview includes Codex hook manifest"
    assert_contains "$preview_section" "hooks/session-start" "Preview includes session-start hook"
    assert_contains "$preview_section" "hooks/session-start-codex" "Preview includes Codex session-start hook"
    assert_contains "$preview_section" "hooks/run-hook.cmd" "Preview includes hook command wrapper"
    assert_contains "$preview_section" ".private-journal/keep.txt" "Preview includes tracked ignored file"
    assert_not_contains "$preview_section" ".private-journal/leak.txt" "Preview excludes ignored untracked file"
    assert_not_contains "$preview_section" "ignored-cache/" "Preview excludes pure ignored directories"
    assert_not_contains "$preview_section" "evals/" "Preview excludes eval harness"
    assert_not_contains "$preview_section" ".gitmodules" "Preview excludes repo submodule metadata"
    assert_not_contains "$preview_section" ".pre-commit-config.yaml" "Preview excludes repo pre-commit config"
    assert_not_contains "$preview_section" "index.js" "Preview excludes OpenCode root entrypoint"
    assert_not_contains "$preview_output" "Overlay file (.codex-plugin/plugin.json) will be regenerated" "Preview omits overlay regeneration note"
    assert_not_contains "$preview_output" "Assets (superpowers-small.svg, app-icon.png) will be seeded from" "Preview omits assets seeding note"
    assert_contains "$preview_section" "skills/example/SKILL.md" "Preview reflects dirty tracked destination file"
    assert_not_matches "$preview_section" "\\*deleting +skills/example/agents/openai\\.yaml" "Preview preserves destination-owned OpenAI agent metadata"
    assert_current_branch "$dest" "$dest_branch" "Preview leaves destination checkout on its original branch"
    assert_branch_absent "$dest" "sync/superpowers-*" "Preview does not create sync branch in destination checkout"

    echo ""
    echo "Mixed-directory assertions..."
    assert_equals "$mixed_only_status" "0" "Mixed ignored directory preview exits successfully under /bin/bash"
    assert_contains "$mixed_only_output" ".private-journal/keep.txt" "Mixed ignored directory preview still includes tracked ignored file"
    assert_not_contains "$mixed_only_output" "ignored-cache/" "Mixed ignored directory preview has no pure ignored directory fixture"

    echo ""
    echo "Convergence assertions..."
    assert_equals "$stale_preview_status" "0" "Stale ignored destination preview exits successfully"
    assert_matches "$stale_preview_section" "\\*deleting +\\.kimi-plugin/plugin\\.json" "Preview deletes stale Kimi manifest from Codex plugin"
    assert_matches "$stale_preview_section" "\\*deleting +\\.private-journal/leak\\.txt" "Preview deletes stale ignored destination file"

    echo ""
    echo "Bootstrap assertions..."
    assert_equals "$bootstrap_status" "0" "Bootstrap preview exits successfully"
    assert_contains "$bootstrap_output" "Mode:     BOOTSTRAP (creating plugins/superpowers/ when absent)" "Bootstrap preview describes directory creation"
    assert_not_contains "$bootstrap_output" "Assets:" "Bootstrap preview omits external assets path"
    assert_contains "$bootstrap_output" "Dry run only. Nothing was changed or pushed." "Bootstrap preview remains dry-run only"
    assert_path_absent "$bootstrap_dest/plugins/superpowers" "Bootstrap preview does not create destination plugin directory"
    assert_current_branch "$bootstrap_dest" "$bootstrap_dest_branch" "Bootstrap preview leaves destination checkout on its original branch"
    assert_branch_absent "$bootstrap_dest" "bootstrap/superpowers-*" "Bootstrap preview does not create bootstrap branch in destination checkout"

    echo ""
    echo "Apply assertions..."
    assert_equals "$dirty_apply_status" "1" "Dirty local apply exits with failure"
    assert_contains "$dirty_apply_output" "ERROR: local checkout has uncommitted changes under 'plugins/superpowers'" "Dirty local apply reports protected destination path"
    assert_current_branch "$dirty_apply_dest" "$dirty_apply_dest_branch" "Dirty local apply leaves destination checkout on its original branch"
    assert_branch_absent "$dirty_apply_dest" "sync/superpowers-*" "Dirty local apply does not create sync branch in destination checkout"
    assert_file_equals "$dirty_skill_path" "# Example Skill

Locally modified fixture content." "Dirty local apply preserves tracked working-tree file content"
    assert_equals "$noop_apply_status" "0" "Clean no-op local apply exits successfully"
    assert_contains "$noop_apply_output" "No changes — embedded plugin was already in sync with upstream" "Clean no-op local apply reports no changes"
    assert_current_branch "$noop_apply_dest" "$noop_apply_dest_branch" "Clean no-op local apply leaves destination checkout on its original branch"
    assert_branch_absent "$noop_apply_dest" "sync/superpowers-*" "Clean no-op local apply does not create sync branch in destination checkout"
    assert_file_equals "$noop_openai_metadata_path" "interface:
  display_name: \"Example\"
  short_description: \"Destination-owned OpenAI metadata\"" "Clean no-op local apply preserves OpenAI agent metadata"

    echo ""
    echo "Missing manifest assertions..."
    assert_equals "$missing_manifest_status" "1" "Missing manifest exits with failure"
    assert_contains "$missing_manifest_output" "ERROR: committed Codex manifest missing at" "Missing manifest reports committed manifest path"

    echo ""
    echo "Help assertions..."
    assert_not_contains "$help_output" "--assets-src" "Help omits --assets-src"

    echo ""
    echo "Source assertions..."
    assert_not_contains "$script_source" "regenerated inline" "Source drops regenerated inline phrasing"
    assert_not_contains "$script_source" "Brand Assets directory" "Source drops Brand Assets directory phrasing"
    assert_not_contains "$script_source" "--assets-src" "Source drops --assets-src"

    if [[ $FAILURES -ne 0 ]]; then
        echo ""
        echo "FAILED: $FAILURES assertion(s) failed."
        exit 1
    fi

    echo ""
    echo "PASS"
}

main "$@"

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč se sync preview nesmí dotknout cílového checkoutu?

Preview je „co by se stalo“. Kdyby přepnul branch nebo vytvořil sync/*, měnil by stav cíle a nešlo by mu věřit jako bezpečnému náhledu. Test hlídá, že cílový branch zůstane původní.

2. Proč se vylučují manifesty Kimi a Antigravity z Codex pluginu?

Codex balíček má obsahovat jen to, co Codex potřebuje. Cizí manifesty by zbytečně zvětšily plugin a mohly by matoucím způsobem ovlivnit discovery.

3. Proč se verze bere z manifestu, a ne z package.json?

Codex plugin je distribuovaný samostatně a jeho verze je zapsána v .codex-plugin/plugin.json. Test používá různé hodnoty (1.2.3 vs. 9.8.7), aby bylo vidět, odkud se čte.

4. Proč se vylučují nesledované ignorované soubory, ale sledované ignorované se zahrnou?

Pokud je soubor sledovaný gitem (.private-journal/keep.txt), je záměrnou součástí repozitáře. Nesledovaný ignorovaný (leak.txt) je lokální smetí a nesmí se dostat ven.

5. K čemu je `SHA-256` ve výstupu balení?

Příjemce archivu může ověřit integritu stažení. Test hlídá, že skript checksum vždy vypíše.

6. Proč manifest potlačuje auto-discovery hooků (`hooks: {}`)?

Codex by jinak mohl hooky načíst automaticky z jiného místa. Prázdný objekt říká, že hooky se řídí explicitně připojenou konfigurací.

7. Proč se test spouští pod `/bin/bash`?

Na macOS je /bin/bash starý (3.x). Test ověřuje, že skript funguje i tam, kde chybí moderní funkce shellu.

8. Proč se maže zastaralé soubory v cíli (`*deleting`)?

Sync má cíl zrcadlit. Soubory, které už ve zdroji nejsou (např. starý manifest Kimi), by v cíli zůstaly a rozbily konzistenci.

9. Proč test kontroluje, že se zachová OpenAI agent metadata cílového repozitáře?

Některé soubory vlastní cíl, ne zdroj. Sync je nesmí smazat, jinak by přišel o ruční úpravy.

Slovník pojmů (9)

Marketplace manifest

.agents/plugins/marketplace.json popisující plugin pro Codex.

Plugin packaging

Vytvoření archivu pluginu (zip) se SHA-256.

Sync preview

Náhled změn synchronizace bez provedení.

`rsync` deleting

Řádky *deleting označují soubory, které se z cíle odstraní.

Overlay manifest

.codex-plugin/plugin.json generovaný pro cílový plugin.

Tracked ignored file

Soubor ignorovaný gitem, ale přesto sledovaný (zahrnuje se).

Hooks auto-discovery

Automatické hledání hooků; manifest ji potlačuje.

Checksum

Hash archivu pro ověření integrity.

Destination checkout

Repozitář, do kterého se synchronizuje.

↑ nahoru

Testy explicitních žádostí o skill: runnery

Skripty, které posílají prompty agentovi v izolovaném prostředí (jedno kolo, multiturn, haiku) a kontrolují, zda se skill vyvolal.

Runnery využívají prompty z adresáře prompts/ (viz příklad „Prompty pro test explicitních žádostí“). run-test.sh <skill> <prompt-file> vytvoří izolovaný projekt a izolovaný HOME, do docs/superpowers/plans/auth-system.md zapíše ukázkový plán (tři úkoly), spustí claude -p s --plugin-dir, --max-turns a --output-format stream-json s timeoutem 300 s a výstup uloží do JSON logu, ve kterém se hledá volání nástroje Skill. run-all.sh projde všechny scénáře.

run-multiturn-test.sh buduje reálnou historii konverzace, aby reprodukoval selhání, kdy agent po delším rozhovoru skill přeskočí, a run-extended-multiturn-test.sh přidává ještě více kontextu. run-haiku-test.sh zkouší stejné s levnějším modelem a s uživatelským CLAUDE.md, protože slabší model může selhat snáz.

Zdrojový kód

tests/explicit-skill-requests/run-all.sh 71 řádků
#!/usr/bin/env bash
# Run all explicit skill request tests
# Usage: ./run-all.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROMPTS_DIR="$SCRIPT_DIR/prompts"

echo "=== Running All Explicit Skill Request Tests ==="
echo ""

PASSED=0
FAILED=0
RESULTS=""

# Test: subagent-driven-development, please
echo ">>> Test 1: subagent-driven-development-please"
if "$SCRIPT_DIR/run-test.sh" "subagent-driven-development" "$PROMPTS_DIR/subagent-driven-development-please.txt"; then
    PASSED=$((PASSED + 1))
    RESULTS="$RESULTS\nPASS: subagent-driven-development-please"
else
    FAILED=$((FAILED + 1))
    RESULTS="$RESULTS\nFAIL: subagent-driven-development-please"
fi
echo ""

# Test: use systematic-debugging
echo ">>> Test 2: use-systematic-debugging"
if "$SCRIPT_DIR/run-test.sh" "systematic-debugging" "$PROMPTS_DIR/use-systematic-debugging.txt"; then
    PASSED=$((PASSED + 1))
    RESULTS="$RESULTS\nPASS: use-systematic-debugging"
else
    FAILED=$((FAILED + 1))
    RESULTS="$RESULTS\nFAIL: use-systematic-debugging"
fi
echo ""

# Test: please use brainstorming
echo ">>> Test 3: please-use-brainstorming"
if "$SCRIPT_DIR/run-test.sh" "brainstorming" "$PROMPTS_DIR/please-use-brainstorming.txt"; then
    PASSED=$((PASSED + 1))
    RESULTS="$RESULTS\nPASS: please-use-brainstorming"
else
    FAILED=$((FAILED + 1))
    RESULTS="$RESULTS\nFAIL: please-use-brainstorming"
fi
echo ""

# Test: mid-conversation execute plan
echo ">>> Test 4: mid-conversation-execute-plan"
if "$SCRIPT_DIR/run-test.sh" "subagent-driven-development" "$PROMPTS_DIR/mid-conversation-execute-plan.txt"; then
    PASSED=$((PASSED + 1))
    RESULTS="$RESULTS\nPASS: mid-conversation-execute-plan"
else
    FAILED=$((FAILED + 1))
    RESULTS="$RESULTS\nFAIL: mid-conversation-execute-plan"
fi
echo ""

echo "=== Summary ==="
echo -e "$RESULTS"
echo ""
echo "Passed: $PASSED"
echo "Failed: $FAILED"
echo "Total: $((PASSED + FAILED))"

if [ "$FAILED" -gt 0 ]; then
    exit 1
fi
tests/explicit-skill-requests/run-test.sh 137 řádků
#!/usr/bin/env bash
# Test explicit skill requests (user names a skill directly)
# Usage: ./run-test.sh <skill-name> <prompt-file>
#
# Tests whether Claude invokes a skill when the user explicitly requests it by name
# (without using the plugin namespace prefix)
#
# Uses isolated HOME to avoid user context interference

set -e

SKILL_NAME="$1"
PROMPT_FILE="$2"
MAX_TURNS="${3:-3}"

if [ -z "$SKILL_NAME" ] || [ -z "$PROMPT_FILE" ]; then
    echo "Usage: $0 <skill-name> <prompt-file> [max-turns]"
    echo "Example: $0 subagent-driven-development ./prompts/subagent-driven-development-please.txt"
    exit 1
fi

# Get the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Get the superpowers plugin root (two levels up)
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/${SKILL_NAME}"
mkdir -p "$OUTPUT_DIR"

# Read prompt from file
PROMPT=$(cat "$PROMPT_FILE")

echo "=== Explicit Skill Request Test ==="
echo "Skill: $SKILL_NAME"
echo "Prompt file: $PROMPT_FILE"
echo "Max turns: $MAX_TURNS"
echo "Output dir: $OUTPUT_DIR"
echo ""

# Copy prompt for reference
cp "$PROMPT_FILE" "$OUTPUT_DIR/prompt.txt"

# Create a minimal project directory for the test
PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"

# Create a dummy plan file for mid-conversation tests
cat > "$PROJECT_DIR/docs/superpowers/plans/auth-system.md" << 'EOF'
# Auth System Implementation Plan

## Task 1: Add User Model
Create user model with email and password fields.

## Task 2: Add Auth Routes
Create login and register endpoints.

## Task 3: Add JWT Middleware
Protect routes with JWT validation.
EOF

# Run Claude with isolated environment
LOG_FILE="$OUTPUT_DIR/claude-output.json"
cd "$PROJECT_DIR"

echo "Plugin dir: $PLUGIN_DIR"
echo "Running claude -p with explicit skill request..."
echo "Prompt: $PROMPT"
echo ""

timeout 300 claude -p "$PROMPT" \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns "$MAX_TURNS" \
    --output-format stream-json \
    > "$LOG_FILE" 2>&1 || true

echo ""
echo "=== Results ==="

# Check if skill was triggered (look for Skill tool invocation)
# Match either "skill":"skillname" or "skill":"namespace:skillname"
SKILL_PATTERN='"skill":"([^"]*:)?'"${SKILL_NAME}"'"'
if grep -q '"name":"Skill"' "$LOG_FILE" && grep -qE "$SKILL_PATTERN" "$LOG_FILE"; then
    echo "PASS: Skill '$SKILL_NAME' was triggered"
    TRIGGERED=true
else
    echo "FAIL: Skill '$SKILL_NAME' was NOT triggered"
    TRIGGERED=false
fi

# Show what skills WERE triggered
echo ""
echo "Skills triggered in this run:"
grep -o '"skill":"[^"]*"' "$LOG_FILE" 2>/dev/null | sort -u || echo "  (none)"

# Check if Claude took action BEFORE invoking the skill (the failure mode)
echo ""
echo "Checking for premature action..."

# Look for tool invocations before the Skill invocation
# This detects the failure mode where Claude starts doing work without loading the skill
FIRST_SKILL_LINE=$(grep -n '"name":"Skill"' "$LOG_FILE" | head -1 | cut -d: -f1)
if [ -n "$FIRST_SKILL_LINE" ]; then
    # Check if any non-Skill, non-system tools were invoked before the first Skill invocation
    # Filter out task tracking tools (planning is ok) and other non-action tools
    PREMATURE_TOOLS=$(head -n "$FIRST_SKILL_LINE" "$LOG_FILE" | \
        grep '"type":"tool_use"' | \
        grep -v '"name":"Skill"' | \
        grep -vE '"name":"(TodoWrite|TaskCreate|TaskUpdate|TaskList|TaskGet)"' || true)
    if [ -n "$PREMATURE_TOOLS" ]; then
        echo "WARNING: Tools invoked BEFORE Skill tool:"
        echo "$PREMATURE_TOOLS" | head -5
        echo ""
        echo "This indicates Claude started working before loading the requested skill."
    else
        echo "OK: No premature tool invocations detected"
    fi
else
    echo "WARNING: No Skill invocation found at all"
fi

# Show first assistant message
echo ""
echo "First assistant response (truncated):"
grep '"type":"assistant"' "$LOG_FILE" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo "  (could not extract)"

echo ""
echo "Full log: $LOG_FILE"
echo "Timestamp: $TIMESTAMP"

if [ "$TRIGGERED" = "true" ]; then
    exit 0
else
    exit 1
fi
tests/explicit-skill-requests/run-multiturn-test.sh 144 řádků
#!/usr/bin/env bash
# Test explicit skill requests in multi-turn conversations
# Usage: ./run-multiturn-test.sh
#
# This test builds actual conversation history to reproduce the failure mode
# where Claude skips skill invocation after extended conversation

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/multiturn"
mkdir -p "$OUTPUT_DIR"

# Create project directory (conversation is cwd-based)
PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"

echo "=== Multi-Turn Explicit Skill Request Test ==="
echo "Output dir: $OUTPUT_DIR"
echo "Project dir: $PROJECT_DIR"
echo "Plugin dir: $PLUGIN_DIR"
echo ""

cd "$PROJECT_DIR"

# Create a dummy plan file
cat > "$PROJECT_DIR/docs/superpowers/plans/auth-system.md" << 'EOF'
# Auth System Implementation Plan

## Task 1: Add User Model
Create user model with email and password fields.

## Task 2: Add Auth Routes
Create login and register endpoints.

## Task 3: Add JWT Middleware
Protect routes with JWT validation.

## Task 4: Write Tests
Add comprehensive test coverage.
EOF

# Turn 1: Start a planning conversation
echo ">>> Turn 1: Starting planning conversation..."
TURN1_LOG="$OUTPUT_DIR/turn1.json"
claude -p "I need to implement an authentication system. Let's plan this out. The requirements are: user registration with email/password, JWT tokens, and protected routes." \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 2 \
    --output-format stream-json \
    > "$TURN1_LOG" 2>&1 || true

echo "Turn 1 complete."
echo ""

# Turn 2: Continue with more planning detail
echo ">>> Turn 2: Continuing planning..."
TURN2_LOG="$OUTPUT_DIR/turn2.json"
claude -p "Good analysis. I've already written the plan to docs/superpowers/plans/auth-system.md. Now I'm ready to implement. What are my options for execution?" \
    --continue \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 2 \
    --output-format stream-json \
    > "$TURN2_LOG" 2>&1 || true

echo "Turn 2 complete."
echo ""

# Turn 3: The critical test - ask for subagent-driven-development
echo ">>> Turn 3: Requesting subagent-driven-development..."
TURN3_LOG="$OUTPUT_DIR/turn3.json"
claude -p "subagent-driven-development, please" \
    --continue \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 2 \
    --output-format stream-json \
    > "$TURN3_LOG" 2>&1 || true

echo "Turn 3 complete."
echo ""

echo "=== Results ==="

# Check if skill was triggered in Turn 3
SKILL_PATTERN='"skill":"([^"]*:)?subagent-driven-development"'
if grep -q '"name":"Skill"' "$TURN3_LOG" && grep -qE "$SKILL_PATTERN" "$TURN3_LOG"; then
    echo "PASS: Skill 'subagent-driven-development' was triggered in Turn 3"
    TRIGGERED=true
else
    echo "FAIL: Skill 'subagent-driven-development' was NOT triggered in Turn 3"
    TRIGGERED=false
fi

# Show what skills were triggered
echo ""
echo "Skills triggered in Turn 3:"
grep -o '"skill":"[^"]*"' "$TURN3_LOG" 2>/dev/null | sort -u || echo "  (none)"

# Check for premature action in Turn 3
echo ""
echo "Checking for premature action in Turn 3..."
FIRST_SKILL_LINE=$(grep -n '"name":"Skill"' "$TURN3_LOG" | head -1 | cut -d: -f1)
if [ -n "$FIRST_SKILL_LINE" ]; then
    PREMATURE_TOOLS=$(head -n "$FIRST_SKILL_LINE" "$TURN3_LOG" | \
        grep '"type":"tool_use"' | \
        grep -v '"name":"Skill"' | \
        grep -vE '"name":"(TodoWrite|TaskCreate|TaskUpdate|TaskList|TaskGet)"' || true)
    if [ -n "$PREMATURE_TOOLS" ]; then
        echo "WARNING: Tools invoked BEFORE Skill tool in Turn 3:"
        echo "$PREMATURE_TOOLS" | head -5
    else
        echo "OK: No premature tool invocations detected"
    fi
else
    echo "WARNING: No Skill invocation found in Turn 3"
    # Show what WAS invoked
    echo ""
    echo "Tools invoked in Turn 3:"
    grep '"type":"tool_use"' "$TURN3_LOG" | grep -o '"name":"[^"]*"' | head -10 || echo "  (none)"
fi

# Show Turn 3 assistant response
echo ""
echo "Turn 3 first assistant response (truncated):"
grep '"type":"assistant"' "$TURN3_LOG" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo "  (could not extract)"

echo ""
echo "Logs:"
echo "  Turn 1: $TURN1_LOG"
echo "  Turn 2: $TURN2_LOG"
echo "  Turn 3: $TURN3_LOG"
echo "Timestamp: $TIMESTAMP"

if [ "$TRIGGERED" = "true" ]; then
    exit 0
else
    exit 1
fi
tests/explicit-skill-requests/run-extended-multiturn-test.sh 114 řádků
#!/usr/bin/env bash
# Extended multi-turn test with more conversation history
# This tries to reproduce the failure by building more context

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/extended-multiturn"
mkdir -p "$OUTPUT_DIR"

PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"

echo "=== Extended Multi-Turn Test ==="
echo "Output dir: $OUTPUT_DIR"
echo "Plugin dir: $PLUGIN_DIR"
echo ""

cd "$PROJECT_DIR"

# Turn 1: Start brainstorming
echo ">>> Turn 1: Brainstorming request..."
claude -p "I want to add user authentication to my app. Help me think through this." \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 3 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn1.json" 2>&1 || true
echo "Done."

# Turn 2: Answer a brainstorming question
echo ">>> Turn 2: Answering questions..."
claude -p "Let's use JWT tokens with 24-hour expiry. Email/password registration." \
    --continue \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 3 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn2.json" 2>&1 || true
echo "Done."

# Turn 3: Ask to write a plan
echo ">>> Turn 3: Requesting plan..."
claude -p "Great, write this up as an implementation plan." \
    --continue \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 3 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn3.json" 2>&1 || true
echo "Done."

# Turn 4: Confirm plan looks good
echo ">>> Turn 4: Confirming plan..."
claude -p "The plan looks good. What are my options for executing it?" \
    --continue \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 2 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn4.json" 2>&1 || true
echo "Done."

# Turn 5: THE CRITICAL TEST
echo ">>> Turn 5: Requesting subagent-driven-development..."
FINAL_LOG="$OUTPUT_DIR/turn5.json"
claude -p "subagent-driven-development, please" \
    --continue \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 2 \
    --output-format stream-json \
    > "$FINAL_LOG" 2>&1 || true
echo "Done."
echo ""

echo "=== Results ==="

# Check final turn
SKILL_PATTERN='"skill":"([^"]*:)?subagent-driven-development"'
if grep -q '"name":"Skill"' "$FINAL_LOG" && grep -qE "$SKILL_PATTERN" "$FINAL_LOG"; then
    echo "PASS: Skill was triggered"
    TRIGGERED=true
else
    echo "FAIL: Skill was NOT triggered"
    TRIGGERED=false

    # Show what was invoked instead
    echo ""
    echo "Tools invoked in final turn:"
    grep '"type":"tool_use"' "$FINAL_LOG" | jq -r '.content[] | select(.type=="tool_use") | .name' 2>/dev/null | head -10 || \
    grep -o '"name":"[^"]*"' "$FINAL_LOG" | head -10 || echo "  (none found)"
fi

echo ""
echo "Skills triggered:"
grep -o '"skill":"[^"]*"' "$FINAL_LOG" 2>/dev/null | sort -u || echo "  (none)"

echo ""
echo "Final turn response (first 500 chars):"
grep '"type":"assistant"' "$FINAL_LOG" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo "  (could not extract)"

echo ""
echo "Logs in: $OUTPUT_DIR"

if [ "$TRIGGERED" = "true" ]; then
    exit 0
else
    exit 1
fi
tests/explicit-skill-requests/run-haiku-test.sh 145 řádků
#!/usr/bin/env bash
# Test with haiku model and user's CLAUDE.md
# This tests whether a cheaper/faster model fails more easily

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

TIMESTAMP=$(date +%s)
OUTPUT_DIR="/tmp/superpowers-tests/${TIMESTAMP}/explicit-skill-requests/haiku"
mkdir -p "$OUTPUT_DIR"

PROJECT_DIR="$OUTPUT_DIR/project"
mkdir -p "$PROJECT_DIR/docs/superpowers/plans"
mkdir -p "$PROJECT_DIR/.claude"

echo "=== Haiku Model Test with User CLAUDE.md ==="
echo "Output dir: $OUTPUT_DIR"
echo "Plugin dir: $PLUGIN_DIR"
echo ""

cd "$PROJECT_DIR"

# Copy user's CLAUDE.md to simulate real environment
if [ -f "$HOME/.claude/CLAUDE.md" ]; then
    cp "$HOME/.claude/CLAUDE.md" "$PROJECT_DIR/.claude/CLAUDE.md"
    echo "Copied user CLAUDE.md"
else
    echo "No user CLAUDE.md found, proceeding without"
fi

# Create a dummy plan file
cat > "$PROJECT_DIR/docs/superpowers/plans/auth-system.md" << 'EOF'
# Auth System Implementation Plan

## Task 1: Add User Model
Create user model with email and password fields.

## Task 2: Add Auth Routes
Create login and register endpoints.

## Task 3: Add JWT Middleware
Protect routes with JWT validation.

## Task 4: Write Tests
Add comprehensive test coverage.
EOF

echo ""

# Turn 1: Start brainstorming
echo ">>> Turn 1: Brainstorming request..."
claude -p "I want to add user authentication to my app. Help me think through this." \
    --model haiku \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 3 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn1.json" 2>&1 || true
echo "Done."

# Turn 2: Answer questions
echo ">>> Turn 2: Answering questions..."
claude -p "Let's use JWT tokens with 24-hour expiry. Email/password registration." \
    --continue \
    --model haiku \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 3 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn2.json" 2>&1 || true
echo "Done."

# Turn 3: Ask to write a plan
echo ">>> Turn 3: Requesting plan..."
claude -p "Great, write this up as an implementation plan." \
    --continue \
    --model haiku \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 3 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn3.json" 2>&1 || true
echo "Done."

# Turn 4: Confirm plan looks good
echo ">>> Turn 4: Confirming plan..."
claude -p "The plan looks good. What are my options for executing it?" \
    --continue \
    --model haiku \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 2 \
    --output-format stream-json \
    > "$OUTPUT_DIR/turn4.json" 2>&1 || true
echo "Done."

# Turn 5: THE CRITICAL TEST
echo ">>> Turn 5: Requesting subagent-driven-development..."
FINAL_LOG="$OUTPUT_DIR/turn5.json"
claude -p "subagent-driven-development, please" \
    --continue \
    --model haiku \
    --plugin-dir "$PLUGIN_DIR" \
    --dangerously-skip-permissions \
    --max-turns 2 \
    --output-format stream-json \
    > "$FINAL_LOG" 2>&1 || true
echo "Done."
echo ""

echo "=== Results (Haiku) ==="

# Check final turn
SKILL_PATTERN='"skill":"([^"]*:)?subagent-driven-development"'
if grep -q '"name":"Skill"' "$FINAL_LOG" && grep -qE "$SKILL_PATTERN" "$FINAL_LOG"; then
    echo "PASS: Skill was triggered"
    TRIGGERED=true
else
    echo "FAIL: Skill was NOT triggered"
    TRIGGERED=false

    echo ""
    echo "Tools invoked in final turn:"
    grep '"type":"tool_use"' "$FINAL_LOG" | grep -o '"name":"[^"]*"' | head -10 || echo "  (none)"
fi

echo ""
echo "Skills triggered:"
grep -o '"skill":"[^"]*"' "$FINAL_LOG" 2>/dev/null | sort -u || echo "  (none)"

echo ""
echo "Final turn response (first 500 chars):"
grep '"type":"assistant"' "$FINAL_LOG" | head -1 | jq -r '.message.content[0].text // .message.content' 2>/dev/null | head -c 500 || echo "  (could not extract)"

echo ""
echo "Logs in: $OUTPUT_DIR"

if [ "$TRIGGERED" = "true" ]; then
    exit 0
else
    exit 1
fi

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč se používá izolovaný HOME?

Uživatelovo ~/.claude, CLAUDE.md a pluginy by ovlivnily výsledek. V izolaci agent vidí jen testovaný plugin a test je reprodukovatelný na libovolném stroji.

2. Proč existuje multiturn test?

Selhání se často objeví až po dlouhé konverzaci, kdy agent ztratí pozornost a skill přeskočí. Jednokolový test by ho nezachytil. Skutečná historie reprodukuje reálné podmínky.

3. Proč se testuje i s modelem haiku?

Levnější model má menší kapacitu a snáze pravidla ignoruje. Pokud i on skill použije, je pravidlo robustní. Je to záměrně přísnější zkouška.

4. Proč se do testovacího projektu zapisuje ukázkový plán?

Prompty odkazují na docs/superpowers/plans/auth-system.md. Soubor musí existovat, jinak by agent řešil chybějící soubor místo vyvolání skillu.

5. K čemu je `--max-turns`?

Omezuje délku běhu. Test potřebuje jen vidět, zda se skill vyvolal na začátku; nesmí běžet donekonečna a stát tokeny.

6. Proč `--output-format stream-json`?

Každá událost (včetně volání nástrojů) je samostatný JSON řádek. Skript v nich může spolehlivě hledat volání nástroje Skill, místo aby parsoval text.

7. Proč `timeout 300`?

Test, který visí, by zablokoval celou sadu. Pevný limit zaručí konec.

8. Proč `--dangerously-skip-permissions` v testu?

Headless běh nemá kdo schvalovat oprávnění. Probíhá v izolovaném dočasném projektu, takže riziko je omezené.

9. Proč se spouští `claude` s `--plugin-dir`?

Načte plugin přímo z lokálního repozitáře, takže se testuje právě aktuální kód, ne nainstalovaná verze.

Slovník pojmů (9)

Runner

Skript, který spouští jeden nebo více testovacích scénářů.

Multi-turn test

Test s historií více výměn před hlavním promptem.

Isolated HOME

Dočasný domovský adresář bez uživatelských nastavení.

`--plugin-dir`

Přepínač načítající plugin z adresáře.

`--max-turns`

Limit počtu kol agenta.

`stream-json`

Výstup po událostech jako JSON řádky.

Skill tool call

Událost, kterou test hledá jako důkaz vyvolání skillu.

Haiku model

Levnější model; slabší test odolnosti pravidla.

Plan fixture

Ukázkový plán auth-system.md.

↑ nahoru

Testy Hermes pluginu (pytest)

Pytest testy bootstrapu a registrace skills v Hermes pluginu: frontmatter, marker, první turn a layouty instalace.

Hermes plugin (.hermes-plugin) je napsaný v Pythonu, proto má testy v pytestu. test_bootstrap.py kontroluje sestavení bootstrap kontextu: odstranění YAML frontmatteru (včetně případu bez něj a ořezání mezer), rozlišení layoutu repozitáře, marker superpowers:using-superpowers bootstrap for hermes s obalem, přítomnost těla skillu using-superpowers, mapování nástrojů načtené z referenčního souboru, pokyn k skill_view a limit velikosti pro Hermes context spill.

test_plugin.py ověřuje register: připojí pouze hook pre_llm_call, zaregistruje každý stock skill jako cestu, registrované skills odpovídají adresářům, první turn vrátí bootstrap kontext a další turny None, hook toleruje budoucí kwargs, rozpozná layout klonu i plochý layout, při chybějícím skills/ selže hlasitě a popisy skills odpovídají frontmatteru. conftest.py poskytuje fixture mock_ctx.

Zdrojový kód

tests/hermes/conftest.py 33 řádků
from pathlib import Path

import pytest
from unittest.mock import MagicMock


@pytest.fixture
def mock_ctx():
    ctx = MagicMock()
    ctx._hooks = {}
    ctx._skills = {}
    ctx._descriptions = {}

    def register_hook(event, fn):
        ctx._hooks[event] = fn

    def register_skill(name, path, description="", frontmatter=None):
        # Mimic hermes' real register_skill, which calls path.exists() and
        # therefore breaks on a str (the bug that silently disabled the whole
        # plugin, found 2026-07-23). Keeping that fidelity here means a
        # regression to str paths fails these tests instead of failing
        # silently inside hermes.
        if not isinstance(path, Path):
            raise AttributeError(
                f"register_skill requires a pathlib.Path, got {type(path).__name__}"
            )
        ctx._skills[name] = path
        ctx._descriptions[name] = description

    ctx.register_hook.side_effect = register_hook
    ctx.register_skill.side_effect = register_skill
    return ctx
tests/hermes/test_bootstrap.py 99 řádků
import importlib
import os
import sys

import pytest

sys.path.insert(0, os.path.abspath(
    os.path.join(os.path.dirname(__file__), "../../.hermes-plugin")
))

BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes"

# Hermes spills injected context over 10,000 chars to a file, which breaks
# inline injection semantics. The bootstrap must stay under it with margin.
HERMES_CONTEXT_SPILL_LIMIT = 10_000


def _load():
    if "__init__" in sys.modules:
        del sys.modules["__init__"]
    return importlib.import_module("__init__")


def _bootstrap():
    m = _load()
    return m._build_bootstrap(m._skills_dir())


class TestStripFrontmatter:
    def test_strips_yaml_block(self):
        m = _load()
        content = "---\nname: foo\ndescription: bar\n---\n# Body\nContent here"
        assert m._strip_frontmatter(content) == "# Body\nContent here"

    def test_no_frontmatter_returns_trimmed_content(self):
        m = _load()
        content = "# No frontmatter\nJust content"
        assert m._strip_frontmatter(content) == "# No frontmatter\nJust content"

    def test_strips_surrounding_whitespace_from_body(self):
        m = _load()
        content = "---\nname: foo\n---\n\n\n# Body\n\n"
        assert m._strip_frontmatter(content) == "# Body"


class TestSkillsDirResolution:
    def test_repo_layout_resolves(self):
        # The repo checkout IS the git-clone layout: .hermes-plugin/ and
        # skills/ are siblings, so resolution must succeed from here.
        m = _load()
        skills = m._skills_dir()
        assert os.path.isfile(
            os.path.join(skills, "using-superpowers", "SKILL.md")
        )


class TestBootstrapContent:
    def test_marker_and_wrapper(self):
        content = _bootstrap()
        assert BOOTSTRAP_MARKER in content
        assert content.startswith("<EXTREMELY_IMPORTANT>")
        assert content.rstrip().endswith("</EXTREMELY_IMPORTANT>")

    def test_contains_using_superpowers_body(self):
        content = _bootstrap()
        # A distinctive line from the skill body proves the real SKILL.md was
        # embedded, not a stub.
        assert "You have superpowers" in content
        assert "## The Rule" in content

    def test_frontmatter_stripped(self):
        content = _bootstrap()
        assert "---\nname:" not in content

    def test_tool_mapping_sourced_from_reference_file(self):
        m = _load()
        content = _bootstrap()
        ref = os.path.join(
            m._skills_dir(), "using-superpowers", "references", "hermes-tools.md"
        )
        with open(ref, encoding="utf-8") as f:
            ref_text = f.read().strip()
        # The mapping is included verbatim from the reference file — the
        # single source, not a drift-prone inline copy.
        assert ref_text in content
        assert "read_file" in content

    def test_skill_view_guidance_present(self):
        content = _bootstrap()
        assert 'skill_view("superpowers:brainstorming")' in content

    def test_under_hermes_context_spill_limit(self):
        content = _bootstrap()
        assert len(content) < HERMES_CONTEXT_SPILL_LIMIT, (
            f"bootstrap is {len(content)} chars; hermes spills injected "
            f"context over {HERMES_CONTEXT_SPILL_LIMIT} to a file, which "
            "breaks inline injection"
        )
tests/hermes/test_plugin.py 179 řádků
import importlib
import importlib.util
import os
import re
import shutil
import sys
from pathlib import Path

import pytest

# Point at the plugin directory
_PLUGIN_DIR = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "../../.hermes-plugin")
)
sys.path.insert(0, _PLUGIN_DIR)

BOOTSTRAP_MARKER = "superpowers:using-superpowers bootstrap for hermes"


def _load_plugin():
    """Re-import plugin module fresh."""
    if "__init__" in sys.modules:
        del sys.modules["__init__"]
    return importlib.import_module("__init__")


def _fire_pre_llm(ctx, **kwargs):
    hook = ctx._hooks["pre_llm_call"]
    defaults = {
        "session_id": "s1",
        "user_message": "hi",
        "conversation_history": [],
        "is_first_turn": False,
        "model": "test-model",
        "platform": "cli",
    }
    defaults.update(kwargs)
    return hook(**defaults)


class TestPluginRegistration:
    def test_register_attaches_only_pre_llm_call_hook(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        assert list(mock_ctx._hooks.keys()) == ["pre_llm_call"]

    def test_register_registers_every_stock_skill_as_path(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        # The conftest mock raises on non-Path (mirroring hermes' real
        # register_skill), so reaching these asserts proves every
        # registration passed a pathlib.Path.
        assert "using-superpowers" in mock_ctx._skills
        assert "brainstorming" in mock_ctx._skills
        for name, path in mock_ctx._skills.items():
            assert isinstance(path, Path)
            assert path.name == "SKILL.md"
            assert path.parent.name == name
            assert path.is_file()

    def test_registered_skills_match_skill_directories(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        skills_root = plugin._skills_dir()
        expected = {
            entry
            for entry in os.listdir(skills_root)
            if os.path.isfile(os.path.join(skills_root, entry, "SKILL.md"))
        }
        assert set(mock_ctx._skills.keys()) == expected


class TestBootstrapInjection:
    def test_first_turn_returns_bootstrap_context(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        result = _fire_pre_llm(mock_ctx, is_first_turn=True)
        assert isinstance(result, dict)
        content = result["context"]
        assert BOOTSTRAP_MARKER in content
        assert content.startswith("<EXTREMELY_IMPORTANT>")
        assert content.rstrip().endswith("</EXTREMELY_IMPORTANT>")

    def test_later_turns_return_none(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        assert _fire_pre_llm(mock_ctx, is_first_turn=False) is None
        assert _fire_pre_llm(mock_ctx, is_first_turn=None) is None

    def test_hook_tolerates_future_kwargs(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        result = _fire_pre_llm(
            mock_ctx, is_first_turn=True, telemetry_schema_version=3
        )
        assert BOOTSTRAP_MARKER in result["context"]


class TestLayoutResolution:
    def _stage(self, tmp_path, layout):
        """Copy the plugin module + a minimal skills tree in the given layout."""
        src_skills = Path(_PLUGIN_DIR).parent / "skills"
        if layout == "clone":
            plugdir = tmp_path / "superpowers" / ".hermes-plugin"
        else:  # flat: module at the plugin dir root, skills nested inside it
            plugdir = tmp_path / "superpowers"
        skills = tmp_path / "superpowers" / "skills"
        plugdir.mkdir(parents=True, exist_ok=True)
        shutil.copy(Path(_PLUGIN_DIR) / "__init__.py", plugdir / "__init__.py")
        for skill in ("using-superpowers", "brainstorming"):
            shutil.copytree(src_skills / skill, skills / skill)
        return plugdir

    def _load_from(self, plugdir):
        spec = importlib.util.spec_from_file_location(
            f"hermes_plugin_test_{plugdir.parent.name}_{plugdir.name}",
            plugdir / "__init__.py",
        )
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        return mod

    def test_clone_layout_resolves_sibling_skills(self, tmp_path, mock_ctx):
        # git-clone install: .hermes-plugin/ and skills/ are siblings.
        plugdir = self._stage(tmp_path, "clone")
        mod = self._load_from(plugdir)
        mod.register(mock_ctx)
        assert "using-superpowers" in mock_ctx._skills

    def test_flat_layout_resolves_nested_skills(self, tmp_path, mock_ctx):
        # flattened install: module at the plugin dir root, skills/ inside it.
        plugdir = self._stage(tmp_path, "flat")
        mod = self._load_from(plugdir)
        mod.register(mock_ctx)
        assert "using-superpowers" in mock_ctx._skills

    def test_missing_skills_raises_loudly(self, tmp_path, mock_ctx):
        plugdir = tmp_path / "superpowers"
        plugdir.mkdir(parents=True)
        shutil.copy(Path(_PLUGIN_DIR) / "__init__.py", plugdir / "__init__.py")
        mod = self._load_from(plugdir)
        with pytest.raises(RuntimeError, match="cannot find the skills"):
            mod.register(mock_ctx)


class TestSkillDescriptions:
    """Hermes builds its skill catalogue from register_skill(description=...),
    which defaults to "". Registering the path alone left every stock skill
    blank in that catalogue, so the model had nothing to select on."""

    def test_every_stock_skill_registers_a_description(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        assert set(mock_ctx._descriptions) == set(mock_ctx._skills)
        blank = sorted(n for n, d in mock_ctx._descriptions.items() if not d.strip())
        assert blank == [], f"registered without a description: {blank}"

    def test_descriptions_match_the_skill_frontmatter(self, mock_ctx):
        plugin = _load_plugin()
        plugin.register(mock_ctx)
        skills_dir = Path(plugin._skills_dir())
        for name, description in mock_ctx._descriptions.items():
            text = (skills_dir / name / "SKILL.md").read_text(encoding="utf-8")
            declared = re.search(r"^description:\s*(.+)$", text, re.M).group(1)
            assert description == declared.strip().strip('"').strip("'")

    @pytest.mark.parametrize(
        "block, expected",
        [
            ('---\nname: demo\ndescription: "Quoted value."\n---\nbody', "Quoted value."),
            ("---\nname: demo\ndescription: Bare value\n---\nbody", "Bare value"),
            ("---\nname: demo\n---\nbody", ""),
            ("no frontmatter at all", ""),
        ],
    )
    def test_frontmatter_value_parsing(self, block, expected):
        plugin = _load_plugin()
        assert plugin._frontmatter_value(block, "description") == expected
tests/hermes/__init__.py 1 řádků

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč první turn dostane bootstrap a další `None`?

Bootstrap (instrukce používat skills) stačí vložit jednou. Opakování v každém turnu by zbytečně nafukovalo kontext a stálo tokeny.

2. Proč plugin registruje jen hook `pre_llm_call`?

Minimalismus: čím méně hooků, tím menší povrch pro chyby a konflikty s jiným kódem Hermesu. Test výslovně hlídá, že žádný jiný hook není připojen.

3. K čemu je test limitu context spill?

Hermes má omezení délky injektovaného kontextu. Pokud by bootstrap přerostl limit, přetekl by (spill) nebo se useknul. Test zajišťuje, že zůstane pod limitem.

4. Proč test „missing skills raises loudly“?

Plugin bez skills je nefunkční. Tichý start by uživateli nic neřekl a agent by postrádal skills bez vysvětlení. Hlasitá chyba je diagnostická.

5. Proč se testují dva layouty (clone a flat)?

Plugin se může instalovat jako klon repozitáře nebo jako plochá kopie. V obou případech musí najít skills.

6. Proč hook toleruje budoucí kwargs?

Hermes může přidat nové parametry. Hook s pevnou signaturou by se rozbil; tolerance zaručuje dopřednou kompatibilitu.

7. Proč se kontroluje, že popisy odpovídají frontmatteru?

Hermes zobrazuje popisy agentovi, který podle nich rozhoduje o použití skillu. Zastaralý popis by vedl k chybným spouštěčům.

8. Co dělá odstranění YAML frontmatteru?

Bootstrap vkládá tělo skillu. Frontmatter (metadata) by v kontextu byl šum. Test pokrývá i skill bez frontmatteru a ořezání bílých znaků.

Slovník pojmů (10)

pytest

Testovací framework pro Python.

Fixture (`mock_ctx`)

Připravený testovací objekt (falešný kontext Hermesu).

`pre_llm_call`

Hook volaný před každým voláním modelu.

Bootstrap context

Text s pokyny using-superpowers vložený do první zprávy.

Marker

Značka superpowers:using-superpowers bootstrap for hermes, podle které se bootstrap pozná.

Context spill limit

Hranice velikosti injektovaného kontextu v Hermesu.

Frontmatter

YAML blok na začátku SKILL.md.

`skill_view`

Nástroj Hermesu pro zobrazení skillu.

Clone layout / flat layout

Dvě podoby instalace, které plugin rozpozná.

Fail loudly

Chyba je viditelná, ne tichá.

↑ nahoru

Testy hooků: session-start a Windows wrapper

Testy hooku session-start (JSON výstup, registrace hooks.json) a hledání bash ve wrapperu run-hook.cmd na Windows.

Hook session-start vkládá bootstrap superpowers na začátku session a run-hook.cmd je polyglot wrapper (cmd + bash), který hook spustí i na Windows. test-session-start.sh ověřuje, že hooks.json registruje SessionStart s dispatchem přes shell: bash, že hook produkuje validní JSON a že při dostupném cat na PATH JSON přes něj proteče; testy běží v dočasném adresáři s upravenou PATH, aby šlo simulovat chybějící nástroje.

test-run-hook-cmd-windows.sh pokrývá cmd polovinu wrapperu: jak najde bash a zda přežije exit kód hooku. Běží v Git Bash na Windows a jinde se přeskočí (SKIP). Případy: exit kód propaguje, najde se per-user instalace Gitu, System32\bash.exe (WSL launcher) se přeskočí ve prospěch Git bash, bash pod WindowsApps (Store stub) se přeskočí, bash.exe v aktuálním adresáři se nespustí (ochrana před spuštěním podstrčeného binárku), nenastavená SystemRoot/LOCALAPPDATA nespustí cizí cestu a při žádném použitelném bashi skript skončí s 0 bez výstupu.

Zdrojový kód

tests/hooks/test-session-start.sh 326 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
HOOK_UNDER_TEST="$REPO_ROOT/hooks/session-start"
WRAPPER_UNDER_TEST="$REPO_ROOT/hooks/run-hook.cmd"

FAILURES=0
TEST_ROOT="$(mktemp -d)"

cleanup() {
    rm -rf "$TEST_ROOT"
}
trap cleanup EXIT

pass() {
    echo "  [PASS] $1"
}

fail() {
    echo "  [FAIL] $1"
    FAILURES=$((FAILURES + 1))
}

make_home() {
    local name="$1"
    local home="$TEST_ROOT/$name/home"
    mkdir -p "$home"
    printf '%s\n' "$home"
}

assert_command_output() {
    local description="$1"
    local shape="$2"
    local contains="$3"
    local not_contains="$4"
    local home="$5"
    shift 5

    local output
    if ! output="$(env -i PATH="${PATH:-}" HOME="$home" "$@" 2>&1)"; then
        fail "$description"
        echo "    hook exited non-zero"
        echo "$output" | sed 's/^/      /'
        return
    fi

    if printf '%s' "$output" | \
        EXPECT_SHAPE="$shape" \
        EXPECT_CONTAINS="$contains" \
        EXPECT_NOT_CONTAINS="$not_contains" \
        node -e '
const fs = require("fs");

const input = fs.readFileSync(0, "utf8");
let payload;
try {
  payload = JSON.parse(input);
} catch (error) {
  console.error(`invalid JSON: ${error.message}`);
  process.exit(1);
}

function hasOwn(object, key) {
  return Object.prototype.hasOwnProperty.call(object, key);
}

function fail(message) {
  console.error(message);
  process.exit(1);
}

const shape = process.env.EXPECT_SHAPE;
let context;

if (shape === "nested") {
  if (!hasOwn(payload, "hookSpecificOutput")) {
    fail("missing hookSpecificOutput");
  }
  if (hasOwn(payload, "additional_context") || hasOwn(payload, "additionalContext")) {
    fail("nested output also included a top-level context field");
  }
  const hookOutput = payload.hookSpecificOutput;
  if (!hookOutput || typeof hookOutput !== "object" || Array.isArray(hookOutput)) {
    fail("hookSpecificOutput is not an object");
  }
  if (hookOutput.hookEventName !== "SessionStart") {
    fail(`unexpected hookEventName: ${hookOutput.hookEventName}`);
  }
  context = hookOutput.additionalContext;
} else if (shape === "cursor") {
  if (hasOwn(payload, "hookSpecificOutput")) {
    fail("cursor output included hookSpecificOutput");
  }
  if (!hasOwn(payload, "additional_context")) {
    fail("cursor output missing additional_context");
  }
  if (hasOwn(payload, "additionalContext")) {
    fail("cursor output included additionalContext");
  }
  context = payload.additional_context;
} else if (shape === "sdk") {
  if (hasOwn(payload, "hookSpecificOutput")) {
    fail("sdk output included hookSpecificOutput");
  }
  if (!hasOwn(payload, "additionalContext")) {
    fail("sdk output missing additionalContext");
  }
  if (hasOwn(payload, "additional_context")) {
    fail("sdk output included additional_context");
  }
  context = payload.additionalContext;
} else {
  fail(`unknown expected shape: ${shape}`);
}

if (typeof context !== "string" || context.trim() === "") {
  fail("injected context was empty");
}

const expectedText = process.env.EXPECT_CONTAINS || "";
if (expectedText && !context.includes(expectedText)) {
  fail(`context did not contain expected text: ${expectedText}`);
}

const forbiddenTexts = (process.env.EXPECT_NOT_CONTAINS || "")
  .split("\u001f")
  .filter(Boolean);
for (const forbiddenText of forbiddenTexts) {
  if (context.includes(forbiddenText)) {
    fail(`context contained forbidden text: ${forbiddenText}`);
  }
}
'; then
        pass "$description"
    else
        fail "$description"
        echo "    output:"
        echo "$output" | sed 's/^/      /'
    fi
}

echo "SessionStart hook output tests"

# Registration shape: the hook must declare shell:"bash" so Claude Code on
# Windows dispatches via Git Bash (or fails with an actionable error) instead
# of PowerShell/cmd.exe, whose parsers break on the quoted command string
# (PowerShell ParserError; cmd.exe quote-stripping on paths with metacharacters).
if node -e '
const hooks = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"));
const entry = hooks.hooks.SessionStart[0].hooks[0];
if (entry.shell !== "bash") {
  console.error(`SessionStart hook shell is ${JSON.stringify(entry.shell)}, expected "bash"`);
  process.exit(1);
}
if (!/run-hook\.cmd" session-start$/.test(entry.command)) {
  console.error(`unexpected SessionStart command shape: ${entry.command}`);
  process.exit(1);
}
' "$REPO_ROOT/hooks/hooks.json"; then
    pass "hooks.json registers SessionStart with shell:bash dispatch"
else
    fail "hooks.json registers SessionStart with shell:bash dispatch"
fi

claude_home="$(make_home claude-code)"
assert_command_output \
    "Claude Code emits nested SessionStart additionalContext" \
    "nested" \
    "" \
    "" \
    "$claude_home" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    bash "$HOOK_UNDER_TEST"

wrapper_home="$(make_home run-hook-wrapper)"
assert_command_output \
    "run-hook.cmd wrapper dispatches to the named session-start script" \
    "nested" \
    "" \
    "" \
    "$wrapper_home" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    bash "$WRAPPER_UNDER_TEST" session-start

cursor_home="$(make_home cursor)"
assert_command_output \
    "Cursor emits top-level additional_context only" \
    "cursor" \
    "" \
    "" \
    "$cursor_home" \
    CURSOR_PLUGIN_ROOT="$REPO_ROOT" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    bash "$HOOK_UNDER_TEST"

copilot_home="$(make_home copilot-cli)"
assert_command_output \
    "Copilot CLI emits top-level additionalContext only" \
    "sdk" \
    "" \
    "" \
    "$copilot_home" \
    COPILOT_CLI=1 \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    bash "$HOOK_UNDER_TEST"

legacy_home="$(make_home legacy-warning-removed)"
mkdir -p "$legacy_home/.config/superpowers/skills"
assert_command_output \
    "SessionStart omits obsolete legacy custom-skill warning" \
    "nested" \
    "" \
    "Superpowers now uses"$'\037'"~/.config/superpowers/skills"$'\037'"~/.claude/skills"$'\037'"legacy" \
    "$legacy_home" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    bash "$HOOK_UNDER_TEST"

# Regression for #2310: Claude Code can spawn SessionStart:startup hooks with
# a broken/empty PATH (anthropics/claude-code#43127). session-start and
# run-hook.cmd's Unix half both shell out to external binaries (dirname, cat)
# that an empty PATH cannot resolve, even though bash itself was invoked by
# absolute path. Every call here should use bash's own builtins/redirection
# instead, so an empty PATH must not change the result.
bash_bin="$(command -v bash)"

broken_path_home="$(make_home broken-path)"
assert_command_output \
    "session-start with empty PATH still emits nested additionalContext" \
    "nested" \
    "" \
    "" \
    "$broken_path_home" \
    PATH="" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    "$bash_bin" "$HOOK_UNDER_TEST"

broken_path_wrapper_home="$(make_home broken-path-wrapper)"
assert_command_output \
    "run-hook.cmd with empty PATH still dispatches session-start" \
    "nested" \
    "" \
    "" \
    "$broken_path_wrapper_home" \
    PATH="" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    "$bash_bin" "$WRAPPER_UNDER_TEST" session-start

# Run by bare filename from inside hooks/ ($0 has no slash), the plugin root
# must still resolve.
bare_name_home="$(make_home bare-name)"
assert_command_output \
    "session-start run by bare filename from hooks/ still emits nested additionalContext" \
    "nested" \
    "" \
    "" \
    "$bare_name_home" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    "$bash_bin" -c 'cd "$1" && exec "$2" session-start' _ "$REPO_ROOT/hooks" "$bash_bin"

bare_name_wrapper_home="$(make_home bare-name-wrapper)"
assert_command_output \
    "run-hook.cmd run by bare filename from hooks/ still dispatches session-start" \
    "nested" \
    "" \
    "" \
    "$bare_name_wrapper_home" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    "$bash_bin" -c 'cd "$1" && exec "$2" run-hook.cmd session-start' _ "$REPO_ROOT/hooks" "$bash_bin"

# run-hook.cmd's Windows half starts bash with a backslash path
# (C:\...\hooks\session-start), so $0 can use \ as its separator. The skill
# must still be found. On Windows use the real Windows path; elsewhere build
# a plugin root whose hook is reached through a name containing a backslash.
backslash_home="$(make_home backslash)"
if command -v cygpath >/dev/null 2>&1; then
    backslash_cwd="$REPO_ROOT"
    backslash_hook="$(cygpath -w "$HOOK_UNDER_TEST")"
else
    backslash_cwd="$TEST_ROOT/backslash/root"
    mkdir -p "$backslash_cwd"
    ln -s "$REPO_ROOT/hooks" "$backslash_cwd/hooks"
    ln -s "$REPO_ROOT/skills" "$backslash_cwd/skills"
    ln -s "$REPO_ROOT/hooks/session-start" "$backslash_cwd/hooks\\session-start"
    backslash_hook='hooks\session-start'
fi
assert_command_output \
    "session-start reached through a backslash path still reads the skill" \
    "nested" \
    "" \
    "Error reading using-superpowers skill" \
    "$backslash_home" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    "$bash_bin" -c 'cd "$1" && exec "$2" "$3"' _ "$backslash_cwd" "$bash_bin" "$backslash_hook"

# When cat is on PATH, the JSON must still go through it: the pipe absorbs
# EPIPE on Windows + Git Bash (#1612). The stub records that it ran.
cat_stub_dir="$TEST_ROOT/cat-stub/bin"
cat_marker="$TEST_ROOT/cat-stub/used"
mkdir -p "$cat_stub_dir"
printf '#!%s\n: > "%s"\nexec /bin/cat "$@"\n' "$bash_bin" "$cat_marker" > "$cat_stub_dir/cat"
chmod +x "$cat_stub_dir/cat"
cat_stub_home="$(make_home cat-stub)"
assert_command_output \
    "session-start with cat on PATH emits nested additionalContext" \
    "nested" \
    "" \
    "" \
    "$cat_stub_home" \
    PATH="$cat_stub_dir" \
    CLAUDE_PLUGIN_ROOT="$REPO_ROOT" \
    "$bash_bin" "$HOOK_UNDER_TEST"
if [[ -f "$cat_marker" ]]; then
    pass "session-start pipes its JSON through cat when cat is on PATH"
else
    fail "session-start pipes its JSON through cat when cat is on PATH"
fi

if [[ "$FAILURES" -gt 0 ]]; then
    echo "STATUS: FAILED ($FAILURES failure(s))"
    exit 1
fi

echo "STATUS: PASSED"
tests/hooks/test-run-hook-cmd-windows.sh 224 řádků
#!/usr/bin/env bash
# Tests for the Windows (cmd) half of hooks/run-hook.cmd: how it finds bash
# and whether the hook's exit code survives. Run from Git Bash on Windows;
# skips anywhere cmd.exe isn't available.
#
# Most cases need the fallback branches, which a machine with Git in
# Program Files never reaches. Those cases run a sandbox copy of the wrapper
# whose Program Files paths point at a directory that doesn't exist.
set -euo pipefail

if ! command -v cmd >/dev/null 2>&1 || ! command -v cygpath >/dev/null 2>&1; then
    echo "SKIP: cmd.exe not available (these tests run in Git Bash on Windows)"
    exit 0
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PF_GIT='C:\Program Files\Git'
# Spelled out: inside Git Bash, cygpath maps its own install dir to "/".
PF_GIT_UNIX='/c/Program Files/Git'

if [[ ! -e "$PF_GIT_UNIX/bin/bash.exe" ]]; then
    echo "SKIP: needs Git for Windows in $PF_GIT to stand in for other installs"
    exit 0
fi

FAILURES=0
TEST_ROOT="$(mktemp -d)"
JUNCTIONS=()

cleanup() {
    # Remove junctions with cmd's rmdir first, which never touches the
    # target, so nothing below can recurse into the real Git install.
    local j left=0
    for j in "${JUNCTIONS[@]}"; do
        cmd //c rmdir "$j" >/dev/null 2>&1 || true
        if [[ -e "$(cygpath "$j")" ]]; then
            echo "WARNING: junction $j still exists; not deleting $TEST_ROOT" >&2
            left=1
        fi
    done
    [[ "$left" -eq 0 ]] && rm -rf "$TEST_ROOT"
}
trap cleanup EXIT

pass() { echo "  [PASS] $1"; }
fail() { echo "  [FAIL] $1"; FAILURES=$((FAILURES + 1)); }

junction() {
    local link="$1" target="$2"
    # Keep Git Bash from rewriting /J into a path.
    MSYS2_ARG_CONV_EXCL="*" cmd /c mklink /J "$link" "$target" >/dev/null
    JUNCTIONS+=("$link")
}

# A plugin root with probe hooks. $1 = "real" keeps the wrapper as is;
# "sandbox" points its Program Files paths at nothing.
make_plugin() {
    local dir="$1" mode="$2"
    mkdir -p "$dir/hooks"
    if [[ "$mode" == sandbox ]]; then
        sed -e 's#C:\\Program Files\\Git\\#C:\\no-such-program-files\\Git\\#g' \
            -e 's#C:\\Program Files (x86)\\Git\\#C:\\no-such-program-files\\Git\\#g' \
            "$REPO_ROOT/hooks/run-hook.cmd" > "$dir/hooks/run-hook.cmd"
        if grep -q 'Program Files' "$dir/hooks/run-hook.cmd"; then
            echo "sandbox wrapper still mentions Program Files" >&2
            exit 1
        fi
    else
        cp "$REPO_ROOT/hooks/run-hook.cmd" "$dir/hooks/run-hook.cmd"
    fi
    printf 'echo probe-ran\n' > "$dir/hooks/probe-ok"
    printf 'echo probe-ran\nexit 7\n' > "$dir/hooks/probe-exit"
}

# run_hook PLUGIN_DIR CWD PROBE [VAR=value...] -> sets OUT and RC
run_hook() {
    local plugin="$1" cwd="$2" probe="$3"
    shift 3
    RC=0
    # tr drops the NUL bytes the WSL launcher prints (UTF-16 text).
    OUT="$(cd "$cwd" && env "$@" cmd //c "$(cygpath -w "$plugin")\\hooks\\run-hook.cmd" "$probe" 2>&1 | tr -d '\000'; exit "${PIPESTATUS[0]}")" || RC=$?
}

SYS32_PATH="/c/Windows/System32"
GIT_USR_BIN="$PF_GIT_UNIX/usr/bin"
NO_LA='C:\no-such-localappdata'

echo "run-hook.cmd (Windows) tests"

# --- exit code of the hook survives the wrapper ---
real="$TEST_ROOT/real"
make_plugin "$real" real
run_hook "$real" "$TEST_ROOT" probe-exit
if [[ "$RC" -eq 7 && "$OUT" == *probe-ran* ]]; then
    pass "hook exit code propagates through run-hook.cmd"
else
    fail "hook exit code propagates through run-hook.cmd (rc=$RC, out=$OUT)"
fi

sandbox="$TEST_ROOT/sandbox"
make_plugin "$sandbox" sandbox

# --- per-user Git install (%LOCALAPPDATA%\Programs\Git) ---
la="$TEST_ROOT/localappdata"
mkdir -p "$la/Programs"
junction "$(cygpath -w "$la/Programs/Git")" "$PF_GIT"
run_hook "$sandbox" "$TEST_ROOT" probe-exit \
    LOCALAPPDATA="$(cygpath -w "$la")" PATH="$SYS32_PATH"
if [[ "$RC" -eq 7 && "$OUT" == *probe-ran* ]]; then
    pass "per-user Git install is found and its exit code propagates"
else
    fail "per-user Git install is found and its exit code propagates (rc=$RC, out=$OUT)"
fi

# --- the System32 WSL launcher on PATH is skipped for a real bash ---
run_hook "$sandbox" "$TEST_ROOT" probe-ok \
    LOCALAPPDATA="$NO_LA" PATH="$SYS32_PATH:$GIT_USR_BIN"
if [[ "$RC" -eq 0 && "$OUT" == *probe-ran* ]]; then
    pass "System32 bash.exe (WSL launcher) is skipped in favor of Git's bash on PATH"
else
    fail "System32 bash.exe (WSL launcher) is skipped in favor of Git's bash on PATH (rc=$RC, out=$OUT)"
fi

# --- a bash under a WindowsApps directory (the Store WSL stub) is skipped ---
apps_la="$TEST_ROOT/apps-localappdata"
apps="$apps_la/Microsoft/WindowsApps"
mkdir -p "$apps"
apps_marker="$TEST_ROOT/windowsapps-ran"
printf '@echo off\r\necho stub> "%s"\r\n' "$(cygpath -w "$apps_marker")" > "$apps/bash.cmd"
run_hook "$sandbox" "$TEST_ROOT" probe-ok \
    LOCALAPPDATA="$(cygpath -w "$apps_la")" PATH="$apps:$SYS32_PATH:$GIT_USR_BIN"
if [[ ! -e "$apps_marker" && "$OUT" == *probe-ran* ]]; then
    pass "bash under WindowsApps (Store WSL stub) is skipped"
else
    fail "bash under WindowsApps (Store WSL stub) is skipped (stub ran: $([[ -e $apps_marker ]] && echo yes || echo no), out=$OUT)"
fi

# --- nothing in the current directory is run: not bash, not where ---
plant="$TEST_ROOT/planted-cwd"
mkdir -p "$plant"
for name in bash.cmd where.bat; do
    printf '@echo off\r\necho planted> "%s"\r\n' "$(cygpath -w "$TEST_ROOT/ran-$name")" > "$plant/$name"
done
run_hook "$sandbox" "$plant" probe-ok \
    LOCALAPPDATA="$NO_LA" PATH="$SYS32_PATH:$GIT_USR_BIN"
for name in bash.cmd where.bat; do
    if [[ ! -e "$TEST_ROOT/ran-$name" && "$OUT" == *probe-ran* ]]; then
        pass "$name in the current directory is not run"
    else
        fail "$name in the current directory is not run (ran: $([[ -e $TEST_ROOT/ran-$name ]] && echo yes || echo no), out=$OUT)"
    fi
done

# --- PATH entries whose names cmd could misparse still work ---
# fake_bash DIR: a bash.cmd that reports it ran.
fake_bash() {
    mkdir -p "$1"
    printf '@echo off\r\necho fake-bash-ran\r\n' > "$1/bash.cmd"
}
for dir_name in 'caret^and%OS%percent' $'caf\u00e9-bin' 'extensionless'; do
    dir="$TEST_ROOT/$dir_name"
    case "$dir_name" in
        extensionless)
            # An extensionless "bash" first on PATH must be skipped.
            mkdir -p "$dir"
            printf 'not a program\n' > "$dir/bash"
            fake_bash "$TEST_ROOT/after-extensionless"
            path="$dir:$TEST_ROOT/after-extensionless:$SYS32_PATH"
            ;;
        *)
            fake_bash "$dir"
            path="$dir:$SYS32_PATH"
            ;;
    esac
    run_hook "$sandbox" "$TEST_ROOT" probe-ok LOCALAPPDATA="$NO_LA" PATH="$path"
    if [[ "$RC" -eq 0 && "$OUT" == *fake-bash-ran* ]]; then
        pass "bash on PATH is found under $dir_name"
    else
        fail "bash on PATH is found under $dir_name (rc=$RC, out=$OUT)"
    fi
done

# --- unset SystemRoot must not let the WSL launcher through ---
run_hook "$sandbox" "$TEST_ROOT" probe-ok -u SystemRoot \
    LOCALAPPDATA="$NO_LA" PATH="$SYS32_PATH:$GIT_USR_BIN"
if [[ "$RC" -eq 0 && "$OUT" != *Subsystem* ]]; then
    pass "unset SystemRoot does not run the WSL launcher"
else
    fail "unset SystemRoot does not run the WSL launcher (rc=$RC, out=$OUT)"
fi

# --- unset LOCALAPPDATA must not probe \Programs\Git on the current drive ---
drive_programs="/c/Programs"
if [[ -e "$drive_programs" ]]; then
    echo "  [SKIP] unset LOCALAPPDATA: C:\\Programs already exists"
else
    mkdir "$drive_programs"
    junction 'C:\Programs\Git' "$PF_GIT"
    run_hook "$sandbox" "$TEST_ROOT" probe-ok -u LOCALAPPDATA PATH="$SYS32_PATH"
    cmd //c rmdir 'C:\Programs\Git' >/dev/null 2>&1 || true
    rmdir "$drive_programs"
    if [[ "$RC" -eq 0 && "$OUT" != *probe-ran* ]]; then
        pass "unset LOCALAPPDATA does not run \\Programs\\Git on the current drive"
    else
        fail "unset LOCALAPPDATA does not run \\Programs\\Git on the current drive (rc=$RC, out=$OUT)"
    fi
fi

# --- no usable bash: exit 0 quietly, without invoking the WSL launcher ---
run_hook "$sandbox" "$TEST_ROOT" probe-ok \
    LOCALAPPDATA="$NO_LA" PATH="$SYS32_PATH"
if [[ "$RC" -eq 0 && -z "$OUT" ]]; then
    pass "no usable bash exits 0 with no output"
else
    fail "no usable bash exits 0 with no output (rc=$RC, out=$OUT)"
fi

if [[ "$FAILURES" -gt 0 ]]; then
    echo "STATUS: FAILED ($FAILURES failure(s))"
    exit 1
fi
echo "STATUS: PASSED"

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč se wrapper pro Windows testuje tak podrobně?

Hledání bashe ve Windows je křehké: je tam WSL launcher, Store stub, per-user i systémové instalace Gitu. Špatná volba znamená buď nefunkční hook, nebo spuštění nesprávného programu. Test pokrývá každou větev.

2. Proč se `System32\bash.exe` přeskakuje?

Je to launcher WSL, ne Git Bash. Spustil by hook v linuxové distribuci s jinými cestami a hook by selhal nebo se choval jinak.

3. Proč test „bash.exe v aktuálním adresáři se nespustí“?

Cmd hledá spustitelné soubory nejdřív v aktuálním adresáři. Útočník by mohl do projektu umístit bash.exe. Wrapper ho nesmí spustit (ochrana před binary planting).

4. Proč při nenalezení bashe skončit s 0 a bez výstupu?

Hook je pomocný. Pád na stroji bez bashe by zablokoval start session. Mlčící úspěch je bezpečnější než zablokování práce.

5. Proč test používá „sandbox kopii“ wrapperu?

Na stroji s Gitem v Program Files by se záložní větve nikdy nespustily. Kopie s cestami na neexistující adresář je donutí použít.

6. Proč se test přeskakuje, když není `cmd`?

Testuje se cmd polovina polyglotu. Na Linuxu nemá smysl a falešné selhání by rušilo CI.

7. Proč se hook výstup kontroluje jako JSON?

Harnessy očekávají strukturovaný JSON s kontextem. Neplatný JSON by session rozbil nebo tiše ignoroval.

8. Proč test mění PATH?

Aby šlo ověřit chování bez cat a s ním. Hook se nesmí spoléhat na nástroj, který nemusí být dostupný.

9. Co je „polyglot“ soubor?

Jeden soubor platný ve dvou jazycích (cmd a bash). Windows spustí cmd část, která najde bash a spustí hook; v bashi se spustí bash část.

10. Pokrývá matcher `startup|clear|compact` v hooks.json všechny způsoby zahájení session?

Podle aktuální dokumentace má SessionStart ještě hodnoty resume (--resume, --continue, /resume) a fork. Superpowers je nezahrnuje, protože v obnovené konverzaci už bootstrap z dřívějška je. Pokud by se v praxi ukázalo, že po resume agent skills ignoruje, je rozšíření matcheru první věc k ověření. Jde o pozorování, ne o potvrzenou chybu.

Slovník pojmů (10)

SessionStart hook

Hook spouštěný při zahájení session; vkládá bootstrap.

`hooks.json`

Konfigurace hooků pro harness.

`run-hook.cmd`

Polyglot wrapper spouštějící hook v bashi na Windows i Unixu.

Polyglot

Soubor platný ve více jazycích současně.

WSL launcher

System32\bash.exe, který spouští Linux ve WSL.

WindowsApps stub

Zástupný bash.exe Microsoft Store.

Binary planting

Podstrčení spustitelného souboru do adresáře, kde ho systém najde dřív.

Git Bash

Bash dodávaný s Git for Windows.

Exit code propagation

Předání návratového kódu hooku volajícímu.

PATH sandbox

Upravená PATH pro simulaci chybějících nástrojů.

↑ nahoru

Testy OpenCode pluginu

Izolované testy načítání pluginu, registrace skills (V2 payload), bootstrap cachingu, priority skills a nativního skill nástroje.

OpenCode plugin (.opencode/plugins/superpowers.js) má nejrozsáhlejší sadu. run-tests.sh je hlavní runner s měřením času a režimem integrace, setup.sh vytvoří izolovaný HOME s nainstalovaným pluginem (symlink, testovací projekt). test-plugin-loading.sh ověří symlink pluginu a jeho cíl, počet nalezených skills a přítomnost using-superpowers (nutné pro bootstrap).

Moduly .mjs jsou unit testy napsané pro Node: test-skill-registration.mjs kontroluje, že V2 registrační payload odpovídá kontraktu OpenCode 2.0.4 ({ id, name, description?, autoinvoke?, path, content }, pole location bylo přejmenováno na path; špatné jméno by skill tiše nezaregistrovalo); test-bootstrap-caching.mjs podvrhuje fs.existsSync/readFileSync a počítá přístupy k bootstrap skillu (scénáře present a missing), tedy že se soubor nečte opakovaně; test-session-bootstrap.mjs ověřuje vložení bootstrapu do session (marker <EXTREMELY_IMPORTANT>) v obou formách odpovědi API (v1 {data} / v2). Integrační shell testy test-priority.sh (dokumentují chování duplicitních jmen skills) a test-tools.sh (nativní skill nástroj načte osobní, projektový i bundled skill) vyžadují nainstalovaný OpenCode a jinak se přeskočí.

Zdrojový kód

tests/opencode/run-tests.sh 170 řádků
#!/usr/bin/env bash
# Main test runner for OpenCode plugin test suite
# Runs all tests and reports results
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

echo "========================================"
echo " OpenCode Plugin Test Suite"
echo "========================================"
echo ""
echo "Repository: $(cd ../.. && pwd)"
echo "Test time: $(date)"
echo ""

# Parse command line arguments
RUN_INTEGRATION=false
VERBOSE=false
SPECIFIC_TEST=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --integration|-i)
            RUN_INTEGRATION=true
            shift
            ;;
        --verbose|-v)
            VERBOSE=true
            shift
            ;;
        --test|-t)
            SPECIFIC_TEST="$2"
            shift 2
            ;;
        --help|-h)
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  --integration, -i  Run integration tests (requires OpenCode)"
            echo "  --verbose, -v      Show verbose output"
            echo "  --test, -t NAME    Run only the specified test"
            echo "  --help, -h         Show this help"
            echo ""
            echo "Tests:"
            echo "  test-plugin-loading.sh  Verify plugin installation and structure"
            echo "  test-bootstrap-caching.sh  Verify bootstrap content caching"
            echo "  test-session-bootstrap.sh  Verify session classification and lookup recovery"
            echo "  test-skill-registration.sh  Verify V2 skill registration contract (2.0.4 path field)"
            echo "  test-tools.sh           Test use_skill and find_skills tools (integration)"
            echo "  test-priority.sh        Test skill priority resolution (integration)"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# List of tests to run (no external dependencies)
tests=(
    "test-plugin-loading.sh"
    "test-bootstrap-caching.sh"
    "test-session-bootstrap.sh"
    "test-skill-registration.sh"
)

# Integration tests (require OpenCode)
integration_tests=(
    "test-tools.sh"
    "test-priority.sh"
)

# Add integration tests if requested
if [ "$RUN_INTEGRATION" = true ]; then
    tests+=("${integration_tests[@]}")
fi

# Filter to specific test if requested
if [ -n "$SPECIFIC_TEST" ]; then
    tests=("$SPECIFIC_TEST")
fi

# Track results
passed=0
failed=0
skipped=0

# Run each test
for test in "${tests[@]}"; do
    echo "----------------------------------------"
    echo "Running: $test"
    echo "----------------------------------------"

    test_path="$SCRIPT_DIR/$test"

    if [ ! -f "$test_path" ]; then
        echo "  [SKIP] Test file not found: $test"
        skipped=$((skipped + 1))
        continue
    fi

    if [ ! -x "$test_path" ]; then
        echo "  Making $test executable..."
        chmod +x "$test_path"
    fi

    start_time=$(date +%s)

    if [ "$VERBOSE" = true ]; then
        if bash "$test_path"; then
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo ""
            echo "  [PASS] $test (${duration}s)"
            passed=$((passed + 1))
        else
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo ""
            echo "  [FAIL] $test (${duration}s)"
            failed=$((failed + 1))
        fi
    else
        # Capture output for non-verbose mode
        if output=$(bash "$test_path" 2>&1); then
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo "  [PASS] (${duration}s)"
            passed=$((passed + 1))
        else
            end_time=$(date +%s)
            duration=$((end_time - start_time))
            echo "  [FAIL] (${duration}s)"
            echo ""
            echo "  Output:"
            echo "$output" | sed 's/^/    /'
            failed=$((failed + 1))
        fi
    fi

    echo ""
done

# Print summary
echo "========================================"
echo " Test Results Summary"
echo "========================================"
echo ""
echo "  Passed:  $passed"
echo "  Failed:  $failed"
echo "  Skipped: $skipped"
echo ""

if [ "$RUN_INTEGRATION" = false ] && [ ${#integration_tests[@]} -gt 0 ]; then
    echo "Note: Integration tests were not run."
    echo "Use --integration flag to run tests that require OpenCode."
    echo ""
fi

if [ $failed -gt 0 ]; then
    echo "STATUS: FAILED"
    exit 1
else
    echo "STATUS: PASSED"
    exit 0
fi
tests/opencode/setup.sh 89 řádků
#!/usr/bin/env bash
# Setup script for OpenCode plugin tests
# Creates an isolated test environment with proper plugin installation
set -euo pipefail

# Get the repository root (two levels up from tests/opencode/)
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"

# Create temp home directory for isolation
export TEST_HOME
TEST_HOME=$(mktemp -d)
export HOME="$TEST_HOME"
export XDG_CONFIG_HOME="$TEST_HOME/.config"
export OPENCODE_CONFIG_DIR="$TEST_HOME/.config/opencode"

# Standard install layout:
#   $OPENCODE_CONFIG_DIR/superpowers/             ← package root
#   $OPENCODE_CONFIG_DIR/superpowers/skills/      ← skills dir (../../skills from plugin)
#   $OPENCODE_CONFIG_DIR/superpowers/.opencode/plugins/superpowers.js ← plugin file
#   $OPENCODE_CONFIG_DIR/plugins/superpowers.js   ← symlink OpenCode reads

SUPERPOWERS_DIR="$OPENCODE_CONFIG_DIR/superpowers"
SUPERPOWERS_SKILLS_DIR="$SUPERPOWERS_DIR/skills"
SUPERPOWERS_PLUGIN_FILE="$SUPERPOWERS_DIR/.opencode/plugins/superpowers.js"

# Install skills
mkdir -p "$SUPERPOWERS_DIR"
cp -r "$REPO_ROOT/skills" "$SUPERPOWERS_DIR/"

# Install plugin
mkdir -p "$(dirname "$SUPERPOWERS_PLUGIN_FILE")"
cp "$REPO_ROOT/.opencode/plugins/superpowers.js" "$SUPERPOWERS_PLUGIN_FILE"

# Register plugin via symlink (what OpenCode actually reads)
mkdir -p "$OPENCODE_CONFIG_DIR/plugins"
ln -sf "$SUPERPOWERS_PLUGIN_FILE" "$OPENCODE_CONFIG_DIR/plugins/superpowers.js"

# Create test skills in different locations for testing

# Personal test skill
mkdir -p "$OPENCODE_CONFIG_DIR/skills/personal-test"
cat > "$OPENCODE_CONFIG_DIR/skills/personal-test/SKILL.md" <<'EOF'
---
name: personal-test
description: Test personal skill for verification
---
# Personal Test Skill

This is a personal skill used for testing.

PERSONAL_SKILL_MARKER_12345
EOF

# Create a project directory for project-level skill tests
mkdir -p "$TEST_HOME/test-project/.opencode/skills/project-test"
cat > "$TEST_HOME/test-project/.opencode/skills/project-test/SKILL.md" <<'EOF'
---
name: project-test
description: Test project skill for verification
---
# Project Test Skill

This is a project skill used for testing.

PROJECT_SKILL_MARKER_67890
EOF

echo "Setup complete: $TEST_HOME"
echo "OPENCODE_CONFIG_DIR:  $OPENCODE_CONFIG_DIR"
echo "Superpowers dir:      $SUPERPOWERS_DIR"
echo "Skills dir:           $SUPERPOWERS_SKILLS_DIR"
echo "Plugin file:          $SUPERPOWERS_PLUGIN_FILE"
echo "Plugin registered at: $OPENCODE_CONFIG_DIR/plugins/superpowers.js"
echo "Test project at:      $TEST_HOME/test-project"

# Helper function for cleanup (call from tests or trap)
cleanup_test_env() {
    if [ -n "${TEST_HOME:-}" ] && [ -d "$TEST_HOME" ]; then
        rm -rf "$TEST_HOME"
    fi
}

# Export for use in tests
export -f cleanup_test_env
export REPO_ROOT
export SUPERPOWERS_DIR
export SUPERPOWERS_SKILLS_DIR
export SUPERPOWERS_PLUGIN_FILE
tests/opencode/test-plugin-loading.sh 83 řádků
#!/usr/bin/env bash
# Test: Plugin Loading
# Verifies that the superpowers plugin loads correctly in OpenCode
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Test: Plugin Loading ==="

# Source setup to create isolated environment
source "$SCRIPT_DIR/setup.sh"

# Trap to cleanup on exit
trap cleanup_test_env EXIT

plugin_link="$OPENCODE_CONFIG_DIR/plugins/superpowers.js"

# Test 1: Verify plugin file exists and is registered
echo "Test 1: Checking plugin registration..."
if [ -L "$plugin_link" ]; then
    echo "  [PASS] Plugin symlink exists"
else
    echo "  [FAIL] Plugin symlink not found at $plugin_link"
    exit 1
fi

# Verify symlink target exists
if [ -f "$(readlink -f "$plugin_link")" ]; then
    echo "  [PASS] Plugin symlink target exists"
else
    echo "  [FAIL] Plugin symlink target does not exist"
    exit 1
fi

# Test 2: Verify skills directory is populated
echo "Test 2: Checking skills directory..."
skill_count=$(find "$SUPERPOWERS_SKILLS_DIR" -name "SKILL.md" | wc -l)
if [ "$skill_count" -gt 0 ]; then
    echo "  [PASS] Found $skill_count skills"
else
    echo "  [FAIL] No skills found in $SUPERPOWERS_SKILLS_DIR"
    exit 1
fi

# Test 3: Check using-superpowers skill exists (critical for bootstrap)
echo "Test 3: Checking using-superpowers skill (required for bootstrap)..."
if [ -f "$SUPERPOWERS_SKILLS_DIR/using-superpowers/SKILL.md" ]; then
    echo "  [PASS] using-superpowers skill exists"
else
    echo "  [FAIL] using-superpowers skill not found (required for bootstrap)"
    exit 1
fi

# Test 4: Verify plugin JavaScript syntax (basic check)
echo "Test 4: Checking plugin JavaScript syntax..."
if node --check "$SUPERPOWERS_PLUGIN_FILE" 2>/dev/null; then
    echo "  [PASS] Plugin JavaScript syntax is valid"
else
    echo "  [FAIL] Plugin has JavaScript syntax errors"
    exit 1
fi

# Test 5: Verify bootstrap text does not reference a hardcoded skills path
echo "Test 5: Checking bootstrap does not advertise a wrong skills path..."
if grep -q 'configDir}/skills/superpowers/' "$SUPERPOWERS_PLUGIN_FILE"; then
    echo "  [FAIL] Plugin still references old configDir skills path"
    exit 1
else
    echo "  [PASS] Plugin does not advertise a misleading skills path"
fi

# Test 6: Verify personal test skill was created
echo "Test 6: Checking test fixtures..."
if [ -f "$OPENCODE_CONFIG_DIR/skills/personal-test/SKILL.md" ]; then
    echo "  [PASS] Personal test skill fixture created"
else
    echo "  [FAIL] Personal test skill fixture not found"
    exit 1
fi

echo ""
echo "=== All plugin loading tests passed ==="
tests/opencode/test-bootstrap-caching.mjs 269 řádků
import fs from 'fs';
import { pathToFileURL } from 'url';

const [, , pluginPath, scenario] = process.argv;

if (!pluginPath || !['present', 'missing'].includes(scenario)) {
  console.error('Usage: node test-bootstrap-caching.mjs PLUGIN_PATH present|missing');
  process.exit(2);
}

let existsCount = 0;
let readCount = 0;

const originalExistsSync = fs.existsSync;
const originalReadFileSync = fs.readFileSync;

fs.existsSync = function (...args) {
  if (isBootstrapSkillPath(args[0])) {
    existsCount += 1;
  }
  return originalExistsSync.apply(this, args);
};

fs.readFileSync = function (...args) {
  if (isBootstrapSkillPath(args[0])) {
    readCount += 1;
  }
  return originalReadFileSync.apply(this, args);
};

const mod = await import(pathToFileURL(pluginPath).href);
const plugin = await mod.SuperpowersPlugin({ client: {}, directory: '.' });
const transform = plugin['experimental.chat.messages.transform'];

// Mapping constants are flavor-specific (#opencode-v2): V1 keeps the 1.18.x
// tool names, V2 teaches the renamed tools. Assert both directly.
const mappingFailures = assertMappingConstants(mod);

const firstOutput = makeOutput(`${scenario} bootstrap first step`);
await transform({}, firstOutput);
const afterFirst = { existsCount, readCount };

const secondOutput = makeOutput(`${scenario} bootstrap second step`);
await transform({}, secondOutput);
const afterSecond = { existsCount, readCount };

// Exercise the V2 path (setup() + ctx.session.hook("context")) with a mock
// ctx so the V2_MAPPING wiring is verified, not just the constant. Run after
// the V1 count snapshots: setup() reads SKILL.md files during registration.
const v2Result = await runV2ContextHook(mod);

const result = {
  scenario,
  firstBootstrapParts: countBootstrapParts(firstOutput),
  secondBootstrapParts: countBootstrapParts(secondOutput),
  staleMentionMapping: bootstrapText(firstOutput).includes('@mention'),
  staleTaskMapping: bootstrapText(firstOutput).includes('`Task` tool with subagents'),
  mapsSubagentToTask: bootstrapText(firstOutput).includes('`task` with `subagent_type: "general"`'),
  mapsMutationToApplyPatch: bootstrapText(firstOutput).includes('`apply_patch`'),
  firstReadCount: afterFirst.readCount,
  secondReadCount: afterSecond.readCount,
  firstExistsCount: afterFirst.existsCount,
  secondExistsCount: afterSecond.existsCount,
  v2BootstrapParts: v2Result.bootstrapParts,
  mapsV2SubagentTool: v2Result.text.includes('`subagent` with `agent: "general"`'),
  mapsV2SessionIDContinuation: v2Result.text.includes('`sessionID` to continue a previous subagent'),
  mapsV2NoTodoTool: v2Result.text.includes('no todo tool'),
  mapsV2MutationToPatch: v2Result.text.includes('`patch` with `patchText`'),
  mapsV2Shell: v2Result.text.includes('`shell`'),
  staleV1ToolsInV2: v2Result.text.includes('`apply_patch`') || v2Result.text.includes('`todowrite`') || v2Result.text.includes('`subagent_type`'),
};

const failures = scenario === 'present'
  ? assertPresentBootstrap(result)
  : assertMissingBootstrap(result);

if (scenario === 'present') {
  failures.push(...assertV2Bootstrap(result));
}
failures.push(...mappingFailures);

if (failures.length > 0) {
  console.error(JSON.stringify(result, null, 2));
  for (const failure of failures) {
    console.error(`FAIL: ${failure}`);
  }
  process.exit(1);
}

console.log(JSON.stringify(result, null, 2));

function isBootstrapSkillPath(filePath) {
  return String(filePath).replaceAll('\\', '/').includes('using-superpowers/SKILL.md');
}

function makeOutput(text) {
  return {
    messages: [{
      info: { role: 'user' },
      parts: [{ type: 'text', text }],
    }],
  };
}

function countBootstrapParts(output) {
  return output.messages[0].parts.filter(
    (part) => part.type === 'text' && part.text.includes('EXTREMELY_IMPORTANT')
  ).length;
}

function bootstrapText(output) {
  return output.messages[0].parts.find(
    (part) => part.type === 'text' && part.text.includes('EXTREMELY_IMPORTANT')
  )?.text || '';
}

function assertPresentBootstrap(result) {
  const failures = [];
  if (result.firstBootstrapParts !== 1) {
    failures.push(`expected first transform to inject one bootstrap part, got ${result.firstBootstrapParts}`);
  }
  if (result.secondBootstrapParts !== 1) {
    failures.push(`expected second transform to inject one bootstrap part, got ${result.secondBootstrapParts}`);
  }
  if (result.firstReadCount !== 1) {
    failures.push(`expected first transform to read SKILL.md once, got ${result.firstReadCount}`);
  }
  if (result.secondReadCount !== result.firstReadCount) {
    failures.push(`expected cached second transform to do no additional reads, got ${result.secondReadCount - result.firstReadCount}`);
  }
  if (result.secondExistsCount !== result.firstExistsCount) {
    failures.push(`expected cached second transform to do no additional exists checks, got ${result.secondExistsCount - result.firstExistsCount}`);
  }
  if (result.staleMentionMapping) {
    failures.push('expected OpenCode bootstrap not to teach @mention subagent syntax');
  }
  if (result.staleTaskMapping) {
    failures.push('expected OpenCode bootstrap not to teach stale Task-tool mapping');
  }
  if (!result.mapsSubagentToTask) {
    failures.push('expected OpenCode bootstrap to map general-purpose subagents to task with subagent_type');
  }
  if (!result.mapsMutationToApplyPatch) {
    failures.push('expected OpenCode bootstrap to map file mutation to apply_patch');
  }
  return failures;
}

function assertMissingBootstrap(result) {
  const failures = [];
  if (result.firstBootstrapParts !== 0) {
    failures.push(`expected no bootstrap when SKILL.md is missing, got ${result.firstBootstrapParts}`);
  }
  if (result.secondBootstrapParts !== 0) {
    failures.push(`expected no bootstrap on second missing-file transform, got ${result.secondBootstrapParts}`);
  }
  if (result.firstReadCount !== 0 || result.secondReadCount !== 0) {
    failures.push(`expected missing file path to avoid reads, got ${result.secondReadCount}`);
  }
  if (result.firstExistsCount < 1) {
    failures.push('expected first transform to check whether SKILL.md exists');
  }
  if (result.secondExistsCount !== result.firstExistsCount) {
    failures.push(`expected missing-file result to be cached, got ${result.secondExistsCount - result.firstExistsCount} extra exists checks`);
  }
  return failures;
}

function assertMappingConstants(mod) {
  const failures = [];
  if (typeof mod.V1_MAPPING !== 'string' || typeof mod.V2_MAPPING !== 'string') {
    failures.push('expected plugin to export V1_MAPPING and V2_MAPPING string constants');
    return failures;
  }
  for (const needle of ['`todowrite`', '`task` with `subagent_type: "general"`', '`apply_patch`', '`bash`']) {
    if (!mod.V1_MAPPING.includes(needle)) {
      failures.push(`expected V1_MAPPING to keep the 1.18.x tool name ${needle}`);
    }
  }
  for (const needle of [
    '`subagent` with `agent: "general"`',
    '`sessionID` to continue a previous subagent',
    'no todo tool',
    '`write`',
    '`edit`',
    '`patch` with `patchText`',
    '`shell`',
    '`read`',
    '`grep`, `glob`',
    '`webfetch`',
    '`websearch`',
  ]) {
    if (!mod.V2_MAPPING.includes(needle)) {
      failures.push(`expected V2_MAPPING to teach the V2 tool ${needle}`);
    }
  }
  for (const stale of ['`todowrite`', '`task` with', '`apply_patch`', '`bash`']) {
    if (mod.V2_MAPPING.includes(stale)) {
      failures.push(`expected V2_MAPPING not to teach the V1-only tool name ${stale}`);
    }
  }
  return failures;
}

// Drive setup() with a mock V2 ctx and fire the captured "context" hook on a
// top-level (parentID-less) session. Returns the injected-part count and the
// injected bootstrap text ('' when nothing was injected).
async function runV2ContextHook(mod) {
  let contextHook = null;
  const ctx = {
    skill: {
      transform: async (fn) => {
        fn({ add: () => {} });
      },
    },
    session: {
      hook: async (name, cb) => {
        if (name === 'context') contextHook = cb;
      },
      get: async ({ sessionID }) => ({ id: sessionID }), // top-level: no parentID
    },
  };
  try {
    await mod.default.setup(ctx);
  } catch (err) {
    console.error('[test] V2 setup() threw:', err);
    return { bootstrapParts: 0, text: '' };
  }
  if (typeof contextHook !== 'function') {
    return { bootstrapParts: 0, text: '' };
  }
  const event = {
    sessionID: 'sess-v2-top',
    messages: [{ role: 'user', content: [{ type: 'text', text: 'v2 bootstrap step' }] }],
  };
  await contextHook(event);
  const parts = event.messages[0].content.filter(
    (part) => part.type === 'text' && part.text.includes('EXTREMELY_IMPORTANT')
  );
  return { bootstrapParts: parts.length, text: parts[0]?.text || '' };
}

function assertV2Bootstrap(result) {
  const failures = [];
  if (result.v2BootstrapParts !== 1) {
    failures.push(`expected V2 context hook to inject one bootstrap part, got ${result.v2BootstrapParts}`);
    return failures;
  }
  if (!result.mapsV2SubagentTool) {
    failures.push('expected V2 bootstrap to map general-purpose subagents to subagent with agent');
  }
  if (!result.mapsV2SessionIDContinuation) {
    failures.push('expected V2 bootstrap to teach sessionID continuation for subagents');
  }
  if (!result.mapsV2NoTodoTool) {
    failures.push('expected V2 bootstrap to state that V2 has no todo tool');
  }
  if (!result.mapsV2MutationToPatch) {
    failures.push('expected V2 bootstrap to map file mutation to patch with patchText');
  }
  if (!result.mapsV2Shell) {
    failures.push('expected V2 bootstrap to map shell commands to the shell tool');
  }
  if (result.staleV1ToolsInV2) {
    failures.push('expected V2 bootstrap not to teach V1-only tool names (apply_patch/todowrite/subagent_type)');
  }
  return failures;
}
tests/opencode/test-bootstrap-caching.sh 33 řádků
#!/usr/bin/env bash
# Test: Bootstrap Content Caching (#1202)
# Verifies the OpenCode transform caches bootstrap content between agent steps.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Test: Bootstrap Content Caching (#1202) ==="

source "$SCRIPT_DIR/setup.sh"
trap cleanup_test_env EXIT

run_present_file_check() {
    node "$SCRIPT_DIR/test-bootstrap-caching.mjs" "$SUPERPOWERS_PLUGIN_FILE" present
}

run_missing_file_check() {
    mv "$SUPERPOWERS_SKILLS_DIR/using-superpowers/SKILL.md" "$TEST_HOME/using-superpowers.SKILL.md.bak"

    node "$SCRIPT_DIR/test-bootstrap-caching.mjs" "$SUPERPOWERS_PLUGIN_FILE" missing
}

echo "Test 1: Caches bootstrap after the first successful transform..."
run_present_file_check
echo "  [PASS] Bootstrap content is cached while fresh message arrays still receive injection"

echo "Test 2: Caches missing SKILL.md result..."
run_missing_file_check
echo "  [PASS] Missing bootstrap file is cached and not re-probed every transform"

echo ""
echo "=== All bootstrap caching tests passed ==="
tests/opencode/test-session-bootstrap.mjs 225 řádků
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { pathToFileURL } from 'node:url';

const [, , inputPath] = process.argv;
assert.ok(inputPath, 'pass the plugin module path');
const pluginURL = pathToFileURL(fs.realpathSync(inputPath));
const marker = '<EXTREMELY_IMPORTANT>\nYou have superpowers.';
let generation = 0;

function reply(flavor, session) {
  return flavor === 'v1' ? { data: session } : session;
}

function makeEvent(flavor, sessionID) {
  const text = { type: 'text', text: 'Execute the assigned task' };
  return {
    sessionID,
    messages: [flavor === 'v1'
      ? { info: { role: 'user', sessionID }, parts: [text] }
      : { role: 'user', content: [text] }],
  };
}

function bootstrapCount(event) {
  return event.messages.flatMap((message) => message.parts ?? message.content ?? []).filter(
    (part) => part.type === 'text' && part.text.startsWith(marker)
  ).length;
}

async function makeHarness(flavor, fetchSession) {
  const mod = await import(`${pluginURL.href}?session-test=${++generation}`);
  const lookups = [];
  const registered = [];
  const get = async (id) => {
    lookups.push(id);
    return fetchSession(id, lookups.length);
  };
  let invoke;
  if (flavor === 'v1') {
    const hooks = await mod.SuperpowersPlugin({
      client: { session: { get: ({ path: { id } }) => get(id) } },
      directory: '.',
    });
    invoke = (event) => hooks['experimental.chat.messages.transform']({}, event);
  } else {
    await mod.default.setup({
      skill: { transform: async (transform) => transform({ add: (skill) => registered.push(skill) }) },
      session: {
        get: ({ sessionID }) => get(sessionID),
        hook: async (name, callback) => { if (name === 'context') invoke = callback; },
      },
    });
  }
  assert.equal(typeof invoke, 'function');
  return { invoke, lookups, registered };
}

for (const flavor of ['v1', 'v2']) {
  for (const [kind, extra, expected] of [
    ['root', {}, 1],
    ['child', { parentID: 'parent' }, 0],
    ['fork', { fork: { sessionID: 'origin' } }, 1],
  ]) {
    const id = `${flavor}-${kind}`;
    const h = await makeHarness(flavor, () => reply(flavor, { id, ...extra }));
    const event = makeEvent(flavor, id);
    await h.invoke(event);
    assert.equal(bootstrapCount(event), expected, `${id}: first request`);
    await h.invoke(event);
    assert.equal(bootstrapCount(event), expected, `${id}: repeated event`);
    const fresh = makeEvent(flavor, id);
    await h.invoke(fresh);
    assert.equal(bootstrapCount(fresh), expected, `${id}: fresh request`);
    assert.deepEqual(h.lookups, [id], `${id}: cache successful classification`);
    if (flavor === 'v2' && kind === 'child') {
      assert.ok(h.registered.some((skill) => skill.id === 'brainstorming'));
    }
  }

  const failures = [
    ['throws', () => { throw new Error('temporary lookup failure'); }],
    ['missing', () => undefined],
    ['null', () => null],
    ['empty', () => reply(flavor, {})],
    ['wrong-id', () => reply(flavor, { id: 'different-session' })],
    ['invalid-parent', (id) => reply(flavor, { id, parentID: 42 })],
  ];
  if (flavor === 'v1') {
    failures.push(['resolved-http-error', () => ({
      data: undefined,
      error: { name: 'UnknownError', data: { message: 'temporary 503' } },
      response: { ok: false, status: 503 },
    })]);
  }
  for (const [kind, firstResult] of failures) {
    const id = `${flavor}-${kind}`;
    const h = await makeHarness(flavor, (sessionID, call) => call === 1
      ? firstResult(sessionID)
      : reply(flavor, { id: sessionID, parentID: 'parent' }));
    const counts = [];
    for (let step = 0; step < 2; step++) {
      const event = makeEvent(flavor, id);
      await h.invoke(event);
      counts.push(bootstrapCount(event));
    }
    assert.deepEqual(counts, [1, 0], `${id}: recover on the next request`);
    assert.deepEqual(h.lookups, [id, id], `${id}: never cache the failure`);
  }

  const isolated = await makeHarness(flavor, (id) => reply(flavor,
    id === 'child-session' ? { id, parentID: 'parent' } : { id }));
  for (const [id, expected] of [['root-session', 1], ['child-session', 0], ['root-session', 1], ['child-session', 0]]) {
    const event = makeEvent(flavor, id);
    await isolated.invoke(event);
    assert.equal(bootstrapCount(event), expected);
  }
  assert.deepEqual(isolated.lookups, ['root-session', 'child-session']);

  const bounded = await makeHarness(flavor, (id) => reply(flavor, { id, parentID: 'parent' }));
  for (let index = 0; index <= 512; index++) {
    const event = makeEvent(flavor, `eviction-${index}`);
    await bounded.invoke(event);
    assert.equal(bootstrapCount(event), 0);
  }
  const evicted = makeEvent(flavor, 'eviction-0');
  await bounded.invoke(evicted);
  assert.equal(bootstrapCount(evicted), 0);
  assert.equal(bounded.lookups.filter((id) => id === 'eviction-0').length, 2);

  const restarted = await makeHarness(flavor, (id) => reply(flavor, { id, parentID: 'parent' }));
  const afterRestart = makeEvent(flavor, 'eviction-0');
  await restarted.invoke(afterRestart);
  assert.equal(bootstrapCount(afterRestart), 0);
  assert.deepEqual(restarted.lookups, ['eviction-0']);

  const unknown = await makeHarness(flavor, () => { throw new Error('must not look up a missing ID'); });
  const noID = makeEvent(flavor, undefined);
  await unknown.invoke(noID);
  assert.equal(bootstrapCount(noID), 1);
  assert.deepEqual(unknown.lookups, []);
}

function compactedEvent(sessionID) {
  return {
    sessionID,
    system: [],
    messages: [{
      role: 'assistant',
      content: [{ type: 'compaction', provider: 'fixture', encrypted: 'opaque-checkpoint' }],
    }],
  };
}

const compactedRoot = await makeHarness('v2', (id) => ({ id }));
const rootEvent = compactedEvent('compacted-root');
const checkpoint = structuredClone(rootEvent.messages[0]);
await compactedRoot.invoke(rootEvent);
assert.equal(bootstrapCount(rootEvent), 1);
assert.deepEqual(rootEvent.messages[0], checkpoint);
assert.equal(rootEvent.messages.length, 2);
assert.equal(rootEvent.messages[1].role, 'user');
assert.deepEqual(rootEvent.system, []);
await compactedRoot.invoke(rootEvent);
assert.equal(bootstrapCount(rootEvent), 1);
assert.equal(rootEvent.messages.length, 2);
const freshRootEvent = compactedEvent('compacted-root');
await compactedRoot.invoke(freshRootEvent);
assert.equal(bootstrapCount(freshRootEvent), 1);
assert.deepEqual(compactedRoot.lookups, ['compacted-root']);

const compactedChild = await makeHarness('v2', (id) => ({ id, parentID: 'parent' }));
const childEvent = compactedEvent('compacted-child');
const originalChild = structuredClone(childEvent);
await compactedChild.invoke(childEvent);
assert.equal(bootstrapCount(childEvent), 0);
assert.deepEqual(childEvent, originalChild);
assert.deepEqual(compactedChild.lookups, ['compacted-child']);

const retryChild = await makeHarness('v2', (id, call) => {
  if (call === 1) throw new Error('temporary lookup failure');
  return { id, parentID: 'parent' };
});
const unknownChild = compactedEvent('retry-compacted-child');
await retryChild.invoke(unknownChild);
assert.equal(bootstrapCount(unknownChild), 1);
const recoveredChild = compactedEvent('retry-compacted-child');
await retryChild.invoke(recoveredChild);
assert.equal(bootstrapCount(recoveredChild), 0);
assert.equal(recoveredChild.messages.length, 1);
assert.equal(retryChild.lookups.length, 2);

const newPromptAfterCheckpoint = compactedEvent('new-prompt-after-checkpoint-root');
newPromptAfterCheckpoint.messages.push({ role: 'user', content: [{ type: 'text', text: 'Continue' }] });
await compactedRoot.invoke(newPromptAfterCheckpoint);
assert.equal(bootstrapCount(newPromptAfterCheckpoint), 1);
assert.equal(newPromptAfterCheckpoint.messages.length, 2);
assert.equal(newPromptAfterCheckpoint.messages[1].content.length, 2);

const retainedUser = compactedEvent('retained-user-root');
retainedUser.messages.unshift({ role: 'user', content: [{ type: 'text', text: 'Keep going' }] });
const retainedCheckpoint = structuredClone(retainedUser.messages[1]);
await compactedRoot.invoke(retainedUser);
assert.equal(bootstrapCount(retainedUser), 1);
assert.equal(retainedUser.messages.length, 2);
assert.equal(retainedUser.messages[0].content.length, 2);
assert.ok(retainedUser.messages[0].content[0].text.startsWith(marker));
assert.equal(retainedUser.messages[0].content[1].text, 'Keep going');
assert.deepEqual(retainedUser.messages[1], retainedCheckpoint);
await compactedRoot.invoke(retainedUser);
assert.equal(bootstrapCount(retainedUser), 1);
assert.equal(retainedUser.messages.length, 2);

const retainedUserChild = compactedEvent('retained-user-child');
retainedUserChild.messages.unshift({ role: 'user', content: [{ type: 'text', text: 'Keep going' }] });
const originalRetainedUserChild = structuredClone(retainedUserChild);
await compactedChild.invoke(retainedUserChild);
assert.equal(bootstrapCount(retainedUserChild), 0);
assert.deepEqual(retainedUserChild, originalRetainedUserChild);
const empty = { sessionID: 'empty', messages: [] };
await compactedRoot.invoke(empty);
assert.deepEqual(empty.messages, []);

console.log('Session classification, recovery and cache lifetime passed');
tests/opencode/test-session-bootstrap.sh 5 řádků
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
node "$SCRIPT_DIR/test-session-bootstrap.mjs" "$SCRIPT_DIR/../../.opencode/plugins/superpowers.js"
tests/opencode/test-skill-registration.mjs 206 řádků
import fs from 'fs';
import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';

// Verifies the V2 skill registration payload matches OpenCode 2.0.4's
// Skill.Info contract (packages/schema/src/skill.ts):
//   { id, name, description?, autoinvoke?, path, content }
// Upstream commit 199aabe9e2 (first released in v2.0.4) renamed the required
// file field `location` -> `path`. A wrong field name makes draft.add()
// throw inside the host's transform rebuild, which asynchronously disables
// the whole plugin ("Plugin disabled after skill.transform failed") and
// takes the bootstrap hook down with it — see PR #2106 review by 80avin.

const [, , inputPath] = process.argv;

if (!inputPath) {
  console.error('Usage: node test-skill-registration.mjs PLUGIN_PATH');
  process.exit(2);
}

const pluginPath = fs.realpathSync(inputPath);
const skillsDir = path.resolve(path.dirname(pluginPath), '../../skills');
const mod = await import(pathToFileURL(pluginPath).href);

const failures = [];

// --- Run 1: passive capture of every draft.add payload -------------------
const added = [];
await mod.default.setup(makeCtx({ add: (skill) => added.push(skill) }));

const expectedIds = fs.existsSync(skillsDir)
  ? fs.readdirSync(skillsDir, { withFileTypes: true })
      .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
      .filter((e) => fs.existsSync(path.join(skillsDir, e.name, 'SKILL.md')))
      .map((e) => e.name)
      .sort()
  : [];

if (added.length === 0) {
  failures.push('expected setup() to register at least one skill via draft.add()');
}
if (JSON.stringify(added.map((s) => s.id).sort()) !== JSON.stringify(expectedIds)) {
  failures.push(`expected draft.add() ids to match skills dir contents, got ${JSON.stringify(added.map((s) => s.id))}`);
}

for (const skill of added) {
  if (typeof skill.path !== 'string' || !path.isAbsolute(skill.path)) {
    failures.push(`skill "${skill.id}": expected required absolute Skill.Info field "path", got ${JSON.stringify(skill.path)}`);
  } else if (skill.path !== path.join(skillsDir, skill.id, 'SKILL.md')) {
    failures.push(`skill "${skill.id}": expected path ${path.join(skillsDir, skill.id, 'SKILL.md')}, got ${skill.path}`);
  } else if (!fs.existsSync(skill.path)) {
    failures.push(`skill "${skill.id}": path does not exist on disk: ${skill.path}`);
  }
  // Stale 2.0.3-era fields must not leak into the payload: the host strips
  // unknown keys, but keeping them would silently mask a future regression
  // to a schema that no longer accepts `path`.
  if ('location' in skill) {
    failures.push(`skill "${skill.id}": payload still carries the pre-2.0.4 field "location"`);
  }
  if ('slash' in skill) {
    failures.push(`skill "${skill.id}": payload carries "slash", removed from Skill.Info in 2.0.4`);
  }
  if (typeof skill.id !== 'string' || skill.id.length === 0) failures.push(`skill payload missing non-empty "id"`);
  if (typeof skill.name !== 'string' || skill.name.length === 0) failures.push(`skill "${skill.id}" missing non-empty "name"`);
  if (typeof skill.content !== 'string' || !skill.content.trim()) failures.push(`skill "${skill.id}" missing non-empty "content"`);
  if ('description' in skill && typeof skill.description !== 'string') {
    failures.push(`skill "${skill.id}": "description" must be a string when present`);
  } else if ('description' in skill && /["']$/.test(skill.description)) {
    failures.push(`skill "${skill.id}": description ends with a dangling quote: ${JSON.stringify(skill.description)}`);
  }
  if (typeof skill.content === 'string' && skill.content.startsWith('---')) {
    failures.push(`skill "${skill.id}": content still starts with the frontmatter delimiter`);
  }
}

// --- Run 2: hostile draft.add must not abort the remaining registrations --
// The real host swallows a throw escaping the transform callback and then
// hard-disables the plugin asynchronously. Locally we can only observe the
// synchronous half of that contract: when draft.add() rejects one skill, the
// plugin must keep registering the rest instead of aborting the loop.
const hostileId = added.length > 1 ? added[Math.floor(added.length / 2)].id : null;
const survived = [];
let setupThrew = null;
let survivingContextHook;
try {
  await mod.default.setup(makeCtx({
    add: (skill) => {
      if (skill.id === hostileId) throw new Error('Simulated Skill.Info decode failure');
      survived.push(skill.id);
    },
    onHook: (name, callback) => {
      if (name === 'context') survivingContextHook = callback;
    },
  }));
} catch (err) {
  setupThrew = err;
}
if (setupThrew) {
  failures.push(`expected setup() to contain draft.add() failures, but it threw: ${setupThrew.message}`);
} else if (hostileId) {
  const expectedSurvivors = added.map((s) => s.id).filter((id) => id !== hostileId);
  if (JSON.stringify(survived.sort()) !== JSON.stringify(expectedSurvivors.sort())) {
    failures.push(`expected all non-rejected skills to still register when one draft.add() throws, got ${JSON.stringify(survived)}`);
  }
}
if (typeof survivingContextHook !== 'function') {
  failures.push('expected bootstrap hook to survive a rejected skill');
} else {
  const event = {
    sessionID: 'registration-survival-root',
    messages: [{ role: 'user', content: [{ type: 'text', text: 'Continue' }] }],
  };
  await survivingContextHook(event);
  const count = event.messages.flatMap((message) => message.content).filter(
    (part) => part.type === 'text' && part.text.startsWith('<EXTREMELY_IMPORTANT>\nYou have superpowers.')
  ).length;
  if (count !== 1) failures.push(`expected surviving bootstrap once, got ${count}`);
}

// --- Run 3: quoted and multi-line frontmatter values ---------------------
// The description is what the host shows in its skill list. A quoted value
// that wraps onto indented continuation lines must register as one unquoted
// line, so exercise each layout against a synthetic install: a copy of the
// plugin next to fixture skills, laid out like a real package root.
const frontmatterFixtures = {
  'multi-line-double': {
    frontmatter: 'description: "Use when foo happens\n  and bar continues\n  and baz ends"',
    expected: 'Use when foo happens and bar continues and baz ends',
  },
  'multi-line-single': {
    frontmatter: "description: 'Use when foo happens\n  and bar continues\n  and baz ends'",
    expected: 'Use when foo happens and bar continues and baz ends',
  },
  'single-line-quoted': {
    frontmatter: 'description: "Plain quoted"',
    expected: 'Plain quoted',
  },
  'block-scalar': {
    frontmatter: 'description: >\n  Folded line one\n  line two',
    expected: 'Folded line one line two',
  },
};
const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'superpowers-frontmatter-'));
try {
  const fixturePlugin = path.join(fixtureRoot, '.opencode', 'plugins', 'superpowers.js');
  fs.mkdirSync(path.dirname(fixturePlugin), { recursive: true });
  fs.copyFileSync(pluginPath, fixturePlugin);
  for (const [id, { frontmatter }] of Object.entries(frontmatterFixtures)) {
    const skillDir = path.join(fixtureRoot, 'skills', id);
    fs.mkdirSync(skillDir, { recursive: true });
    fs.writeFileSync(path.join(skillDir, 'SKILL.md'), `---\nname: ${id}\n${frontmatter}\n---\n# Title\n\nBody.\n`);
  }
  const fixtureMod = await import(pathToFileURL(fixturePlugin).href);
  const fixtureAdded = [];
  await fixtureMod.default.setup(makeCtx({ add: (skill) => fixtureAdded.push(skill) }));
  for (const [id, { expected }] of Object.entries(frontmatterFixtures)) {
    const skill = fixtureAdded.find((s) => s.id === id);
    if (!skill) {
      failures.push(`fixture "${id}": expected setup() to register it`);
      continue;
    }
    if (skill.description !== expected) {
      failures.push(`fixture "${id}": expected description ${JSON.stringify(expected)}, got ${JSON.stringify(skill.description)}`);
    }
    if (skill.content.startsWith('---')) {
      failures.push(`fixture "${id}": content still starts with the frontmatter delimiter`);
    }
  }
} finally {
  fs.rmSync(fixtureRoot, { recursive: true, force: true });
}

const result = {
  registered: added.length,
  ids: added.map((s) => s.id),
  allPathsValid: added.every((s) => s.path === path.join(skillsDir, s.id, 'SKILL.md') && fs.existsSync(s.path)),
  staleLocationField: added.some((s) => 'location' in s),
  hostileRejectedId: hostileId,
  survivedHostileAdd: JSON.stringify(survived.sort()) === JSON.stringify(added.map((s) => s.id).filter((id) => id !== hostileId).sort()),
};

if (failures.length > 0) {
  console.error(JSON.stringify(result, null, 2));
  for (const failure of failures) {
    console.error(`FAIL: ${failure}`);
  }
  process.exit(1);
}

console.log(JSON.stringify(result, null, 2));

function makeCtx({ add, onHook = () => {} }) {
  return {
    skill: {
      transform: async (fn) => {
        await fn({ list: () => [], get: () => undefined, add, update: () => {}, remove: () => {} });
      },
    },
    session: {
      hook: async (name, callback) => onHook(name, callback),
      get: async ({ sessionID }) => ({ id: sessionID }), // top-level: no parentID
    },
  };
}
tests/opencode/test-skill-registration.sh 23 řádků
#!/usr/bin/env bash
# Test: V2 Skill Registration Contract (#2106 review)
# Verifies setup() registers skills matching OpenCode 2.0.4's Skill.Info
# schema (path field, no stale location/slash) and contains per-skill
# draft.add() failures instead of aborting registration.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Test: V2 Skill Registration Contract ==="

source "$SCRIPT_DIR/setup.sh"
trap cleanup_test_env EXIT

node "$SCRIPT_DIR/test-skill-registration.mjs" "$SUPERPOWERS_PLUGIN_FILE"
node "$SCRIPT_DIR/test-skill-registration.mjs" "$OPENCODE_CONFIG_DIR/plugins/superpowers.js"

echo "  [PASS] Skill payloads match the 2.0.4 Skill.Info contract"
echo "  [PASS] A rejected draft.add() skips one skill without aborting the rest"
echo "  [PASS] Quoted and multi-line frontmatter values register unquoted"
echo ""
echo "=== All skill registration tests passed ==="
tests/opencode/test-priority.sh 218 řádků
#!/usr/bin/env bash
# Test: Skill Priority Resolution
# Documents current OpenCode duplicate-name behavior for local and bundled
# skills. The desired local-shadowing behavior is tracked separately; this
# test keeps the integration suite honest without adding a plugin workaround.
# NOTE: These tests require OpenCode to be installed and configured
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
OPENCODE_TEST_TIMEOUT_SECONDS="${OPENCODE_TEST_TIMEOUT_SECONDS:-120}"

echo "=== Test: Skill Priority Resolution ==="

# Source setup to create isolated environment
source "$SCRIPT_DIR/setup.sh"

# Trap to cleanup on exit
trap cleanup_test_env EXIT

# Create same skill "priority-test" in all three locations with different markers
echo "Setting up priority test fixtures..."

# 1. Create in superpowers location (lowest priority)
mkdir -p "$SUPERPOWERS_SKILLS_DIR/priority-test"
cat > "$SUPERPOWERS_SKILLS_DIR/priority-test/SKILL.md" <<'EOF'
---
name: priority-test
description: Superpowers version of priority test skill
---
# Priority Test Skill (Superpowers Version)

This is the SUPERPOWERS version of the priority test skill.

PRIORITY_MARKER_SUPERPOWERS_VERSION
EOF

# 2. Create in personal location (medium priority)
mkdir -p "$OPENCODE_CONFIG_DIR/skills/priority-test"
cat > "$OPENCODE_CONFIG_DIR/skills/priority-test/SKILL.md" <<'EOF'
---
name: priority-test
description: Personal version of priority test skill
---
# Priority Test Skill (Personal Version)

This is the PERSONAL version of the priority test skill.

PRIORITY_MARKER_PERSONAL_VERSION
EOF

# 3. Create in project location (highest priority)
mkdir -p "$TEST_HOME/test-project/.opencode/skills/priority-test"
cat > "$TEST_HOME/test-project/.opencode/skills/priority-test/SKILL.md" <<'EOF'
---
name: priority-test
description: Project version of priority test skill
---
# Priority Test Skill (Project Version)

This is the PROJECT version of the priority test skill.

PRIORITY_MARKER_PROJECT_VERSION
EOF

echo "  Created priority-test skill in all three locations"

# Test 1: Verify fixture setup
echo ""
echo "Test 1: Verifying test fixtures..."

if [ -f "$SUPERPOWERS_SKILLS_DIR/priority-test/SKILL.md" ]; then
    echo "  [PASS] Superpowers version exists"
else
    echo "  [FAIL] Superpowers version missing"
    exit 1
fi

if [ -f "$OPENCODE_CONFIG_DIR/skills/priority-test/SKILL.md" ]; then
    echo "  [PASS] Personal version exists"
else
    echo "  [FAIL] Personal version missing"
    exit 1
fi

if [ -f "$TEST_HOME/test-project/.opencode/skills/priority-test/SKILL.md" ]; then
    echo "  [PASS] Project version exists"
else
    echo "  [FAIL] Project version missing"
    exit 1
fi

# Check if opencode is available for integration tests
if ! command -v opencode &> /dev/null; then
    echo ""
    echo "  [SKIP] OpenCode not installed - skipping integration tests"
    echo "  To run these tests, install OpenCode: https://opencode.ai"
    echo ""
    echo "=== Priority fixture tests passed (integration tests skipped) ==="
    exit 0
fi

run_opencode() {
    local result_var="$1"
    local dir="$2"
    local prompt="$3"
    local command_output
    local exit_code

    set +e
    command_output=$(cd "$dir" && timeout "${OPENCODE_TEST_TIMEOUT_SECONDS}s" opencode run --print-logs --format json "$prompt" 2>&1)
    exit_code=$?
    set -e

    if [ $exit_code -eq 124 ]; then
        echo "  [FAIL] OpenCode timed out after ${OPENCODE_TEST_TIMEOUT_SECONDS}s"
        exit 1
    fi

    if [ $exit_code -ne 0 ]; then
        echo "  [FAIL] OpenCode returned non-zero exit code: $exit_code"
        echo "  Output was:"
        awk 'NR <= 80 { print }' <<<"$command_output"
        exit 1
    fi

    printf -v "$result_var" '%s' "$command_output"
}

assert_contains() {
    local output="$1"
    local needle="$2"
    local message="$3"

    if [[ "$output" == *"$needle"* ]]; then
        echo "  [PASS] $message"
    else
        echo "  [FAIL] $message"
        echo "  Expected to find: $needle"
        echo "  Output was:"
        awk 'NR <= 80 { print }' <<<"$output"
        exit 1
    fi
}

first_skill_tool_event() {
    awk '/"type":"tool_use"/ && /"tool":"skill"/ { print; exit }' <<<"$1"
}

describe_priority_result() {
    local output="$1"
    local expected_marker="$2"
    local fallback_marker="$3"
    local pass_message="$4"
    local known_bug_message="$5"
    local loaded_skill

    loaded_skill="$(first_skill_tool_event "$output")"

    if [[ "$loaded_skill" == *"$expected_marker"* ]]; then
        echo "  [PASS] $pass_message"
    elif [[ "$loaded_skill" == *"$fallback_marker"* ]]; then
        echo "  [INFO] $known_bug_message"
        echo "  [INFO] Tracked separately: OpenCode bundled skills can shadow local skills with duplicate native names"
    else
        echo "  [FAIL] Could not verify priority marker in native skill tool output"
        echo "  Output was:"
        awk 'NR <= 80 { print }' <<<"$output"
        exit 1
    fi
}

# Test 2: Document personal vs bundled superpowers priority
echo ""
echo "Test 2: Documenting personal vs superpowers priority..."
echo "  Running from outside project directory..."

run_opencode output "$HOME" "Call the skill tool with name \"priority-test\". Show the exact content including any PRIORITY_MARKER text."
describe_priority_result \
    "$output" \
    "PRIORITY_MARKER_PERSONAL_VERSION" \
    "PRIORITY_MARKER_SUPERPOWERS_VERSION" \
    "Personal version loaded for duplicate native skill name" \
    "Current OpenCode behavior loaded bundled superpowers version instead of personal version"

# Test 3: Document project vs bundled superpowers priority
echo ""
echo "Test 3: Documenting project vs personal/superpowers priority..."
echo "  Running from project directory..."

run_opencode output "$TEST_HOME/test-project" "Call the skill tool with name \"priority-test\". Show the exact content including any PRIORITY_MARKER text."
describe_priority_result \
    "$output" \
    "PRIORITY_MARKER_PROJECT_VERSION" \
    "PRIORITY_MARKER_SUPERPOWERS_VERSION" \
    "Project version loaded for duplicate native skill name" \
    "Current OpenCode behavior loaded bundled superpowers version instead of project version"

# Test 4: Test a non-colliding bundled superpowers skill is still available
echo ""
echo "Test 4: Testing non-colliding superpowers skill remains available..."

mkdir -p "$SUPERPOWERS_SKILLS_DIR/superpowers-only-test"
cat > "$SUPERPOWERS_SKILLS_DIR/superpowers-only-test/SKILL.md" <<'EOF'
---
name: superpowers-only-test
description: Superpowers-only priority test skill
---
# Superpowers Only Test Skill

PRIORITY_MARKER_SUPERPOWERS_ONLY_VERSION
EOF

run_opencode output "$TEST_HOME/test-project" "Call the skill tool with name \"superpowers-only-test\". Show the exact content including any PRIORITY_MARKER text."
assert_contains "$output" "PRIORITY_MARKER_SUPERPOWERS_ONLY_VERSION" "Non-colliding superpowers skill is still registered"

echo ""
echo "=== All priority tests passed ==="
tests/opencode/test-tools.sh 96 řádků
#!/usr/bin/env bash
# Test: Native Skill Tool Functionality
# Verifies that OpenCode's native skill tool can load personal, project,
# and bundled superpowers skills.
# NOTE: These tests require OpenCode to be installed and configured
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
OPENCODE_TEST_TIMEOUT_SECONDS="${OPENCODE_TEST_TIMEOUT_SECONDS:-120}"

echo "=== Test: Tools Functionality ==="

# Source setup to create isolated environment
source "$SCRIPT_DIR/setup.sh"

# Trap to cleanup on exit
trap cleanup_test_env EXIT

# Check if opencode is available
if ! command -v opencode &> /dev/null; then
    echo "  [SKIP] OpenCode not installed - skipping integration tests"
    echo "  To run these tests, install OpenCode: https://opencode.ai"
    exit 0
fi

run_opencode() {
    local result_var="$1"
    local dir="$2"
    local prompt="$3"
    local command_output
    local exit_code

    set +e
    command_output=$(cd "$dir" && timeout "${OPENCODE_TEST_TIMEOUT_SECONDS}s" opencode run --print-logs --format json "$prompt" 2>&1)
    exit_code=$?
    set -e

    if [ $exit_code -eq 124 ]; then
        echo "  [FAIL] OpenCode timed out after ${OPENCODE_TEST_TIMEOUT_SECONDS}s"
        exit 1
    fi

    if [ $exit_code -ne 0 ]; then
        echo "  [FAIL] OpenCode returned non-zero exit code: $exit_code"
        echo "  Output was:"
        awk 'NR <= 80 { print }' <<<"$command_output"
        exit 1
    fi

    printf -v "$result_var" '%s' "$command_output"
}

assert_contains() {
    local output="$1"
    local needle="$2"
    local message="$3"

    if [[ "$output" == *"$needle"* ]]; then
        echo "  [PASS] $message"
    else
        echo "  [FAIL] $message"
        echo "  Expected to find: $needle"
        echo "  Output was:"
        awk 'NR <= 80 { print }' <<<"$output"
        exit 1
    fi
}

# Test 1: Test personal skill loading via OpenCode's native skill tool
echo "Test 1: Testing native skill tool with a personal skill..."
echo "  Running opencode with personal-test request..."

run_opencode output "$TEST_HOME/test-project" "Call the skill tool with name \"personal-test\". Then print the PERSONAL_SKILL_MARKER_12345 marker."
assert_contains "$output" '"tool":"skill"' "OpenCode called the native skill tool"
assert_contains "$output" "PERSONAL_SKILL_MARKER_12345" "native skill tool loaded personal-test skill content"

# Test 2: Test project skill loading
echo ""
echo "Test 2: Testing native skill tool with a project skill..."
echo "  Running opencode with project-test request..."

run_opencode output "$TEST_HOME/test-project" "Call the skill tool with name \"project-test\". Then print the PROJECT_SKILL_MARKER_67890 marker."
assert_contains "$output" "PROJECT_SKILL_MARKER_67890" "native skill tool loaded project-test skill content"

# Test 3: Test bundled superpowers skill loading
echo ""
echo "Test 3: Testing native skill tool with a superpowers skill..."
echo "  Running opencode with brainstorming skill..."

run_opencode output "$TEST_HOME/test-project" "Call the skill tool with name \"brainstorming\". Then tell me the loaded skill title."
assert_contains "$output" '"name":"brainstorming"' "native skill tool loaded bundled brainstorming skill"
assert_contains "$output" "Brainstorming Ideas Into Designs" "brainstorming skill content was returned"

echo ""
echo "=== All native skill tool tests passed ==="

Kvíz (9 otázek, odpověď se rozbalí kliknutím)

1. Proč setup vytváří izolovaný HOME?

Test nesmí číst ani měnit skutečné konfigurace uživatele. Dočasný domov s vlastním pluginem zajistí reprodukovatelnost a nic nezanechá.

2. Proč je důležité jméno pole `path` v registračním payloadu?

OpenCode 2.0.4 přejmenoval location na path. Se starým jménem by se draft.add() tiše nezaregistroval a plugin by neměl žádné skills. Test chrání proti takové tiché regresi.

3. Co ověřuje test bootstrap cachingu?

Že plugin čte soubor using-superpowers jednou a ne při každé zprávě. Test podvrhne funkce souborového systému, spočítá volání a porovná scénář, kdy soubor existuje a kdy chybí.

4. Proč se podvrhují funkce `fs`?

Počítání přístupů na disk je jediný spolehlivý způsob, jak ověřit cache bez měření času. Testy jsou rychlé a deterministické.

5. Proč test session bootstrap zkouší dvě formy odpovědi (v1 a v2)?

OpenCode API vrací buď {data: session}, nebo přímo session. Plugin musí fungovat s oběma; test používá funkci reply(flavor, session).

6. Proč se integrační testy přeskočí bez OpenCode?

Nelze předpokládat jeho přítomnost (CI). [SKIP] místo selhání zachovává užitečnost jednotkových testů.

7. Co dokumentuje `test-priority.sh`?

Současné chování, když existují skills stejného jména v superpowers, osobním a projektovém místě. Žádoucí chování (lokální přebije bundled) se sleduje zvlášť; test jen drží integrační sadu pravdivou a nepřidává workaround.

8. Proč se testuje nativní skill tool přes `"tool":"skill"` ve výstupu?

Dokazuje, že OpenCode skill skutečně načetl nástrojem, ne že ho agent jen opsal. Marker PERSONAL_SKILL_MARKER_12345 v obsahu potvrdí načtení správného souboru.

9. Proč jsou `.sh` obaly pro `.mjs` testy?

Runner spouští shell skripty. Obal najde Node, předá cestu k pluginu a sjednotí výstup [PASS]/[FAIL].

Slovník pojmů (10)

OpenCode

Agentní harness s vlastním plugin API.

Skill registration payload

Objekt {id, name, description?, autoinvoke?, path, content}.

Bootstrap caching

Jednorázové načtení bootstrap skillu a opětovné použití.

Session bootstrap

Vložení instrukcí do session při jejím vzniku.

`<EXTREMELY_IMPORTANT>` marker

Značka bootstrap textu v session.

Isolated HOME

Dočasný domovský adresář pro test.

Native skill tool

Vestavěný nástroj OpenCode pro načtení skillu.

`[SKIP]`

Výsledek testu, který nemá prostředí k běhu.

Shadowing

Přebití skillu stejného jména lokální verzí.

Monkey patching (`fs`)

Dočasná výměna funkcí pro počítání volání.

↑ nahoru

Testy Pi extension

Node testy pi balíčku: deklarace v package.json, lifecycle hooky, resources_discover a injekce bootstrapu včetně compaction.

Integrace pro harness Pi je TypeScriptové rozšíření (.pi/extensions/superpowers.ts). Jediný test test-pi-extension.mjs má šest bloků: (1) package.json deklaruje pi balíček s skills a extensions, (2) rozšíření registruje lifecycle hooky bez injekce před kompakcí, (3) resources_discover přispívá adresářem s bundled skills, (4) při startu se bootstrap vloží jako jedna uživatelská zpráva až do agent_end, (5) session_compact vkládá bootstrap po souhrnech kompakce, ne před nimi a (6) reference nástrojů dokumentuje pi mapování.

Test používá falešné Pi API, které zaznamenává registrované handlery a umožňuje je vyvolat. Tím se ověřuje pořadí a podmínky injekce bez spuštění Pi.

Zdrojový kód

tests/pi/test-pi-extension.mjs 138 řádků
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import test from 'node:test';

const __dirname = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(__dirname, '../..');
const packageJsonPath = resolve(repoRoot, 'package.json');
const extensionPath = resolve(repoRoot, '.pi/extensions/superpowers.ts');
const piToolsPath = resolve(repoRoot, 'skills/using-superpowers/references/pi-tools.md');

async function readPackageJson() {
  return JSON.parse(await readFile(packageJsonPath, 'utf8'));
}

async function loadExtension() {
  const handlers = new Map();
  const pi = {
    on(event, handler) {
      if (!handlers.has(event)) handlers.set(event, []);
      handlers.get(event).push(handler);
    },
  };
  const mod = await import(pathToFileURL(extensionPath).href + `?cachebust=${Date.now()}-${Math.random()}`);
  mod.default(pi);
  return { handlers };
}

function firstHandler(handlers, event) {
  const eventHandlers = handlers.get(event) ?? [];
  assert.equal(eventHandlers.length, 1, `expected one ${event} handler`);
  return eventHandlers[0];
}

function textOf(message) {
  if (typeof message.content === 'string') return message.content;
  return message.content
    .filter((part) => part.type === 'text')
    .map((part) => part.text)
    .join('\n');
}

test('package.json declares a pi package with skills and extension resources', async () => {
  const pkg = await readPackageJson();

  assert.equal(pkg.name, 'superpowers');
  assert.ok(pkg.keywords.includes('pi-package'));
  assert.deepEqual(pkg.pi.skills, ['./skills']);
  assert.deepEqual(pkg.pi.extensions, ['./.pi/extensions/superpowers.ts']);
});

test('extension registers lifecycle hooks without pre-compaction injection', async () => {
  const { handlers } = await loadExtension();

  for (const event of ['resources_discover', 'session_start', 'session_compact', 'context', 'agent_end']) {
    assert.equal((handlers.get(event) ?? []).length, 1, `missing ${event} handler`);
  }
  assert.equal((handlers.get('session_before_compact') ?? []).length, 0);
});

test('resources_discover contributes the bundled skills directory', async () => {
  const { handlers } = await loadExtension();
  const discover = firstHandler(handlers, 'resources_discover');

  const result = await discover({ type: 'resources_discover', cwd: repoRoot, reason: 'startup' }, {});

  assert.deepEqual(result.skillPaths, [resolve(repoRoot, 'skills')]);
});

test('startup context injects the bootstrap as one user message until agent_end', async () => {
  const { handlers } = await loadExtension();
  const sessionStart = firstHandler(handlers, 'session_start');
  const context = firstHandler(handlers, 'context');
  const agentEnd = firstHandler(handlers, 'agent_end');

  await sessionStart({ type: 'session_start', reason: 'startup' }, {});

  const originalMessages = [
    { role: 'user', content: [{ type: 'text', text: 'Let us make a react todo list' }], timestamp: 1 },
  ];
  const result = await context({ type: 'context', messages: originalMessages }, {});

  assert.equal(result.messages.length, 2);
  assert.equal(result.messages[0].role, 'user');
  assert.match(textOf(result.messages[0]), /You have superpowers/);
  assert.match(textOf(result.messages[0]), /Pi tool mapping/);
  assert.equal(result.messages[1], originalMessages[0]);

  const repeatedProviderRequest = await context({ type: 'context', messages: originalMessages }, {});
  assert.equal(repeatedProviderRequest.messages.length, 2);
  assert.match(textOf(repeatedProviderRequest.messages[0]), /You have superpowers/);

  const alreadyInjected = await context({ type: 'context', messages: result.messages }, {});
  assert.equal(alreadyInjected, undefined, 'bootstrap should not duplicate when already present');

  await agentEnd({ type: 'agent_end', messages: [] }, {});
  const afterEnd = await context({ type: 'context', messages: originalMessages }, {});
  assert.equal(afterEnd, undefined, 'startup bootstrap should clear after agent_end');
});

test('session_compact injects bootstrap after compaction summaries, not before compaction', async () => {
  const { handlers } = await loadExtension();
  const sessionCompact = firstHandler(handlers, 'session_compact');
  const context = firstHandler(handlers, 'context');

  await sessionCompact({ type: 'session_compact', compactionEntry: {}, fromExtension: false }, {});

  const summary = { role: 'compactionSummary', summary: 'Prior work summary', tokensBefore: 123, timestamp: 1 };
  const user = { role: 'user', content: [{ type: 'text', text: 'Continue' }], timestamp: 2 };
  const result = await context({ type: 'context', messages: [summary, user] }, {});

  assert.equal(result.messages.length, 3);
  assert.equal(result.messages[0], summary);
  assert.equal(result.messages[1].role, 'user');
  assert.match(textOf(result.messages[1]), /You have superpowers/);
  assert.equal(result.messages[2], user);
});

test('pi tools reference documents pi-specific mappings', async () => {
  assert.equal(existsSync(piToolsPath), true, 'pi-tools.md should exist');
  const text = await readFile(piToolsPath, 'utf8');

  // Assert against the mapping-table rows only. The surrounding prose mentions
  // these same tokens, so matching the whole file would still pass if the table
  // were deleted — the exact regression this test exists to catch.
  const rows = text.split('\n').filter((line) => line.startsWith('|'));
  assert.ok(
    rows.some((row) => /subagent/i.test(row)),
    'mapping table documents subagent dispatch',
  );
  assert.ok(
    rows.some((row) => /todo|task/i.test(row)),
    'mapping table documents task tracking',
  );
});

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč se bootstrap vkládá jako jedna uživatelská zpráva až do `agent_end`?

Bootstrap má být vidět modelu po celý běh agenta, ale nemá se opakovat při každém volání. Zpráva trvá do konce běhu a pak zmizí, takže kontext neroste.

2. Proč po compaction ne před ní?

Kompakce shrne předchozí konverzaci. Bootstrap vložený před ní by se zkrátil spolu s ostatním a model by o instrukce přišel. Vložení po souhrnu zaručí, že instrukce přežijí.

3. Proč test „bez pre-compaction injekce“?

Zabraňuje dvojí injekci (před i po) a ztrátě instrukcí. Zdůrazňuje, že správné místo je až po souhrnech.

4. K čemu je `resources_discover`?

Rozšíření v něm oznámí Pi, kde najít skills. Bez toho by Pi bundled skills nenačetlo.

5. Proč test používá falešné Pi API?

Umožňuje deterministicky ověřit chování rozšíření bez skutečného harnessu: zachytí registrované handlery a vyvolá je v definovaném pořadí.

6. Proč se kontroluje `package.json` s klíčovým slovem `pi-package`?

Pi balíčky se objevují podle manifestu. Chybějící deklarace (pi.extensions, pi.skills) znamená, že je Pi nenajde.

7. Co kontroluje test dokumentace nástrojů?

Že pi-tools.md obsahuje pi-specifické mapování (jak v Pi dělat to, co skills popisují obecně). Skill bez mapování by agentovi nedal použitelné pokyny.

8. Proč je test napsán jako `.mjs`?

Repozitář je ES modul ("type": "module") a rozšíření se importuje dynamicky.

Slovník pojmů (9)

Pi

Harness (agentní CLI), pro který existuje rozšíření.

Extension

TypeScriptový modul registrující hooky v Pi.

`resources_discover`

Hook, kterým rozšíření oznamuje adresáře se zdroji (skills).

`agent_end`

Událost konce běhu agenta; po ní bootstrap zmizí.

`session_compact`

Událost kompakce session.

Compaction summary

Souhrn nahrazující starou část konverzace.

Bootstrap injection

Vložení instrukcí using-superpowers do kontextu.

Mock API

Falešné API zaznamenávající handlery.

`pi-package`

Klíčové slovo v package.json označující pi balíček.

↑ nahoru

Testy manifestů pluginů: Antigravity, Devin a Kimi

CI-safe validace manifestů, loga a mapování nástrojů pro Antigravity, Devin CLI a Kimi bez potřeby nainstalovaných agentů.

Každý podporovaný harness má v repozitáři manifest (.antigravity-plugin/, .devin-plugin/, .kimi-plugin/). Tyto testy jsou CI-safe: nevyžadují nainstalovaného agenta a ověřují jen to, co jde zkontrolovat shellem a malým Pythonem.

Antigravity: test-antigravity-tools.sh kontroluje mapování nástrojů (subagenti přes invoke_subagent s typy self a research, sledování úkolů jako artefakt task, odkaz SKILL.md na antigravity-tools.md); test-logo.sh ověřuje, že logo je čtvercové RGBA PNG alespoň 128×128 a (pokud je rsvg-convert) odpovídá čerstvému renderu; test-plugin-manifest.sh validuje manifest a při dostupném agy spustí agy plugin validate. Devin: test-devin-plugin.sh ověřuje manifest .devin-plugin/plugin.json; skills se auto-discovery z skills/, takže není co dalšího testovat. Kimi: test-plugin-manifest.sh kontroluje jméno superpowers a cestu ./skills/.

Zdrojový kód

tests/antigravity/run-tests.sh 17 řádků
#!/usr/bin/env bash
# Run all Antigravity (agy) integration tests.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "=== Antigravity integration tests ==="

for t in "$SCRIPT_DIR"/test-*.sh; do
  echo
  echo ">>> $t"
  bash "$t"
done

echo
echo "=== All Antigravity tests passed ==="
tests/antigravity/test-antigravity-tools.sh 45 řádků
#!/usr/bin/env bash
# Validate the Antigravity (agy) tool mapping: subagent dispatch via
# invoke_subagent (self/research types), task tracking via a task artifact, and
# SKILL.md pointing at the mapping. The plugin manifest and layout are checked
# by test-plugin-manifest.sh.
#
# Mirrors tests/pi/test-pi-extension.mjs's "tools reference documents
# harness-specific mappings" check. CI-safe: does not require `agy` installed.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

MAPPING="$REPO_ROOT/skills/using-superpowers/references/antigravity-tools.md"
SKILL="$REPO_ROOT/skills/using-superpowers/SKILL.md"

fail() { echo "FAIL: $*" >&2; exit 1; }

echo "test-antigravity-tools: checking Antigravity tool mapping"

# --- Mapping exists ---------------------------------------------------------
[ -f "$MAPPING" ] || fail "tool mapping missing at $MAPPING"

# --- Core action→tool mappings are documented -------------------------------
for tool in write_to_file replace_file_content invoke_subagent; do
  grep -q "$tool" "$MAPPING" \
    || fail "mapping does not document the '$tool' tool"
done

# --- Subagents use the built-in self/research types -------------------------
grep -q '`self`' "$MAPPING" \
  || fail "mapping does not document the built-in 'self' subagent type"
grep -q '`research`' "$MAPPING" \
  || fail "mapping does not document the built-in 'research' subagent type"

# --- Task tracking documents the 'task' artifact mechanism ------------------
grep -qE 'ArtifactType.*task|task. artifact' "$MAPPING" \
  || fail "mapping does not document task tracking as a 'task' artifact"

# --- SKILL.md Platform Adaptation links the mapping -------------------------
grep -q "antigravity-tools.md" "$SKILL" \
  || fail "SKILL.md Platform Adaptation does not reference antigravity-tools.md"

echo "PASS: Antigravity tool mapping valid (subagent dispatch, task artifact, SKILL.md link)"
tests/antigravity/test-logo.sh 45 řádků
#!/usr/bin/env bash
# Check the Antigravity Marketplace logo: a square RGBA PNG at least 128x128
# (the Marketplace minimum), at the path the manifest names. When rsvg-convert
# is available, also check the committed PNG matches a fresh render, so the
# asset can't drift from scripts/render-antigravity-logo.sh.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
LOGO="$REPO_ROOT/assets/antigravity-logo.png"

fail() { echo "FAIL: $*" >&2; exit 1; }

echo "test-logo: checking Antigravity logo"

[ -f "$LOGO" ] || fail "logo missing at $LOGO"

python3 - "$LOGO" <<'PY'
import struct
import sys

data = open(sys.argv[1], "rb").read()
if data[:8] != b"\x89PNG\r\n\x1a\n":
    raise SystemExit("FAIL: logo is not a PNG")
width, height, bit_depth, color_type = struct.unpack(">IIBB", data[16:26])
if width != height:
    raise SystemExit(f"FAIL: logo is not square ({width}x{height})")
if width < 128:
    raise SystemExit(f"FAIL: logo is smaller than 128x128 ({width}x{height})")
if color_type != 6:
    raise SystemExit(f"FAIL: logo is not RGBA (PNG color type {color_type})")
PY

if command -v rsvg-convert >/dev/null 2>&1; then
  tmp="$(mktemp -d)"
  trap 'rm -f "$tmp/logo.png"; rmdir "$tmp"' EXIT
  bash "$REPO_ROOT/scripts/render-antigravity-logo.sh" --output "$tmp/logo.png" >/dev/null
  cmp -s "$tmp/logo.png" "$LOGO" \
    || fail "assets/antigravity-logo.png is stale; run scripts/render-antigravity-logo.sh"
else
  echo "SKIP: rsvg-convert not on PATH; not checking logo freshness"
fi

echo "PASS: Antigravity logo valid"
tests/antigravity/test-plugin-manifest.sh 108 řádků
#!/usr/bin/env bash
# Validate the native Antigravity plugin: the Marketplace manifest, the skill
# description agy relies on to bootstrap using-superpowers, and the repo layout
# agy depends on. CI-safe; when `agy` is on PATH, also runs `agy plugin validate`.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

echo "test-plugin-manifest: checking Antigravity plugin"

python3 - "$REPO_ROOT" <<'PY'
import json
import re
import struct
import sys
from pathlib import Path

root = Path(sys.argv[1])

def fail(message):
    raise SystemExit(f"FAIL: {message}")

manifest_path = root / ".antigravity-plugin" / "plugin.json"
if not manifest_path.is_file():
    fail(f"manifest missing at {manifest_path}")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))

# --- Marketplace-required fields -------------------------------------------
for field in ["name", "description", "displayName", "logo",
              "suggestedPrompts", "version", "author"]:
    if not manifest.get(field):
        fail(f"manifest field {field!r} is missing or empty")

if manifest["name"] != "superpowers":
    fail(f"name must be 'superpowers', got {manifest['name']!r}")
if not re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", manifest["name"]):
    fail("name is not kebab-case")

description_length = len(manifest["description"])
# The guide recommends 120-160 characters for Marketplace cards; we use a
# shorter tagline by choice, so enforce only the upper bound.
if description_length > 160:
    fail(f"description is {description_length} characters; Marketplace cards fit at most 160")

prompts = manifest["suggestedPrompts"]
if not isinstance(prompts, list) or not 1 <= len(prompts) <= 3:
    fail("suggestedPrompts must be a list of 1-3 prompts")
if not all(isinstance(p, str) and p.strip() for p in prompts):
    fail("suggestedPrompts entries must be non-empty strings")

claude_manifest = json.loads(
    (root / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8"))
if manifest["version"] != claude_manifest["version"]:
    fail(f"version {manifest['version']!r} != .claude-plugin version "
         f"{claude_manifest['version']!r}")
if manifest["author"] != claude_manifest["author"]:
    fail("author does not match .claude-plugin/plugin.json")

# --- Logo ------------------------------------------------------------------
logo = root / manifest["logo"]
if not logo.is_file():
    fail(f"logo {manifest['logo']!r} does not exist")
header = logo.read_bytes()[:26]
if header[:8] != b"\x89PNG\r\n\x1a\n":
    fail("logo is not a PNG")
width, height = struct.unpack(">II", header[16:24])
if width != height or width < 128:
    fail(f"logo must be square and at least 128x128, got {width}x{height}")

# --- Version bumps ---------------------------------------------------------
version_config = json.loads((root / ".version-bump.json").read_text(encoding="utf-8"))
if not any(entry.get("path") == ".antigravity-plugin/plugin.json"
           and entry.get("field") == "version"
           for entry in version_config.get("files", [])):
    fail(".version-bump.json does not register .antigravity-plugin/plugin.json")

# --- Bootstrap: agy lists each skill's description, and using-superpowers'
# description is what gets the model to load it at the start of a session.
skill_md = (root / "skills" / "using-superpowers" / "SKILL.md").read_text(encoding="utf-8")
frontmatter = re.match(r"---\n(.*?)\n---\n", skill_md, re.DOTALL)
description = frontmatter and re.search(r"^description:(.*)$", frontmatter.group(1), re.MULTILINE)
if not description or "Use when starting any conversation" not in description.group(1):
    fail("using-superpowers description no longer says 'Use when starting any "
         "conversation'; Antigravity relies on it to bootstrap")

# --- Layout agy depends on -------------------------------------------------
# A root plugin.json would be read instead of .antigravity-plugin/plugin.json,
# a root hooks.json would run on every model call, and Cursor loads any
# rules/*.md shipped in a plugin.
for stray in ["plugin.json", "hooks.json", "rules"]:
    if (root / stray).exists():
        fail(f"root {stray} must not exist")
PY

if command -v agy >/dev/null 2>&1; then
  output="$(agy plugin validate "$REPO_ROOT" 2>&1)" \
    || { echo "$output" >&2; echo "FAIL: agy plugin validate failed" >&2; exit 1; }
  grep -q '\[ok\]' <<<"$output" \
    || { echo "$output" >&2; echo "FAIL: agy plugin validate did not report [ok]" >&2; exit 1; }
  grep -qE 'skills +: [0-9]+ processed' <<<"$output" \
    || { echo "$output" >&2; echo "FAIL: agy found no skills" >&2; exit 1; }
else
  echo "SKIP: agy not on PATH; not running agy plugin validate"
fi

echo "PASS: Antigravity plugin manifest and layout valid"
tests/devin/test-devin-plugin.sh 64 řádků
#!/usr/bin/env bash
# Validate the Devin CLI integration. `devin plugins install obra/superpowers`
# reads `.devin-plugin/plugin.json` and auto-discovers the co-located `skills/`
# directory; Devin CLI surfaces every installed skill's name + description in
# the system prompt at session start and invokes them via its native `skill`
# tool, and its system prompt already documents its own tools (subagent
# profiles, todo tracking, question prompts), so there is no hook, injector,
# or tool-mapping scaffold to test. What IS Devin-specific is the manifest.
#
# Mirrors tests/kimi/test-plugin-manifest.sh. CI-safe: does not require
# `devin` installed.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

MANIFEST="$REPO_ROOT/.devin-plugin/plugin.json"

fail() { echo "FAIL: $*" >&2; exit 1; }

echo "test-devin-plugin: checking Devin CLI manifest"

# --- Manifest is valid and matches the repo version -------------------------
[ -f "$MANIFEST" ] || fail "manifest missing at $MANIFEST"

python3 - "$MANIFEST" <<'PY'
import json
import sys
from pathlib import Path

manifest_path = Path(sys.argv[1])
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
repo_root = manifest_path.parents[1]

if manifest.get("name") != "superpowers":
    raise AssertionError(f"plugin name: expected 'superpowers', got {manifest.get('name')!r}")

package = json.loads((repo_root / "package.json").read_text(encoding="utf-8"))
if manifest.get("version") != package.get("version"):
    raise AssertionError(
        f"manifest version {manifest.get('version')!r} != package.json version {package.get('version')!r}"
    )

# Devin CLI plugins carry skills only (auto-discovered from ./skills/); the
# manifest supports metadata + dependency lists, nothing executable.
unsupported = ["skills", "hooks", "commands", "sessionStart", "contextFileName", "inject"]
present = sorted(field for field in unsupported if field in manifest)
if present:
    raise AssertionError("unsupported Devin manifest fields present: " + ", ".join(present))

version_config = json.loads((repo_root / ".version-bump.json").read_text(encoding="utf-8"))
entries = version_config.get("files")
if not isinstance(entries, list) or not any(
    entry.get("path") == ".devin-plugin/plugin.json" and entry.get("field") == "version"
    for entry in entries
    if isinstance(entry, dict)
):
    raise AssertionError(".version-bump.json must update .devin-plugin/plugin.json version")

print("Devin plugin manifest looks good")
PY

echo "PASS: Devin CLI plugin valid (manifest)"
tests/kimi/run-tests.sh 7 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

bash "$SCRIPT_DIR/test-plugin-manifest.sh"
tests/kimi/test-plugin-manifest.sh 87 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
MANIFEST="$REPO_ROOT/.kimi-plugin/plugin.json"

python3 - "$MANIFEST" <<'PY'
import json
import sys
from pathlib import Path

manifest_path = Path(sys.argv[1])
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))

def assert_equal(actual, expected, label):
    if actual != expected:
        raise AssertionError(f"{label}: expected {expected!r}, got {actual!r}")

def assert_present(text, needle, label):
    if needle not in text:
        raise AssertionError(f"{label}: missing {needle!r}")

assert_equal(manifest.get("name"), "superpowers", "plugin name")
assert_equal(manifest.get("skills"), "./skills/", "skills path")
assert_equal(
    manifest.get("sessionStart", {}).get("skill"),
    "using-superpowers",
    "sessionStart.skill",
)

instructions = manifest.get("skillInstructions")
if not isinstance(instructions, str) or not instructions.strip():
    raise AssertionError("skillInstructions must be a non-empty string")

for token in [
    "AskUserQuestion",
    "TodoList",
    "Agent",
    "Skill",
    "Read",
    "Write",
    "Edit",
    "Bash",
    "Grep",
    "Glob",
    "FetchURL",
    "WebSearch",
]:
    assert_present(instructions, token, "skillInstructions")

version_config = json.loads(
    (manifest_path.parents[1] / ".version-bump.json").read_text(encoding="utf-8")
)
version_entries = version_config.get("files")
if not isinstance(version_entries, list):
    raise AssertionError(".version-bump.json must contain files list")

if not any(
    entry.get("path") == ".kimi-plugin/plugin.json" and entry.get("field") == "version"
    for entry in version_entries
    if isinstance(entry, dict)
):
    raise AssertionError(
        ".version-bump.json must update .kimi-plugin/plugin.json version"
    )

unsupported_fields = [
    "tools",
    "commands",
    "hooks",
    "apps",
    "inject",
    "configFile",
    "config_file",
    "bootstrap",
]
present_unsupported = sorted(field for field in unsupported_fields if field in manifest)
if present_unsupported:
    raise AssertionError(
        "unsupported Kimi runtime fields present: "
        + ", ".join(present_unsupported)
    )

print("Kimi plugin manifest looks good")
PY

Kvíz (8 otázek, odpověď se rozbalí kliknutím)

1. Proč jsou testy „CI-safe“?

CI nemá nainstalované všechny agenty. Test, který vyžaduje agy nebo Devin, by na CI selhal. Statická validace manifestů poběží kdekoli.

2. Proč Devin nemá test hooků ani mapování nástrojů?

Devin CLI sám zobrazuje skills v system promptu a má vlastní dokumentaci nástrojů. Jediná věc specifická pro integraci je manifest, takže se testuje jen ten.

3. Proč test loga kontroluje minimální velikost 128×128 a RGBA?

Marketplace Antigravity vyžaduje tento minimální formát. Test dřív než marketplace zachytí neplatný soubor.

4. K čemu je porovnání loga s čerstvým renderem?

scripts/render-antigravity-logo.sh generuje PNG ze SVG. Kdyby někdo upravil SVG a nepřegeneroval PNG, test selže a upozorní, že asset je zastaralý.

5. Proč se kontroluje, že `SKILL.md` odkazuje na `antigravity-tools.md`?

Agent se musí dozvědět, jak překládat názvy nástrojů. Chybějící odkaz by znamenal, že mapování existuje, ale nikdo ho nenajde.

6. Proč se testují přesné názvy typů subagentů (`self`, `research`)?

Pokud harness typy přejmenuje nebo mapování zastará, skill by dával agentovi nefunkční pokyny. Test je včasná signalizace.

7. Proč test Kimi kontroluje `skills: "./skills/"`?

Je to klíčové pole, podle kterého Kimi najde skills. Překlep znamená, že plugin nebude mít žádné skills.

8. Proč se `agy plugin validate` spouští jen, když je `agy` v PATH?

Rozšíří test o oficiální validátor tam, kde je dostupný, a neblokuje prostředí bez něj.

Slovník pojmů (10)

Plugin manifest

JSON soubor popisující plugin (jméno, verzi, cesty k skills).

Antigravity (agy)

Harness od Googlu; má vlastní marketplace a mapování nástrojů.

`invoke_subagent`

Nástroj pro spuštění subagenta v Antigravity.

Subagent type `self` / `research`

Vestavěné typy subagentů.

Task artifact

Způsob sledování úkolů v Antigravity.

Marketplace logo

Čtvercové RGBA PNG min. 128×128.

`rsvg-convert`

Nástroj pro renderování SVG do PNG.

Devin CLI

Agent, který skills načítá z skills/ a zobrazuje v system promptu.

Kimi plugin

Manifest .kimi-plugin/plugin.json.

CI-safe

Test nezávislý na nainstalovaném agentovi.

↑ nahoru

Testy kvality repozitáře: shell lint, velikost skills a bump verze

Testy skriptu lint-shell (ShellCheck/shfmt s fake nástroji), limitu 20 000 bajtů na SKILL.md a skriptu bump-version.

test-lint-shell.sh ověřuje scripts/lint-shell.sh pomocí falešných nástrojů (stub shellcheck a shfmt, které zapisují svá volání do logu): v režimu check hlásí „Linting 3 shell files“, nespouští shfmt, spouští ShellCheck se --severity=warning, --external-sources a --source-path=SCRIPTDIR, zahrne změněný soubor bez přípony poznaný podle shebangu (hooks/session-start), sledované i nesledované .sh a ignoruje Markdown se shell ukázkami.

test-skill-size.sh selže, pokud některý SKILL.md dosáhne 20 000 bajtů: po compaction Claude Code připojí skill zkrácený a vše za řezem se ztratí; občasný obsah patří do references/. Test měří bajty (přísněji než znaky). Aktualizace k aktuální dokumentaci (říjen 2026): dokumentace dnes uvádí, že si každý vyvolaný skill podrží prvních 5 000 tokenů a všechny znovu připojené skills sdílejí rozpočet 25 000 tokenů; limit 20 000 bajtů je tedy konzervativní a stále užitečný. test-bump-version.sh testuje scripts/bump-version.sh: --check, --audit a bump na novou verzi změní JSON i YAML manifest, Hermes manifest je registrován v .version-bump.json, nevalidní YAML (číselná verze) bump odmítne a nezmění nic, a audit rozliší pin #v4.0.0 od adresy 10.4.0.0.

Zdrojový kód

tests/shell-lint/test-lint-shell.sh 180 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SCRIPT_UNDER_TEST="$REPO_ROOT/scripts/lint-shell.sh"

FAILURES=0
TEST_ROOT="$(mktemp -d)"

cleanup() {
  rm -rf "$TEST_ROOT"
}
trap cleanup EXIT

pass() {
  echo "  [PASS] $1"
}

fail() {
  echo "  [FAIL] $1"
  FAILURES=$((FAILURES + 1))
}

assert_contains() {
  local haystack="$1"
  local needle="$2"
  local description="$3"

  if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
    pass "$description"
  else
    fail "$description"
    echo "    expected to find: $needle"
    echo "    in:"
    printf '%s\n' "$haystack" | sed 's/^/      /'
  fi
}

assert_not_contains() {
  local haystack="$1"
  local needle="$2"
  local description="$3"

  if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
    fail "$description"
    echo "    did not expect to find: $needle"
    echo "    in:"
    printf '%s\n' "$haystack" | sed 's/^/      /'
  else
    pass "$description"
  fi
}

configure_git_identity() {
  local repo="$1"

  git -C "$repo" config user.name "Test Bot"
  git -C "$repo" config user.email "test@example.com"
}

write_stub_tool() {
  local path="$1"
  local name="$2"

  cat >"$path" <<EOF
#!/usr/bin/env bash
{
  printf '${name}:'
  for arg in "\$@"; do
    printf ' <%s>' "\$arg"
  done
  printf '\n'
} >> "\$SUPERPOWERS_SHELL_LINT_TEST_LOG"
exit 0
EOF
  chmod +x "$path"
}

make_fixture_repo() {
  local repo="$1"

  git init -q -b main "$repo"
  configure_git_identity "$repo"

  mkdir -p "$repo/hooks"
  cat >"$repo/tracked.sh" <<'EOF'
#!/usr/bin/env bash
echo "tracked"
EOF
  cat >"$repo/hooks/session-start" <<'EOF'
#!/bin/sh
echo "extensionless"
EOF
  cat >"$repo/README.md" <<'EOF'
# Fixture

```bash
echo "not a shell script"
```
EOF
  cat >"$repo/untracked.sh" <<'EOF'
#!/usr/bin/env bash
echo "untracked"
EOF

  git -C "$repo" add tracked.sh hooks/session-start README.md
  git -C "$repo" commit -q -m "fixture"

  printf '\necho "changed"\n' >>"$repo/tracked.sh"
  printf '\necho "changed extensionless"\n' >>"$repo/hooks/session-start"
}

run_lint_shell() {
  local repo="$1"
  local fakebin="$2"
  local log="$3"
  shift 3

  (
    cd "$repo"
    PATH="$fakebin:$PATH" \
      SUPERPOWERS_SHELL_LINT_TEST_LOG="$log" \
      bash "$SCRIPT_UNDER_TEST" "$@"
  )
}

echo "Shell lint script tests"

fixture="$TEST_ROOT/repo"
fakebin="$TEST_ROOT/bin"
log="$TEST_ROOT/tool.log"
mkdir -p "$fixture" "$fakebin"
: >"$log"
write_stub_tool "$fakebin/shellcheck" "shellcheck"
write_stub_tool "$fakebin/shfmt" "shfmt"
make_fixture_repo "$fixture"

if output="$(run_lint_shell "$fixture" "$fakebin" "$log" 2>&1)"; then
  pass "lint-shell check mode exits successfully with stub tools"
else
  fail "lint-shell check mode exits successfully with stub tools"
  printf '%s\n' "$output" | sed 's/^/      /'
fi

tool_log="$(cat "$log")"
assert_contains "$output" "Linting 3 shell files" "reports changed shell file count"
assert_not_contains "$tool_log" "shfmt:" "does not run shfmt in lint mode"
assert_contains "$tool_log" "shellcheck:" "runs ShellCheck"
assert_contains "$tool_log" "<--severity=warning>" "uses warning severity as the baseline"
assert_contains "$tool_log" "<--external-sources>" "allows ShellCheck to follow sourced files"
assert_contains "$tool_log" "<--source-path=SCRIPTDIR>" "resolves ShellCheck sources relative to each script"
assert_contains "$tool_log" "<hooks/session-start>" "includes changed extensionless shell shebang file"
assert_contains "$tool_log" "<tracked.sh>" "includes changed tracked .sh file"
assert_contains "$tool_log" "<untracked.sh>" "includes untracked shell files by default"
assert_not_contains "$tool_log" "README.md" "ignores Markdown with shell snippets"

: >"$log"
if output="$(run_lint_shell "$fixture" "$fakebin" "$log" --all --format 2>&1)"; then
  pass "lint-shell --format exits successfully with stub tools"
else
  fail "lint-shell --format exits successfully with stub tools"
  printf '%s\n' "$output" | sed 's/^/      /'
fi

tool_log="$(cat "$log")"
assert_contains "$tool_log" "<-w>" "uses shfmt write mode with --format"
assert_contains "$tool_log" "shellcheck:" "runs ShellCheck after --format"
assert_contains "$tool_log" "<--severity=warning>" "keeps warning severity after --format"
assert_contains "$tool_log" "<hooks/session-start>" "--all includes tracked extensionless shell shebang file"
assert_contains "$tool_log" "<tracked.sh>" "--all includes tracked .sh file"
assert_not_contains "$tool_log" "untracked.sh" "--all ignores untracked shell files"

if [[ "$FAILURES" -eq 0 ]]; then
  echo "All shell lint script tests passed"
else
  echo "$FAILURES shell lint script test(s) failed"
  exit 1
fi
tests/skill-size/test-skill-size.sh 32 řádků
#!/usr/bin/env bash
# Fails when any skill's SKILL.md reaches Claude Code's compaction cut.
#
# After a compaction, Claude Code re-attaches each invoked skill truncated to
# 20,000 characters (#2481). Anything past the cut is gone from the agent's
# context for the rest of the session unless it re-reads the file. Content a
# skill only needs sometimes belongs in references/, where the agent reads it
# fresh from disk at the step that needs it.
#
# Measures bytes, which is stricter than characters for files with non-ASCII
# text. Usage: tests/skill-size/test-skill-size.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
LIMIT=20000

failed=0
for skill in "$REPO_ROOT"/skills/*/SKILL.md; do
  size=$(wc -c <"$skill" | tr -d ' ')
  if ((size >= LIMIT)); then
    echo "FAIL: ${skill#"$REPO_ROOT"/} is $size bytes (limit: under $LIMIT)" >&2
    failed=1
  fi
done

if ((failed)); then
  echo "Move content the skill only needs sometimes into its references/ directory." >&2
  exit 1
fi
echo "PASS: every SKILL.md is under $LIMIT bytes"
tests/version-bump/test-bump-version.sh 90 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SCRIPT_SOURCE="$REPO_ROOT/scripts/bump-version.sh"
TEST_ROOT="$(mktemp -d)"

cleanup() {
  rm -rf "$TEST_ROOT"
}
trap cleanup EXIT

fail() {
  echo "FAIL: $*" >&2
  exit 1
}

make_fixture() {
  local repo="$1"
  local yaml_body="$2"

  mkdir -p "$repo/scripts" "$repo/.hermes-plugin"
  cp "$SCRIPT_SOURCE" "$repo/scripts/bump-version.sh"
  cat >"$repo/.version-bump.json" <<'JSON'
{
  "files": [
    { "path": "package.json", "field": "version" },
    { "path": ".hermes-plugin/plugin.yaml", "field": "version" }
  ],
  "audit": { "exclude": [] }
}
JSON
  cat >"$repo/package.json" <<'JSON'
{
  "name": "fixture",
  "version": "1.2.3"
}
JSON
  printf '%s\n' "$yaml_body" >"$repo/.hermes-plugin/plugin.yaml"
}

happy_repo="$TEST_ROOT/happy"
make_fixture "$happy_repo" $'name: superpowers\nversion: 1.2.3'

/bin/bash "$happy_repo/scripts/bump-version.sh" --check >"$TEST_ROOT/check.out"
/bin/bash "$happy_repo/scripts/bump-version.sh" --audit >"$TEST_ROOT/audit.out"
/bin/bash "$happy_repo/scripts/bump-version.sh" 2.3.4 >"$TEST_ROOT/bump.out"

[[ "$(jq -r '.version' "$happy_repo/package.json")" == "2.3.4" ]] \
  || fail "JSON manifest was not bumped"
[[ "$(yq -r '.version' "$happy_repo/.hermes-plugin/plugin.yaml")" == "2.3.4" ]] \
  || fail "YAML manifest was not bumped"

jq -e '
  any(.files[];
    .path == ".hermes-plugin/plugin.yaml" and .field == "version")
' "$REPO_ROOT/.version-bump.json" >/dev/null \
  || fail "Hermes manifest is not registered"

invalid_repo="$TEST_ROOT/invalid"
make_fixture "$invalid_repo" $'name: superpowers\nversion: 123'
cp "$invalid_repo/package.json" "$TEST_ROOT/package.before"
cp "$invalid_repo/.hermes-plugin/plugin.yaml" "$TEST_ROOT/plugin.before"

if /bin/bash "$invalid_repo/scripts/bump-version.sh" 2.3.4 \
  >"$TEST_ROOT/invalid.out" 2>&1; then
  fail "bump accepted a non-string YAML version"
fi

cmp -s "$TEST_ROOT/package.before" "$invalid_repo/package.json" \
  || fail "JSON manifest changed before YAML validation failed"
cmp -s "$TEST_ROOT/plugin.before" "$invalid_repo/.hermes-plugin/plugin.yaml" \
  || fail "invalid YAML manifest changed"

audit_repo="$TEST_ROOT/audit-boundaries"
make_fixture "$audit_repo" $'name: superpowers\nversion: 1.2.3'
/bin/bash "$audit_repo/scripts/bump-version.sh" 4.0.0 >/dev/null
printf 'host = "10.4.0.0"\n' >"$audit_repo/server.js"
printf 'pin: superpowers.git#v4.0.0\n' >"$audit_repo/INSTALL.md"
/bin/bash "$audit_repo/scripts/bump-version.sh" --audit >"$TEST_ROOT/audit-boundaries.out"

grep -q 'INSTALL.md' "$TEST_ROOT/audit-boundaries.out" \
  || fail "audit missed an undeclared #v4.0.0 pin"
if grep -q 'server.js' "$TEST_ROOT/audit-boundaries.out"; then
  fail "audit flagged 10.4.0.0 as version 4.0.0"
fi

echo "Version-bump tests passed"

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč lint test používá falešné nástroje?

Zajímá nás, jak skript nástroje volá (argumenty, výběr souborů), ne výsledek lintování. Stub zapíše volání do logu, takže test běží bez nainstalovaného ShellChecku a je deterministický.

2. Proč se rozpoznávají shell soubory podle shebangu?

Skripty jako hooks/session-start nemají příponu .sh. Bez kontroly shebangu by zůstaly nezlintované.

3. Proč lint ignoruje Markdown?

Markdown obsahuje ukázky shellu, které nejsou spustitelné skripty. ShellCheck by hlásil falešné chyby.

4. Proč limit 20 000 bajtů na SKILL.md?

Po compaction se skill znovu připojí zkrácený (issue #2481 uvádí 20 000 znaků; aktuální dokumentace Claude Code mluví o prvních 5 000 tokenech na skill a sdíleném rozpočtu 25 000 tokenů). Co je za řezem, agent ztratí, dokud soubor znovu nepřečte. Test vynucuje, aby se zřídka potřebný obsah přesunul do references/; je konzervativnější než dokumentace, což je bezpečné.

5. Proč se měří bajty a ne znaky?

Bajtů je u textu s nečeskými znaky víc než znaků. Měření bajtů je přísnější, takže je bezpečné (nikdy nepodhodnotí velikost).

6. Proč bump test kontroluje, že se nevalidní YAML odmítne bez změny souborů?

Bump mění víc souborů najednou. Pokud by selhal uprostřed, zůstaly by manifesty nekonzistentní. Test ověřuje, že se nejdřív validuje a teprve potom zapisuje (atomicita).

7. K čemu je `--audit` a proč test rozlišuje `#v4.0.0` a `10.4.0.0`?

Audit hledá nezmapované výskyty staré verze. Hraniční kontrola zabrání falešným nálezům, kde je verze jen součástí jiného čísla (IP adresa).

8. Proč `.version-bump.json` obsahuje i Hermes manifest?

Každý manifest s verzí musí být bumpnut najednou. Test hlídá, že přidaný Hermes manifest nezůstal mimo seznam.

9. Proč se skripty spouští přes `/bin/bash`?

Ověření funguje i se starším bashem (macOS), ne jen s moderní verzí z PATH.

10. Je limit 20 000 bajtů v testu pořád aktuální vůči dokumentaci Claude Code?

Je to konzervativní odhad. Dokumentace dnes udává 5 000 tokenů na skill po compaction a 25 000 tokenů sdíleně pro všechny znovu připojené skills; 20 000 bajtů češtiny či angličtiny je řádově kolem tohoto rozsahu a navíc dokumentace doporučuje držet SKILL.md pod 500 řádky. Pro přesnější kontrolu by se hodilo měřit i řádky a odhad tokenů. Změnu hodnoty ale AGENTS.md ponechává maintainerovi.

Slovník pojmů (11)

ShellCheck

Statický analyzátor shell skriptů.

shfmt

Formátovač shell skriptů.

Stub tool

Falešný nástroj zapisující svá volání do logu.

Shebang

Řádek #!/usr/bin/env bash určující interpret.

`--severity=warning`

Základní úroveň závažnosti pro ShellCheck.

`--source-path=SCRIPTDIR`

Hledání zdrojovaných souborů relativně ke skriptu.

Compaction cut

Limit 20 000 znaků, na který se skill po compaction zkrátí.

`references/`

Adresář pro obsah načítaný jen při potřebě.

`.version-bump.json`

Seznam souborů a polí s verzí, které se bumpují společně.

Version audit

Hledání nezmapovaných výskytů verze.

Atomic bump

Změna se provede celá, nebo vůbec.

↑ nahoru

Testy nástrojů skills: struktura diagnosing, find-polluter a render-graphs

Testy struktury skillu diagnosing-superpowers, skriptu find-polluter.sh (issue #2008) a render-graphs.js (ESM, chybějící Graphviz).

test-skill-structure.sh kontroluje, co jde ověřit shellem u skillu diagnosing-superpowers (chování testují eval scénáře): SKILL.md existuje, frontmatter jméno je správné, popis začíná „Use when“, má méně než 1024 znaků a nepoužívá workflow slova, tělo je v rozpočtu slov, obsahuje požadované sekce, odkazované soubory existují a do dodaných souborů neprosákly lokální cesty ani jména.

test-find-polluter.sh testuje skript bisekce: dokumentovaný vzor src/**/*.test.ts najde vnořené i top-level testy (regrese issue #2008), spustí je, detekuje „FOUND POLLUTER“, a vzor s úvodním ./ dá stejné soubory. test-render-graphs.sh ověřuje render-graphs.js: při chybějícím Graphviz skončí nenulově s instalační hláškou a ne s chybou „require is not defined“ (skript běží jako ES modul), fixture diagram se vykreslí a skript ohlásí „Found 1 diagram(s)“. Testy používají prázdný PATH a skutečnou cestu k Node, protože shimy správců verzí (mise, asdf) by Node pod prázdným PATH nenašly.

Zdrojový kód

tests/diagnosing-superpowers/test-skill-structure.sh 152 řádků
#!/usr/bin/env bash
# Structural checks for skills/diagnosing-superpowers. Behavior is tested by
# scenario evals kept by the maintainer; this script only checks the things a
# shell can check: frontmatter, referenced files exist, no local paths or
# names leaked into shipped files, SKILL.md word budget.
set -u

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SKILL_DIR="$REPO_ROOT/skills/diagnosing-superpowers"
SKILL_MD="$SKILL_DIR/SKILL.md"
WORD_BUDGET=1000

PASSES=0
FAILURES=0

pass() { echo "  [PASS] $1"; PASSES=$((PASSES + 1)); }
fail() { echo "  [FAIL] $1"; FAILURES=$((FAILURES + 1)); }

echo "diagnosing-superpowers structure"

# --- SKILL.md frontmatter -------------------------------------------------
if [ -f "$SKILL_MD" ]; then
  pass "SKILL.md exists"
  frontmatter="$(awk 'NR==1 && $0!="---"{exit} NR>1 && $0=="---"{exit} NR>1{print}' "$SKILL_MD")"
  if printf '%s\n' "$frontmatter" | grep -q '^name: diagnosing-superpowers$'; then
    pass "frontmatter name is diagnosing-superpowers"
  else
    fail "frontmatter name is diagnosing-superpowers"
  fi
  description="$(printf '%s\n' "$frontmatter" | awk '/^description:/{sub(/^description:[ ]*/,""); print; found=1; next} found && /^[ ]/{print} found && !/^[ ]/{exit}' | tr '\n' ' ')"
  if printf '%s' "$description" | grep -q '^Use when'; then
    pass "description starts with 'Use when'"
  else
    fail "description starts with 'Use when' (got: ${description:0:60})"
  fi
  if [ "${#description}" -le 1024 ]; then
    pass "description under 1024 characters"
  else
    fail "description under 1024 characters (${#description})"
  fi
  for banned in "dispatch" "then" "step"; do
    if printf '%s' "$description" | grep -qiw "$banned"; then
      fail "description contains workflow word '$banned'"
    else
      pass "description avoids workflow word '$banned'"
    fi
  done

  # --- word budget --------------------------------------------------------
  body_words="$(awk 'BEGIN{fm=0} NR==1 && $0=="---"{fm=1; next} fm==1 && $0=="---"{fm=2; next} fm==2{print}' "$SKILL_MD" | wc -w | tr -d ' ')"
  if [ "$body_words" -le "$WORD_BUDGET" ]; then
    pass "SKILL.md body within $WORD_BUDGET words ($body_words)"
  else
    fail "SKILL.md body within $WORD_BUDGET words ($body_words)"
  fi

  # --- required sections --------------------------------------------------
  for heading in "## Hard rules" "## Red Flags"; do
    if grep -q "^$heading" "$SKILL_MD"; then
      pass "SKILL.md has section '$heading'"
    else
      fail "SKILL.md has section '$heading'"
    fi
  done

  # --- every referenced skill file exists --------------------------------
  while IFS= read -r ref; do
    if [ -f "$SKILL_DIR/$ref" ]; then
      pass "referenced file exists: $ref"
    else
      fail "referenced file exists: $ref"
    fi
  done < <(grep -o '\(references\|prompts\|templates\)/[A-Za-z0-9._-]*\.md' "$SKILL_MD" | sort -u)
else
  fail "SKILL.md exists"
fi

# --- expected files -------------------------------------------------------
expected_files=(
  references/redaction-policy.md
  references/session-discovery.md
  references/context-safety.md
  references/github-issues.md
  prompts/analyst-common.md
  prompts/skill-timeline.md
  prompts/plan-adherence.md
  prompts/repeated-work.md
  prompts/stumbles.md
  prompts/quality-evidence.md
  prompts/request-conflicts.md
  prompts/cost-and-time.md
  prompts/scrub.md
  prompts/scrub-audit.md
  prompts/similar-session.md
  templates/case.md
  templates/report.md
  templates/bundle-README.md
  templates/issue.md
)
for rel in "${expected_files[@]}"; do
  if [ -f "$SKILL_DIR/$rel" ]; then
    pass "expected file present: $rel"
  else
    fail "expected file present: $rel"
  fi
done

# --- removed harness recipes stay removed --------------------------------
removed_files=(
  references/claude-code-sessions.md
  references/codex-sessions.md
  references/other-harnesses.md
)
for rel in "${removed_files[@]}"; do
  if [ ! -e "$SKILL_DIR/$rel" ]; then
    pass "removed reference absent: $rel"
  else
    fail "removed reference absent: $rel"
  fi
done

removed_reference_hits="$(grep -rn -E 'references/(claude-code-sessions|codex-sessions|other-harnesses)\.md' "$SKILL_DIR" --include='*.md' 2>/dev/null || true)"
if [ -z "$removed_reference_hits" ]; then
  pass "active skill prose has no references to removed harness recipes"
else
  fail "active skill prose has no references to removed harness recipes"
  printf '%s\n' "$removed_reference_hits" | head -10 | sed 's/^/    /'
fi

# --- no local paths or names in shipped files ----------------------------
leaks="$(grep -rn -E '/Users/|/home/|jesse' "$SKILL_DIR" "$SCRIPT_DIR" --exclude=test-skill-structure.sh 2>/dev/null || true)"
if [ -z "$leaks" ]; then
  pass "no machine-specific paths or names in shipped files (skills + tests)"
else
  fail "no machine-specific paths or names in shipped files (skills + tests)"
  printf '%s\n' "$leaks" | head -10 | sed 's/^/    /'
fi

# --- "the user" never appears in skill prose -----------------------------
user_hits="$(grep -rn -i 'the user' "$SKILL_DIR" --include='*.md' 2>/dev/null || true)"
if [ -z "$user_hits" ]; then
  pass "skill files say 'your human partner', not 'the user'"
else
  fail "skill files say 'your human partner', not 'the user'"
  printf '%s\n' "$user_hits" | head -10 | sed 's/^/    /'
fi

echo
echo "Passed: $PASSES  Failed: $FAILURES"
[ "$FAILURES" -eq 0 ]
tests/systematic-debugging/test-find-polluter.sh 91 řádků
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SCRIPT_UNDER_TEST="$REPO_ROOT/skills/systematic-debugging/find-polluter.sh"

FAILURES=0
TEST_ROOT="$(mktemp -d)"

cleanup() {
  rm -rf "$TEST_ROOT"
}
trap cleanup EXIT

pass() {
  echo "  [PASS] $1"
}

fail() {
  echo "  [FAIL] $1"
  FAILURES=$((FAILURES + 1))
}

assert_contains() {
  local haystack="$1"
  local needle="$2"
  local description="$3"

  if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
    pass "$description"
  else
    fail "$description (expected output to contain: $needle)"
  fi
}

# Toy project: one top-level test, one nested test. A stubbed `npm` on PATH
# creates the pollution marker whenever any test runs, so the first test file
# executed is always identified as the polluter.
setup_project() {
  PROJECT="$TEST_ROOT/project"
  rm -rf "$PROJECT"
  mkdir -p "$PROJECT/src/feature" "$PROJECT/bin"
  echo "test('top')" > "$PROJECT/src/top.test.ts"
  echo "test('nested')" > "$PROJECT/src/feature/nested.test.ts"
  cat > "$PROJECT/bin/npm" <<'EOF'
#!/usr/bin/env bash
touch pollution.marker
EOF
  chmod +x "$PROJECT/bin/npm"
}

# run_polluter <pattern> — runs the script in the toy project with the stub
# npm first on PATH; captures combined output, never aborts on exit code.
run_polluter() {
  local pattern="$1"
  rm -f "$PROJECT/pollution.marker"
  (
    cd "$PROJECT"
    PATH="$PROJECT/bin:$PATH" "$SCRIPT_UNDER_TEST" 'pollution.marker' "$pattern" 2>&1
  ) || true
}

echo "Test: documented pattern finds nested test files (issue #2008)"
setup_project
OUTPUT="$(run_polluter 'src/**/*.test.ts')"
assert_contains "$OUTPUT" "FOUND POLLUTER" "documented pattern runs tests and detects pollution"

echo "Test: documented pattern also finds top-level test files"
setup_project
OUTPUT="$(run_polluter 'src/**/*.test.ts')"
assert_contains "$OUTPUT" "Found 2 test files" "src/**/*.test.ts matches src/top.test.ts and src/feature/nested.test.ts"

echo "Test: ./-prefixed pattern matches the same files"
setup_project
OUTPUT="$(run_polluter './src/**/*.test.ts')"
assert_contains "$OUTPUT" "Found 2 test files" "leading ./ on the pattern is accepted"

echo "Test: non-matching pattern reports an honest zero"
setup_project
OUTPUT="$(run_polluter 'nomatch/**/*.test.ts')"
assert_contains "$OUTPUT" "Found 0 test files" "empty result counts as 0, not 1"
assert_contains "$OUTPUT" "No polluter found" "empty result exits via the clean path"

echo ""
if [ "$FAILURES" -gt 0 ]; then
  echo "$FAILURES test(s) failed"
  exit 1
fi
echo "All tests passed"
tests/writing-skills/test-render-graphs.sh 116 řádků
#!/usr/bin/env bash
set -u

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SCRIPT_UNDER_TEST="$REPO_ROOT/skills/writing-skills/render-graphs.js"
# Resolve the real binary: version-manager shims (mise, asdf) can't find node
# under the empty PATH used for the missing-Graphviz case.
NODE_BIN="$(node -p 'process.execPath')"

PASSES=0
FAILURES=0
TEST_ROOT="$(mktemp -d)"

cleanup() {
  rm -rf "$TEST_ROOT"
}
trap cleanup EXIT

pass() {
  echo "  [PASS] $1"
  PASSES=$((PASSES + 1))
}

fail() {
  echo "  [FAIL] $1"
  FAILURES=$((FAILURES + 1))
}

assert_contains() {
  local haystack="$1"
  local needle="$2"
  local description="$3"

  if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
    pass "$description"
  else
    fail "$description"
    echo "    expected to find: $needle"
  fi
}

assert_not_contains() {
  local haystack="$1"
  local needle="$2"
  local description="$3"

  if printf '%s' "$haystack" | grep -Fq -- "$needle"; then
    fail "$description"
    echo "    did not expect to find: $needle"
  else
    pass "$description"
  fi
}

fixture="$TEST_ROOT/fixture-skill"
mkdir -p "$fixture" "$TEST_ROOT/empty-path"
cat >"$fixture/SKILL.md" <<'EOF'
---
name: fixture-skill
---

# Fixture Skill

```dot
digraph fixture_graph {
  start -> end;
}
```
EOF

echo "Writing-skills render-graphs tests"

missing_dot_output="$(PATH="$TEST_ROOT/empty-path" "$NODE_BIN" "$SCRIPT_UNDER_TEST" "$fixture" 2>&1)"
missing_dot_status=$?

if [[ "$missing_dot_status" -ne 0 ]]; then
  pass "missing Graphviz exits non-zero"
else
  fail "missing Graphviz exits non-zero"
fi
assert_contains "$missing_dot_output" "Error: graphviz (dot) not found." "missing Graphviz reports install guidance"
assert_not_contains "$missing_dot_output" "ReferenceError: require is not defined" "script runs as an ES module"

render_output="$("$NODE_BIN" "$SCRIPT_UNDER_TEST" "$fixture" 2>&1)"
render_status=$?

if [[ "$render_status" -eq 0 ]]; then
  pass "fixture diagram renders"
else
  fail "fixture diagram renders"
  printf '%s\n' "$render_output"
fi

assert_contains "$render_output" "Found 1 diagram(s)" "reports discovered diagram"
assert_contains "$render_output" "Rendered: fixture_graph.svg" "reports rendered SVG"

if [[ -f "$fixture/diagrams/fixture_graph.svg" ]]; then
  pass "writes SVG output"
else
  fail "writes SVG output"
fi

if [[ -f "$fixture/diagrams/fixture_graph.svg" ]] && grep -Fq "<svg" "$fixture/diagrams/fixture_graph.svg"; then
  pass "SVG output has SVG markup"
else
  fail "SVG output has SVG markup"
fi

echo
echo "Results: $PASSES passed, $FAILURES failed"

if [[ "$FAILURES" -gt 0 ]]; then
  exit 1
fi

Kvíz (10 otázek, odpověď se rozbalí kliknutím)

1. Proč popis skillu musí začínat „Use when“?

Popis je spouštěč: agent podle něj rozhoduje, kdy skill použít. Formulace „Use when…“ popisuje situaci, ne obsah, takže agent skill správně vybere. Popis shrnující workflow by agent mohl přečíst místo celého skillu.

2. Proč limit 1024 znaků v popisu?

Popisy všech skills jsou stále v kontextu. Dlouhý popis zabírá místo u každé session. Limit drží kontext malý.

3. Proč test kontroluje, že do shipped souborů neprosákly lokální cesty a jména?

Skill se distribuuje veřejně. Cesta typu /home/uživatel/... nebo jméno z lokálního testu by byl únik soukromých dat.

4. Co byla regrese #2008 ve find-polluteru?

Vzor src/**/.test.ts nenašel soubory přímo v src/, protože find -path neumí */ s nulovou hloubkou. Test ověřuje, že se najdou oba (src/top.test.ts i src/feature/nested.test.ts).

5. Proč se render-graphs testuje s prázdným PATH?

Simuluje stroj bez Graphviz a ověřuje chybovou hlášku. Proto je nutné Node volat absolutní cestou.

6. Proč test hledá, že se NEobjeví „require is not defined“?

Balíček je ES modul a require v něm neexistuje. Chyba by značila, že skript byl napsán v CommonJS stylu a na Windows nebo s novým Node by padl.

7. Proč se kontroluje „Found 1 diagram(s)“?

Potvrzuje, že extrakce ```dot bloků funguje na fixture a že výstup je srozumitelný.

8. Proč strukturální test nezkouší chování skillu?

Chování závisí na LLM a testují ho drahé eval scénáře. Shell kontroluje jen deterministické věci (soubory, frontmatter, rozpočet).

9. Proč rozpočet slov těla SKILL.md?

Dlouhý skill zabírá kontext a hůře přežije compaction. Slovní limit udržuje skill stručný.

10. Proč test hlídá popis pod 1024 znaků, když dokumentace Claude Code zkracuje výpis až na 1 536?

Limit 1 024 znaků pochází ze standardu Agent Skills, který používají i jiné harnessy (Codex, Cursor, Gemini a další). Skill distribuovaný pro více platforem se musí vejít do nejpřísnějšího z nich. Claude Code samotný má limit volnější (description + when_to_use do 1 536 znaků ve výpisu).

Slovník pojmů (10)

Structural test

Test souborů a metadat, ne chování.

Frontmatter

YAML metadata (name, description) na začátku SKILL.md.

Description budget

Limit 1024 znaků popisu skillu.

Word budget

Maximální počet slov těla skillu.

Leak check

Kontrola, že dodané soubory neobsahují lokální cesty a jména.

Polluter

Test vytvářející nechtěný stav (find-polluter).

Issue #2008

Regrese: vzor **/ minul soubory v základním adresáři.

ESM

ECMAScript moduly; import místo require.

Graphviz `dot`

Nástroj pro vykreslení diagramů.

Version-manager shim

Zástupný spustitelný soubor (mise, asdf), který pod prázdným PATH nefunguje.

↑ nahoru

Shrnutí a audit

Generováno skriptem site/build-tutorial.mjs. Needituj ručně.