Praktický tutoriál gstack
Devět příkladů z repozitáře gstack — od browser skillu přes dokumentaci, release a iOS QA až po praktické používání AI. U každého je podrobný popis, zdrojový kód, kvíz se skrytými odpověďmi a slovník pojmů.
Úvod
gstack („Garry's Stack“) je sada skills pro Claude Code — slash příkazů, které z agenta dělají tým rolí (review, QA, release, plánování) — spolu s rychlým headless prohlížečem. Tento tutoriál nevysvětluje všechno; bere devět konkrétních příkladů a u každého ukazuje, jak funguje, proč je to dobré řešení a proč je bezpečné.
Tutoriál je jeden soubor: nepotřebuje internet ani jiné soubory. Obsah se generuje příkazem bun site/build-tutorial.ts ze stejných dat jako běžící dokumentační portál.
Spuštění
Na hostiteli nemusí být Bun ani Node — vše běží v Dockeru.
- Spusťte kontejnery:
docker compose up -d --build
- Otevřete portál na
http://localhost:8080(dostupný jen z tohoto počítače). - Příkazy spouštějte v kontejneru
dev-t372:docker compose exec dev bun run typecheck docker compose exec dev bun test test/site-portal.test.ts
- Znovu vygenerujte tento tutoriál:
docker compose exec dev bun site/build-tutorial.ts
- Úklid:
docker compose down
Bezpečnost portálu. Kontejner web-t372 má repozitář připojený jen pro čtení, shozená oprávnění, health check a port vázaný na 127.0.0.1. Portál nikdy neservíruje .git, node_modules, .gstack ani soubory .env* a posílá CSP script-src 'self'.
Jak se učit
- Přečtěte popis příkladu — co dělá a proč je řešení navržené právě takhle.
- Projděte zdrojový kód. Čísla řádků pomáhají orientaci; první soubor je rozbalený.
- Zodpovězte kvíz. Odpověď si nejdřív promyslete a pak ji odkryjte kliknutím; tlačítko „Odkrýt vše“ slouží ke kontrole.
- Projděte slovník pojmů. Každý pojem je vysvětlený v kontextu právě tohoto příkladu.
Mapa příkladů
| # | Příklad | Oblast | Otázek | Pojmů |
|---|---|---|---|---|
| 1 | Browser skill: Hacker News front page | Browser skills | 15 | 16 |
| 2 | Tutorial: dokumentace funkce za 90 sekund | Dokumentace · /document-generate | 14 | 16 |
| 3 | How-to: první produkční deploy | Release · /setup-deploy a /land-and-deploy | 15 | 16 |
| 4 | How-to: diagramy v dokumentech a export mimo PDF | Dokumenty · /make-pdf a /diagram | 15 | 16 |
| 5 | How-to: zdokumentovat funkci před vydáním | Dokumentace · /document-release a /document-generate | 14 | 16 |
| 6 | How-to: testování iOS aplikací (GStack iOS) | iOS QA · /ios-qa a /ios-clean | 16 | 16 |
| 7 | QA bez webové stránky (CLI, API, joby, webhooky) | Testování · /qa a /qa-only | 14 | 16 |
| 8 | GBrain s gstackem: rychlá prohlídka | Paměť a vyhledávání · /setup-gbrain a /sync-gbrain | 14 | 16 |
| 9 | Praktické používání AI: skills, modely, rozpočet a triky | Závěrečný díl · praxe s Claude Code a gstackem | 15 | 16 |
Browser skill: Hacker News front page
Referenční browser skill, který z titulní stránky Hacker News vytáhne 30 příběhů jako JSON — s parserem, který se testuje bez sítě a bez prohlížeče.
Popis
Co příklad dělá
hackernews-frontpage je nejmenší „zajímavý“ browser skill v gstacku. Jedním příkazem ($B skill run hackernews-frontpage) otevře news.ycombinator.com, přečte HTML stránky a vypíše na stdout jediný JSON dokument ve tvaru { "stories": [...], "count": N }. Každý příběh má rank, id, title, url, points a comments.
Příklad je v repozitáři záměrně jako referenční skill: nemá přihlašování, HTML je stabilní, výstup je deterministický a dá se otestovat nad uloženým souborem. Díky tomu na něm lze ukázat všechny součásti browser-skills systému najednou.
Jak je příklad složený
| Soubor | Role |
|---|---|
SKILL.md | Manifest: name, description, host, trusted, source, version, args, triggers. Podle něj skill najde a spustí $B skill run. |
script.ts | Vlastní logika. Čistá funkce parseStoriesFromHtml(html) + main(), který jen zavolá browse.goto, browse.html a vypíše JSON. |
_lib/browse-client.ts | Malý SDK, který mluví s démonem prohlížeče přes loopback HTTP (POST /command). Každý skill má vlastní kopii. |
script.test.ts | Testy parseru proti uloženému HTML. Žádný démon, žádná síť. |
fixtures/hn-2026-04-26.html | Zmražený výřez titulní stránky: 5 příběhů, z toho jeden job posting a jeden s „discuss“. |
Jak to funguje krok za krokem
- Spuštění.
$B skill runspustíscript.tsjako podproces a předá mu v prostředíGSTACK_PORTaGSTACK_SKILL_TOKEN— scoped token platný jen po dobu tohoto spuštění. - Navigace.
main()zavolábrowse.goto('https://news.ycombinator.com/'). SDK pošle příkaz démonu na127.0.0.1s tokenem v hlavičce. - Čtení HTML.
browse.html()vrátí zdrojový kód stránky jako řetězec. - Parsování.
parseStoriesFromHtmlnajde regulárním výrazem každý řádektr.athing, z něj vytáhne odkaz vspan.titlelinea potom v následujícím „subtext“ řádku skóre a počet komentářů. - Výstup. Skript zapíše
JSON.stringify(output)na stdout a skončí s kódem 0. Při chybě skončí nenulovým kódem.
Proč je parser napsaný právě takhle
- Čistá funkce, exportovaná zvlášť.
parseStoriesFromHtmlnic nečte ze sítě ani z disku, jen mění string na pole. Proto jde testovat okamžitě a opakovatelně.main()je navíc chráněnéif (import.meta.main), takže import z testu skript nespustí. - Ohraničený lookahead. Skóre a komentáře se hledají jen v úseku od konce řádku příběhu po nejbližší
tr.spacernebo dalšítr.athing. Bez toho by u job postingu (který nemá vlastní skóre) „vyteklo“ skóre následujícího příběhu. Přesně tuhle chybu hlídá test s job postingem. nullmísto vymyšlené hodnoty. Job posting nemá points ani comments, proto jsou typynumber | null. Odkaz „discuss“ se záměrně počítá jako0komentářů.- Dekódování entit.
&,",'… se převedou zpět, aby titulek a URL byly skutečný text (quantum&chess). - Nevymýšlí si. Řádek
tr.athingbeztitlelinese přeskočí, prázdné nebo nesouvisející HTML vrátí[].
Bezpečnostní model
Skill běží s scoped tokenem (jen čtení a zápis příkazů, platnost končí s procesem). SDK nepřidává žádné nové schopnosti — používá jen existující HTTP povrch démona. Démon poslouchá výhradně na 127.0.0.1, takže ho zvenku nikdo nezavolá. Při ručním ladění (bun run script.ts) se použije root token ze stavového souboru .gstack/browse.json — to je vaše vlastní oprávnění, ne oprávnění agenta.
Proč je to dobrý a bezpečný vzor
Po změně HTML na Hacker News selže test nad zmraženou fixture dřív, než si toho všimne uživatel. Rozbitý parser je tak zachycen v CI, ne v produkci. A protože skill je samostatný adresář s vlastní kopií SDK, dá se zkopírovat kamkoli a poběží stejně — žádný drift verzí, žádný globální balíček.
Zdrojový kód 5
browser-skills/hackernews-frontpage/SKILL.md52 řádků
---name: hackernews-frontpagedescription: Scrape the Hacker News front page (titles, points, comment counts).host: news.ycombinator.comtrusted: truesource: humanversion: 1.0.0args: []triggers: - scrape hacker news frontpage - scrape hn frontpage - get hn top stories - latest hacker news stories---# Hacker News front-page scraperScrapes the Hacker News (`news.ycombinator.com`) front page and returns thetop 30 stories as JSON. Each story has its rank, title, link URL, point count,and comment count.## Usage```$ $B skill run hackernews-frontpage{ "stories": [ { "rank": 1, "title": "...", "url": "...", "points": 412, "comments": 87 }, ... ], "count": 30}```## How it works1. Navigates to `https://news.ycombinator.com` via the daemon.2. Reads the page HTML.3. Parses each story row (HN's stable `tr.athing` structure) into a typed `Story` record.4. Emits a single JSON document on stdout.## Why this is the reference skill`hackernews-frontpage` is the smallest interesting browser-skill: no auth,stable HTML, deterministic output, file-fixture-friendly. Every Phase 1component (SDK, scoped tokens, three-tier lookup, spawn lifecycle) isexercised by `$B skill run hackernews-frontpage` and the bundled`script.test.ts`.When the HN HTML rotates and our selectors break, the test fails against thecaptured fixture before users notice. That's the point.
browser-skills/hackernews-frontpage/script.ts132 řádků
/** * hackernews-frontpage — scrape the HN front page and emit JSON. * * Output protocol: * stdout = a single JSON document on success: { stories: Story[], count } * stderr = anything we want logged (currently nothing) * exit 0 on success, nonzero on parse / network failure. * * The parser logic (`parseStoriesFromHtml`) is exported so script.test.ts can * exercise it against bundled HTML fixtures without spinning up the daemon. */import { browse } from './_lib/browse-client';export interface Story { /** 1-based rank as displayed on HN. */ rank: number; /** HN item id (the integer in `tr.athing[id]`). */ id: string; title: string; /** Outbound URL the title links to. */ url: string; /** null when the row has no score (job postings). */ points: number | null; /** null when the row has no comments link (job postings). */ comments: number | null;}export interface Output { stories: Story[]; count: number;}const FRONT_PAGE_URL = 'https://news.ycombinator.com/';/** * Parse HN front-page HTML into Story[]. * * HN's structure is stable: each story is a pair of rows. * <tr class="athing submission" id="<itemid>"> * <td class="rank">N.</td> * <td class="title">...</td> * <td class="title"><span class="titleline"><a href="<url>">title</a> ...</span></td> * </tr> * <tr><td colspan="2"></td><td class="subtext"><span class="subline"> * <span class="score" id="score_<itemid>">N points</span> * ... <a href="item?id=<itemid>">N comments</a> * </span></td></tr> * * Job postings ("Foo (YC X25) is hiring...") omit the score and comments — * those fields come back as null. */export function parseStoriesFromHtml(html: string): Story[] { const stories: Story[] = []; // Match each `tr.athing` row, capturing the id attribute and the row body. const rowRegex = /<tr\s+[^>]*\bclass="athing[^"]*"[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/tr>/g; let match: RegExpExecArray | null; let rank = 0; while ((match = rowRegex.exec(html)) !== null) { rank++; const id = match[1]; const rowBody = match[2]; // Title link: <span class="titleline"><a href="..." ...>title</a> const titleMatch = rowBody.match(/<span\s+class="titleline"[^>]*>\s*<a\s+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/); if (!titleMatch) continue; const url = decodeHtmlEntities(titleMatch[1]); const title = stripTags(decodeHtmlEntities(titleMatch[2])).trim(); // The next sibling tr should hold the subtext row. Bound the lookahead // to before the next story (tr.spacer marks the gap, then tr.athing). // Bug if we don't bound: the score from story N+1 leaks into story N // when story N is a job posting (no score of its own). const subtextStart = match.index + match[0].length; const tail = html.slice(subtextStart); const spacerIdx = tail.search(/<tr\b[^>]*\bclass="spacer\b/); const nextAthingIdx = tail.search(/<tr\b[^>]*\bclass="athing\b/); const candidates = [spacerIdx, nextAthingIdx].filter(i => i >= 0); const boundary = candidates.length > 0 ? Math.min(...candidates) : tail.length; const subtextSlice = tail.slice(0, boundary); let points: number | null = null; let comments: number | null = null; const scoreMatch = subtextSlice.match(/<span\s+class="score"[^>]*>(\d+)\s*points?<\/span>/); if (scoreMatch) points = parseInt(scoreMatch[1], 10); // Comment count: an anchor like `<a href="item?id=...">N comments</a>`, // or `discuss` (treated as 0). Skip "hide" / "context" / "from" links. const commentsMatch = subtextSlice.match(/<a\s+href="item\?id=\d+"[^>]*>(\d+)\s*(?: )?\s*comments?<\/a>/); if (commentsMatch) { comments = parseInt(commentsMatch[1], 10); } else if (/discuss<\/a>/.test(subtextSlice)) { comments = 0; } stories.push({ rank, id, title, url, points, comments }); } return stories;}function stripTags(s: string): string { return s.replace(/<[^>]*>/g, '');}function decodeHtmlEntities(s: string): string { return s .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, "'") .replace(/'/g, "'") .replace(/</g, '<') .replace(/>/g, '>') .replace(/ /g, ' ');}// ─── Main entry (only when run as a script, not when imported by tests) ─if (import.meta.main) { await main();}async function main(): Promise<void> { await browse.goto(FRONT_PAGE_URL); const html = await browse.html(); const stories = parseStoriesFromHtml(html); const output: Output = { stories, count: stories.length }; process.stdout.write(JSON.stringify(output) + '\n');}
browser-skills/hackernews-frontpage/script.test.ts105 řádků
/** * hackernews-frontpage script tests — exercise parseStoriesFromHtml against * the bundled HN fixture. No daemon, no network: the parser is a pure function * over HTML, so we test it directly. */import { describe, it, expect } from 'bun:test';import * as fs from 'fs';import * as path from 'path';import { parseStoriesFromHtml } from './script';const FIXTURE = fs.readFileSync( path.join(__dirname, 'fixtures', 'hn-2026-04-26.html'), 'utf-8',);describe('parseStoriesFromHtml against bundled HN fixture', () => { it('returns 5 stories (matching the fixture)', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories).toHaveLength(5); }); it('assigns 1-based ranks in document order', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories.map(s => s.rank)).toEqual([1, 2, 3, 4, 5]); }); it('extracts ids matching the tr.athing[id] attribute', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories.map(s => s.id)).toEqual([ '40000001', '40000002', '40000003', '40000004', '40000005', ]); }); it('extracts titles and decodes HTML entities', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories[0].title).toBe('Show HN: A toy compiler in 200 lines'); expect(stories[1].title).toBe('Database internals: writing an LSM tree'); expect(stories[3].title).toBe("Ask HN: What's your most underrated tool?"); expect(stories[4].title).toBe('Why quantum & chess engines disagree'); }); it('extracts URLs and decodes ampersands', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories[0].url).toBe('https://example.com/blog-post-1'); expect(stories[1].url).toBe('https://example.org/database-internals'); expect(stories[4].url).toBe('https://example.io/quantum&chess'); }); it('parses point counts as numbers', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories[0].points).toBe(412); expect(stories[1].points).toBe(298); expect(stories[3].points).toBe(156); expect(stories[4].points).toBe(73); }); it('parses comment counts as numbers', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories[0].comments).toBe(87); expect(stories[1].comments).toBe(152); expect(stories[4].comments).toBe(12); }); it('treats "discuss" links as 0 comments', () => { const stories = parseStoriesFromHtml(FIXTURE); expect(stories[3].comments).toBe(0); }); it('returns null points + null comments for job postings', () => { const stories = parseStoriesFromHtml(FIXTURE); // Story #3 is the YC-hiring row in the fixture. expect(stories[2].title).toContain('YC W26'); expect(stories[2].points).toBeNull(); expect(stories[2].comments).toBeNull(); }); it('returns [] for empty HTML', () => { expect(parseStoriesFromHtml('')).toEqual([]); }); it('returns [] for HTML with no story rows', () => { expect(parseStoriesFromHtml('<html><body><p>nothing here</p></body></html>')).toEqual([]); }); it('does not fabricate stories from arbitrary tr.athing rows missing titleline', () => { const html = '<tr class="athing" id="999"><td>nothing</td></tr>'; expect(parseStoriesFromHtml(html)).toEqual([]); });});describe('output shape', () => { it('every story has all required keys', () => { const stories = parseStoriesFromHtml(FIXTURE); for (const s of stories) { expect(typeof s.rank).toBe('number'); expect(typeof s.id).toBe('string'); expect(typeof s.title).toBe('string'); expect(typeof s.url).toBe('string'); // points/comments may be null for job rows expect(s.points === null || typeof s.points === 'number').toBe(true); expect(s.comments === null || typeof s.comments === 'number').toBe(true); } });});
browser-skills/hackernews-frontpage/fixtures/hn-2026-04-26.html52 řádků
<!DOCTYPE html><html lang="en" op="news"><head><meta charset="utf-8"><title>Hacker News</title></head><body><center><table id="hnmain" border="0" cellpadding="0" cellspacing="0" width="85%" bgcolor="#f6f6ef"><tr><td><table border="0" cellpadding="0" cellspacing="0" class="itemlist"><tr class="athing submission" id="40000001"> <td align="right" valign="top" class="title"><span class="rank">1.</span></td> <td valign="top" class="votelinks"><center><a id="up_40000001" href="vote?id=40000001"><div class="votearrow" title="upvote"></div></a></center></td> <td class="title"><span class="titleline"><a href="https://example.com/blog-post-1" rel="noreferrer">Show HN: A toy compiler in 200 lines</a> <span class="sitebit comhead"> (<a href="from?site=example.com"><span class="sitestr">example.com</span></a>)</span></span></td></tr><tr><td colspan="2"></td><td class="subtext"><span class="subline"> <span class="score" id="score_40000001">412 points</span> by <a href="user?id=alice" class="hnuser">alice</a> <span class="age" title="2026-04-26T08:15:00"><a href="item?id=40000001">3 hours ago</a></span> <span id="unv_40000001"></span> | <a href="hide?id=40000001&goto=news">hide</a> | <a href="item?id=40000001">87 comments</a> </span></td></tr><tr class="spacer" style="height:5px"></tr><tr class="athing submission" id="40000002"> <td align="right" valign="top" class="title"><span class="rank">2.</span></td> <td valign="top" class="votelinks"><center><a id="up_40000002" href="vote?id=40000002"><div class="votearrow" title="upvote"></div></a></center></td> <td class="title"><span class="titleline"><a href="https://example.org/database-internals" rel="noreferrer">Database internals: writing an LSM tree</a> <span class="sitebit comhead"> (<a href="from?site=example.org"><span class="sitestr">example.org</span></a>)</span></span></td></tr><tr><td colspan="2"></td><td class="subtext"><span class="subline"> <span class="score" id="score_40000002">298 points</span> by <a href="user?id=bob" class="hnuser">bob</a> <span class="age" title="2026-04-26T07:42:00"><a href="item?id=40000002">4 hours ago</a></span> <span id="unv_40000002"></span> | <a href="hide?id=40000002&goto=news">hide</a> | <a href="item?id=40000002">152 comments</a> </span></td></tr><tr class="spacer" style="height:5px"></tr><tr class="athing submission" id="40000003"> <td align="right" valign="top" class="title"><span class="rank">3.</span></td> <td valign="top" class="votelinks"><center><a id="up_40000003" href="vote?id=40000003"><div class="votearrow" title="upvote"></div></a></center></td> <td class="title"><span class="titleline"><a href="https://example.com/yc-w26-startup">Acme (YC W26) is hiring senior engineers (remote)</a> <span class="sitebit comhead"> (<a href="from?site=example.com"><span class="sitestr">example.com</span></a>)</span></span></td></tr><tr><td colspan="2"></td><td class="subtext"><span class="subline"> <span class="age" title="2026-04-26T06:00:00"><a href="item?id=40000003">5 hours ago</a></span> </span></td></tr><tr class="spacer" style="height:5px"></tr><tr class="athing submission" id="40000004"> <td align="right" valign="top" class="title"><span class="rank">4.</span></td> <td valign="top" class="votelinks"><center><a id="up_40000004" href="vote?id=40000004"><div class="votearrow" title="upvote"></div></a></center></td> <td class="title"><span class="titleline"><a href="https://example.net/ask-hn" rel="noreferrer">Ask HN: What's your most underrated tool?</a></span></td></tr><tr><td colspan="2"></td><td class="subtext"><span class="subline"> <span class="score" id="score_40000004">156 points</span> by <a href="user?id=carol" class="hnuser">carol</a> <span class="age" title="2026-04-26T05:30:00"><a href="item?id=40000004">6 hours ago</a></span> <span id="unv_40000004"></span> | <a href="hide?id=40000004&goto=news">hide</a> | <a href="item?id=40000004">discuss</a> </span></td></tr><tr class="spacer" style="height:5px"></tr><tr class="athing submission" id="40000005"> <td align="right" valign="top" class="title"><span class="rank">5.</span></td> <td valign="top" class="votelinks"><center><a id="up_40000005" href="vote?id=40000005"><div class="votearrow" title="upvote"></div></a></center></td> <td class="title"><span class="titleline"><a href="https://example.io/quantum&chess">Why quantum & chess engines disagree</a> <span class="sitebit comhead"> (<a href="from?site=example.io"><span class="sitestr">example.io</span></a>)</span></span></td></tr><tr><td colspan="2"></td><td class="subtext"><span class="subline"> <span class="score" id="score_40000005">73 points</span> by <a href="user?id=dave" class="hnuser">dave</a> <span class="age" title="2026-04-26T04:00:00"><a href="item?id=40000005">7 hours ago</a></span> <span id="unv_40000005"></span> | <a href="hide?id=40000005&goto=news">hide</a> | <a href="item?id=40000005">12 comments</a> </span></td></tr><tr class="spacer" style="height:5px"></tr></table></td></tr></table></center></body></html>
browser-skills/hackernews-frontpage/_lib/browse-client.ts264 řádků
/** * browse-client — canonical SDK that browser-skill scripts import to drive the * gstack daemon over loopback HTTP. * * Distribution model: * This file is the canonical source. Each browser-skill ships a sibling * copy at `<skill>/_lib/browse-client.ts` (Phase 2's generator copies it * alongside every generated skill; Phase 1's bundled `hackernews-frontpage` * reference skill ships a hand-copied version). The skill imports the * sibling via relative path: `import { browse } from './_lib/browse-client'`. * * Why per-skill copies and not a single global SDK: each skill is fully * portable (copy the directory anywhere, it runs), version drift is * impossible (the SDK is frozen at the version the skill was authored * against), no npm publish workflow, no fixed-path tilde imports. * * Auth resolution: * 1. GSTACK_PORT + GSTACK_SKILL_TOKEN env vars (set by `$B skill run` when * spawning the script). The token is a per-spawn scoped capability bound * to read+write commands; it expires when the spawn ends. * 2. State file fallback: read `BROWSE_STATE_FILE` env or `<git-root>/.gstack/browse.json` * and use the `port` + `token` (the daemon root token). This path exists * for developers running a skill directly via `bun run script.ts` outside * the harness — your own authority, not an agent's. * * Trust: * The SDK exposes only the daemon's existing HTTP surface (POST /command). * No new capabilities. The token's scopes (read+write for spawned skills, * full root for standalone debug) determine what actually executes. * * Zero side effects on import. Safe to import from tests or plain scripts. */import * as fs from 'fs';import * as path from 'path';import * as cp from 'child_process';export interface BrowseClientOptions { /** Override port. Default: GSTACK_PORT env or state file. */ port?: number; /** Override token. Default: GSTACK_SKILL_TOKEN env, then state file root token. */ token?: string; /** Tab id to target (every command can scope to a tab). Default: BROWSE_TAB env or undefined (active tab). */ tabId?: number; /** Per-request timeout in milliseconds. Default: 30_000. */ timeoutMs?: number; /** Override state-file path. Default: BROWSE_STATE_FILE env or <git-root>/.gstack/browse.json. */ stateFile?: string;}interface ResolvedAuth { port: number; token: string; source: 'env' | 'state-file';}function parseIntegerEnvValue(value: string | undefined): number | undefined { const trimmed = value?.trim(); if (!trimmed || !/^-?\d+$/.test(trimmed)) return undefined; const parsed = parseInt(trimmed, 10); return Number.isFinite(parsed) ? parsed : undefined;}/** Resolve the daemon port + token. Throws a clear error if neither path works. */export function resolveBrowseAuth(opts: BrowseClientOptions = {}): ResolvedAuth { if (opts.port !== undefined && opts.token !== undefined) { return { port: opts.port, token: opts.token, source: 'env' }; } // 1. Env vars (set by $B skill run when spawning). const envPort = process.env.GSTACK_PORT; const envToken = process.env.GSTACK_SKILL_TOKEN; if (envPort && envToken) { const port = opts.port ?? parseIntegerEnvValue(envPort); if (port !== undefined) { return { port, token: opts.token ?? envToken, source: 'env' }; } } // 2. State file fallback (developer running `bun run script.ts` directly). const stateFile = opts.stateFile ?? process.env.BROWSE_STATE_FILE ?? defaultStateFile(); if (stateFile && fs.existsSync(stateFile)) { try { const data = JSON.parse(fs.readFileSync(stateFile, 'utf-8')); if (typeof data.port === 'number' && typeof data.token === 'string') { return { port: opts.port ?? data.port, token: opts.token ?? data.token, source: 'state-file', }; } } catch { // fall through to error } } throw new Error( 'browse-client: cannot find daemon port + token. Either spawn via `$B skill run` ' + '(sets GSTACK_PORT + GSTACK_SKILL_TOKEN) or run from a project with a live daemon ' + '(.gstack/browse.json must exist).' );}function defaultStateFile(): string | null { try { const proc = cp.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8', timeout: 2000, windowsHide: true }); const root = proc.status === 0 ? proc.stdout.trim() : null; const base = root || process.cwd(); return path.join(base, '.gstack', 'browse.json'); } catch { return path.join(process.cwd(), '.gstack', 'browse.json'); }}export class BrowseClientError extends Error { constructor( message: string, public readonly status?: number, public readonly body?: string, ) { super(message); this.name = 'BrowseClientError'; }}/** * Thin client over the daemon's POST /command endpoint. * * Convenience methods cover the common cases (goto, click, text, snapshot, * etc.). For anything not exposed as a method, use `command(cmd, args)`. */export class BrowseClient { readonly port: number; readonly token: string; readonly tabId?: number; readonly timeoutMs: number; constructor(opts: BrowseClientOptions = {}) { const auth = resolveBrowseAuth(opts); this.port = auth.port; this.token = auth.token; this.tabId = opts.tabId ?? parseIntegerEnvValue(process.env.BROWSE_TAB); this.timeoutMs = opts.timeoutMs ?? 30_000; } // ─── Low-level dispatch ───────────────────────────────────────── /** Send an arbitrary command; returns raw response text. Throws on non-2xx. */ async command(cmd: string, args: string[] = []): Promise<string> { const body = JSON.stringify({ command: cmd, args, ...(this.tabId !== undefined && !isNaN(this.tabId) ? { tabId: this.tabId } : {}), }); let resp: Response; try { resp = await fetch(`http://127.0.0.1:${this.port}/command`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.token}`, }, body, signal: AbortSignal.timeout(this.timeoutMs), }); } catch (err: any) { if (err.name === 'TimeoutError' || err.name === 'AbortError') { throw new BrowseClientError(`browse-client: command "${cmd}" timed out after ${this.timeoutMs}ms`); } if (err.code === 'ECONNREFUSED') { throw new BrowseClientError(`browse-client: daemon not running on port ${this.port}`); } throw new BrowseClientError(`browse-client: ${err.message ?? err}`); } const text = await resp.text(); if (!resp.ok) { let message = `browse-client: command "${cmd}" failed with status ${resp.status}`; try { const parsed = JSON.parse(text); if (parsed.error) message += `: ${parsed.error}`; } catch { if (text) message += `: ${text.slice(0, 200)}`; } throw new BrowseClientError(message, resp.status, text); } return text; } // ─── Navigation ───────────────────────────────────────────────── async goto(url: string): Promise<string> { return this.command('goto', [url]); } async wait(arg: string): Promise<string> { return this.command('wait', [arg]); } // ─── Reading ──────────────────────────────────────────────────── async text(selector?: string): Promise<string> { return this.command('text', selector ? [selector] : []); } async html(selector?: string): Promise<string> { return this.command('html', selector ? [selector] : []); } async links(): Promise<string> { return this.command('links'); } async forms(): Promise<string> { return this.command('forms'); } async accessibility(): Promise<string> { return this.command('accessibility'); } async attrs(selector: string): Promise<string> { return this.command('attrs', [selector]); } async media(...flags: string[]): Promise<string> { return this.command('media', flags); } async data(...flags: string[]): Promise<string> { return this.command('data', flags); } // ─── Interaction ──────────────────────────────────────────────── async click(selector: string): Promise<string> { return this.command('click', [selector]); } async fill(selector: string, value: string): Promise<string> { return this.command('fill', [selector, value]); } async select(selector: string, value: string): Promise<string> { return this.command('select', [selector, value]); } async hover(selector: string): Promise<string> { return this.command('hover', [selector]); } async type(text: string): Promise<string> { return this.command('type', [text]); } async press(key: string): Promise<string> { return this.command('press', [key]); } async scroll(selector?: string): Promise<string> { return this.command('scroll', selector ? [selector] : []); } // ─── Snapshot + screenshot ────────────────────────────────────── /** Snapshot returns the ARIA tree. Pass flags like '-i' (interactive only), '-c' (compact). */ async snapshot(...flags: string[]): Promise<string> { return this.command('snapshot', flags); } async screenshot(...args: string[]): Promise<string> { return this.command('screenshot', args); }}/** * Default singleton. Lazily resolves auth on first method call so a script can * import `browse` and immediately call `await browse.goto(...)` without * threading through a constructor. */class LazyBrowseClient { private inner: BrowseClient | null = null; private get(): BrowseClient { if (!this.inner) this.inner = new BrowseClient(); return this.inner; } // Mirror the BrowseClient surface; each method delegates to a freshly resolved instance. command(cmd: string, args: string[] = []) { return this.get().command(cmd, args); } goto(url: string) { return this.get().goto(url); } wait(arg: string) { return this.get().wait(arg); } text(selector?: string) { return this.get().text(selector); } html(selector?: string) { return this.get().html(selector); } links() { return this.get().links(); } forms() { return this.get().forms(); } accessibility() { return this.get().accessibility(); } attrs(selector: string) { return this.get().attrs(selector); } media(...flags: string[]) { return this.get().media(...flags); } data(...flags: string[]) { return this.get().data(...flags); } click(selector: string) { return this.get().click(selector); } fill(selector: string, value: string) { return this.get().fill(selector, value); } select(selector: string, value: string) { return this.get().select(selector, value); } hover(selector: string) { return this.get().hover(selector); } type(text: string) { return this.get().type(text); } press(key: string) { return this.get().press(key); } scroll(selector?: string) { return this.get().scroll(selector); } snapshot(...flags: string[]) { return this.get().snapshot(...flags); } screenshot(...args: string[]) { return this.get().screenshot(...args); }}export const browse = new LazyBrowseClient();
Kvíz 15
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Co přesně příklad vrací a v jakém formátu?
Na stdout jediný JSON dokument { "stories": Story[], "count": number }. Každá položka Story má rank, id, title, url, points a comments. Jediný dokument na stdout je záměr: volající (agent nebo skript) může výstup rovnou předat parseru JSON a nemusí oddělovat logy od dat — případné logy by šly na stderr.
2Proč je parsování oddělené do exportované funkce parseStoriesFromHtml a není součástí main()?
Čistá funkce nad stringem se testuje bez démona a bez sítě — test jí dá uložené HTML a porovná výsledek. main() obsahuje vedlejší efekty (navigace, síť, zápis na stdout), které by testy zpomalily a udělaly nestabilní. Rozdělení také umožňuje import ze script.test.ts bez spuštění skriptu, protože main() běží jen při import.meta.main.
3Proč test běží proti souboru fixtures/hn-2026-04-26.html, a ne proti živému webu?
Živý web se mění a vyžaduje síť, takže test by byl pomalý, nedeterministický a mohl by selhat bez zavinění kódu. Fixture je zmražená kopie struktury, nad kterou jsou výsledky vždy stejné (5 příběhů, známá čísla). Až Hacker News změní HTML, nejde o chybu testu — jde o signál, že je potřeba fixture obnovit a opravit selektory.
4Co by se stalo, kdyby lookahead pro skóre a komentáře nebyl ohraničený?
Regulár by u job postingu (který nemá span.score) hledal dál v HTML a našel skóre dalšího příběhu. Job posting by tak dostal cizí points a comments. Ohraničení na nejbližší tr.spacer nebo tr.athing zaručuje, že se čte jen vlastní „subtext“ řádek příběhu. Test returns null points + null comments for job postings tuhle regresi hlídá.
5Proč jsou points a comments typu number | null a ne prostě 0?
0 a „neexistuje“ jsou různé informace. Příběh s 0 komentáři má odkaz „discuss“, kdežto job posting žádný komentářový odkaz ani skóre vůbec nemá. Kdyby se nuly dosadily všude, konzument dat by nerozeznal „nikdo nekomentoval“ od „tohle není diskusní příspěvek“. null zachová pravdivost dat.
6Proč se odkaz „discuss“ interpretuje jako 0 komentářů?
Hacker News u příběhu bez komentářů místo „N comments“ zobrazí „discuss“. Pro uživatele to znamená, že komentářů je nula, takže skript vrací 0 (a ne null). Pokrývá to samostatný test treats "discuss" links as 0 comments.
7Jaké bezpečnostní oprávnění má skript při běhu přes $B skill run?
Dostane scoped token vázaný na čtení a zápis příkazů, který platí jen po dobu spuštění (expiruje s koncem procesu). Předává se přes GSTACK_PORT a GSTACK_SKILL_TOKEN. Skript tak nemůže víc, než dovoluje token; i kdyby ho někdo zneužil, po skončení spuštění je neplatný.
8Proč démon poslouchá jen na 127.0.0.1?
Loopback rozhraní je dostupné jen z téhož stroje. Nikdo ze sítě tak démona nezavolá, ani kdyby znal port nebo token. Je to nejjednodušší a nejspolehlivější vrstva obrany: útočník by musel nejdřív získat přístup přímo na vaše zařízení.
9Proč má každý skill vlastní kopii _lib/browse-client.ts místo jednoho sdíleného SDK?
Skill je pak přenositelný (zkopírujete adresář a funguje), verze SDK je zmrazená na tu, proti které byl skill napsán (žádný drift), nepotřebujete publikovat balíček do npm a nemusíte spoléhat na pevné cesty typu ~/.... Cenou je duplicita kódu, kterou generátor v pozdější fázi řeší automatickým kopírováním.
10Jak SDK zjistí port a token, když skript běží ručně mimo $B skill run?
Nejdřív zkusí proměnné GSTACK_PORT + GSTACK_SKILL_TOKEN. Když nejsou, přečte stavový soubor (BROWSE_STATE_FILE nebo <git-root>/.gstack/browse.json) a použije port a root token démona. To je určeno pro vývojáře, kteří skill ladí přes bun run script.ts — jde o jejich vlastní oprávnění, ne o oprávnění agenta.
11Proč se nepoužívá plnohodnotný HTML parser, ale regulární výrazy? Je to bezpečné?
Struktura tr.athing je na Hacker News dlouhodobě stabilní a skript potřebuje jen několik polí, takže regexy jsou jednoduché a bez závislostí. Nejde o bezpečnostní riziko, protože skript HTML pouze čte a vrací jako data — nikdy ho nevykonává ani nevkládá do stránky. Slabinou je křehkost při změně HTML, a právě tu zachytává test nad fixture.
12Co udělá parser s prázdným vstupem nebo s HTML bez příběhů?
Vrátí []. Test returns [] for empty HTML a returns [] for HTML with no story rows to hlídají. Parser tedy nespadne a nevymýšlí výsledky — count bude 0 a volající to pozná.
13Proč parser přeskočí řádek tr.athing, který nemá span.titleline?
Bez titulku a odkazu by záznam byl neúplný. Raději ho vynechat, než vracet příběh s prázdným title a url. Test does not fabricate stories from arbitrary tr.athing rows missing titleline zajišťuje, že parser neumí „vyrobit“ falešný příběh.
14K čemu slouží triggers v SKILL.md?
Jsou to fráze („scrape hacker news frontpage“, „get hn top stories“…), podle kterých lze skill najít z přirozeného zadání. Spolu s host: news.ycombinator.com a trusted: true popisují, co skill dělá a komu se věří; agent z toho pozná, že skill je vhodný pro daný úkol.
15Jak se z tohoto příkladu pozná, že se parser po změně Hacker News rozbil?
Spuštění bun test nad script.test.ts selže na zmražené fixture, pokud selektory přestanou odpovídat struktuře. Chyba se objeví při vývoji nebo v CI, ne až u uživatele, který by dostal prázdný nebo špatný výstup. To je zdůvodnění v samotném SKILL.md: „test fails against the captured fixture before users notice“.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1Browser skill
Samostatný adresář (manifest SKILL.md + skript), který automatizuje konkrétní úkol v prohlížeči. V tomto příkladu hackernews-frontpage umí jedinou věc: vrátit titulní stránku Hacker News jako JSON.
2`$B`
Zkratka pro binárku prohlížeče gstacku. Příkaz $B skill run hackernews-frontpage najde skill, spustí jeho script.ts a předá mu přihlašovací údaje k démonu.
3Démon (daemon) prohlížeče
Dlouho běžící proces, který drží prohlížeč a poslouchá příkazy přes HTTP na loopbacku. Skript goto a html neprovádí sám — posílá je démonu přes SDK.
4`browse-client` (SDK)
Soubor _lib/browse-client.ts s objektem browse. Zabalí POST /command do pohodlných metod (goto, html), vyřeší port a token a nemá vedlejší efekty při importu.
5Scoped token
Časově omezený token vázaný na oprávnění (zde čtení + zápis příkazů) a na jedno spuštění. Skript s ním nemůže víc než povolené příkazy a po skončení procesu přestane platit.
6Loopback (`127.0.0.1`)
Síťové rozhraní dostupné jen z téhož počítače. Démon na něm poslouchá, takže ho zvenku nelze oslovit.
7Fixture
Soubor fixtures/hn-2026-04-26.html — zmražená ukázka HTML se 5 příběhy (včetně job postingu a „discuss“), nad kterou testy běží opakovatelně bez sítě.
8`tr.athing`
Řádek tabulky HTML s třídou athing a atributem id; na Hacker News představuje jeden příběh. Parser podle něj počítá rank a čte id.
9`span.titleline`
Element obsahující odkaz na titulek příběhu. Z jeho prvního <a> se bere url (atribut href) a title (text uvnitř).
10Subtext řádek
Řádek těsně pod příběhem se skóre (span.score), autorem, stářím a odkazem na komentáře. Parser v něm hledá points a comments.
11Ohraničený lookahead
Omezení vyhledávání skóre/komentářů na úsek před nejbližším tr.spacer nebo dalším tr.athing. Brání tomu, aby si příběh „půjčil“ data od následujícího.
12Job posting
Příspěvek typu „… is hiring“ bez skóre a bez komentářů. V příkladu dostane points: null a comments: null a slouží jako okrajový případ pro testy.
13Dekódování HTML entit
Funkce decodeHtmlEntities převádí &, ", ' apod. zpět na znaky, aby výstup obsahoval skutečný text a URL (quantum&chess).
14`import.meta.main`
Příznak Bunu, který je pravdivý jen při přímém spuštění souboru. Chrání main() před spuštěním při importu z testu.
15Stdout / stderr protokol
Úmluva skriptu: data (jediný JSON) jdou na stdout, logy na stderr, úspěch je exit kód 0, chyba nenulový kód. Díky tomu je výstup strojově zpracovatelný.
16Deterministický výstup
Stejný vstup (HTML) dává vždy stejný výstup. Základ pro spolehlivé testy; u parseru to zaručuje čistá funkce bez náhodnosti a bez času.
Tutorial: dokumentace funkce za 90 sekund
Krok za krokem: jak /document-generate přečte kód, rozdělí dokumentaci do čtyř kvadrantů Diataxis, napíše ji a doplní tabulku pokrytí do PR.
Popis
Co příklad ukazuje
Tutoriál provede celým během skillu /document-generate nad existujícím projektem. Výsledkem jsou čtyři dokumenty, každý pro jiného čtenáře, a tabulka pokrytí v těle pull requestu. Autor tutoriálu dává čtenáři „čtyři tahy“: scope → archaeology → partition → write.
Čtyři kvadranty Diataxis
| Kvadrant | Pro koho | Jak vypadá |
|---|---|---|
| Tutorial | nováček | vede k funkčnímu výsledku do 3 kroků, končí „What you built“ |
| How-to | zkušený uživatel | prerekvizity, očíslované kroky s přesnými příkazy, ověření, troubleshooting |
| Reference | volající API | stručný, úplný výpis s typy a výchozími hodnotami, bez vyprávění |
| Explanation | reviewer | nejdřív problém, potom přístup, kompromisy a zvažované alternativy |
Každý typ má jedinou úlohu, a proto se dokumenty neopakují a snadno se udržují.
Průběh po krocích
- Spuštění —
/document-generatese zeptá na cíl výstupu: (A) inline do existujících souborů, (B) samostatné soubory, (C) obojí. Doporučená je C: README ukazuje na hloubkové dokumenty. - Archaeology — asi 30 sekund ticha. Skill čte strukturu repozitáře, README/ARCHITECTURE/CONTRIBUTING/CLAUDE.md, celé implementační soubory, testy (odhalí okrajové případy) a komentáře
NOTE:,DESIGN:,WHY:. Na konci vypíše řádek typu „Researched 47 files…“ — číslo je důkaz, že skill kód opravdu četl. - Partition plan — tabulka entit × kvadrantů. Ne každá entita potřebuje všechny čtyři: CLI přepínače dostanou reference + how-to, interní moduly reference + explanation, uživatelské funkce všechny čtyři. Nad 5 dokumentů se skill zeptá na potvrzení.
- Reference první — reference ustálí slovník, proto vzniká jako první (
GENERATED: docs/reference-widget-service.md). - Explanation, how-to, tutorial — vznikají rychle po sobě a kontroluje je Step 8 Quality Self-Review.
- Cross-linking — dokumenty na sebe odkazují;
grep -rE '\]\([^)]*\.md\)' docs/pomůže ověřit, že žádný odkaz nevede do prázdna. - Souhrn v PR — sekce
## Documentation Generateds tabulkou souborů, kvadrantů a popisů.
Proč je to nejlepší možný postup
- Nejdřív čtení, až potom psaní. Dokumentace z názvů souborů by si vymýšlela signatury. Povinná archaeology je hlavní ochrana proti halucinacím.
- Struktura je vynucená. Chybí-li how-to sekce ověření, zachytí to self-review před commitem.
- Odkazy jsou součástí kontroly. Dokument bez cest k sousedům by byl slepá ulička.
- Bezpečné ve výchozím stavu. Skill generuje soubory, které projdou obvyklým code review; nic nenasazuje ani nepublikuje.
Co si čtenář odnese
Po dokončení má projekt čtyři krátké dokumenty, které si reviewer může prohlédnout podle tabulky v PR. /document-release později ohlásí entitu jako plně pokrytou (4/4 kvadranty).
Zdrojový kód 1
docs/tutorial-document-generate.md142 řádků
# Tutorial: generate docs for a feature in 90 secondsYou'll run `/document-generate` against a project you already have, watch it write tutorial / how-to / reference / explanation docs in the right places, and end with a coverage map you can drop into a PR. By the end, you'll know the four moves: scope, archaeology, partition, write.## What you'll need- gstack installed (`git clone --single-branch --depth 1 https://github.com/garrytan/gstack.git ~/.claude/skills/gstack && cd ~/.claude/skills/gstack && ./setup`)- Claude Code running in any project that has at least one piece of public surface (a CLI command, an exported function, a config option, a skill, an API endpoint)- About 90 secondsYou do not need a `docs/` directory in advance — the skill creates one if it's missing. You do not need to know Diataxis terminology — the skill labels the output for you.## Step 1: Invoke the skill in any projectOpen Claude Code in the project you want to document. Type:```/document-generate```You'll see the skill ask one question about output target:```A) Write documentation inline in existing files (README, ARCHITECTURE, etc.)B) Create standalone documentation files (e.g., docs/ directory)C) Both — inline summaries in existing files + deep docs in standalone filesRECOMMENDATION: Choose C because it maximizes both discoverability and depth.```Pick C. You'll get a README pointer plus a full set of standalone docs.## Step 2: Watch the archaeology runThe skill goes silent for ~30 seconds while it reads the codebase. This is intentional — the Step 1 "Codebase Archaeology" phase is the most important step in the workflow. The skill is reading:- The full repository structure- README, ARCHITECTURE, CONTRIBUTING, CLAUDE.md (the entry points)- The implementation files for whatever you're documenting (full file, not just signatures)- The tests (which reveal edge cases and intended behavior)- Inline comments tagged `// NOTE:`, `// DESIGN:`, `// WHY:`When it finishes, you'll see a line like:```Researched 47 files, identified 12 public surface items, 8 concepts, and 4 design decisions.```That number tells you the skill actually read the code rather than guessing from filenames.## Step 3: See the Diataxis partition planThe skill prints a partition plan showing which quadrants it'll write for which entity:```Documentation plan: [entity] [tutorial] [how-to] [reference] [explanation] WidgetService ✅ new ✅ new ✅ new ✅ new --verbose flag ❌ ✅ new ✅ inline ❌ Bayesian scheduler ❌ ❌ ✅ new ✅ new```Not every entity needs all four quadrants. CLI flags get reference + how-to. Internal modules get reference + explanation. User-facing features get all four. The skill picks based on entity type.If the plan has more than 5 documents, the skill asks you to confirm before proceeding. Otherwise it goes.## Step 4: Read the first doc that landsReference docs land first because they fix the vocabulary. You'll see lines like:```GENERATED: docs/reference-widget-service.md```Open that file. It has a strict structure: one-paragraph intro, complete API listing with types and defaults, 2-3 runnable examples, and a Related section linking to the how-to and tutorial that will land next.This is what reference docs look like in Diataxis: factual, exhaustive, no narrative. If you find yourself wanting to explain *why* an option exists, that belongs in the explanation doc the skill will write next.## Step 5: See the explanation, how-to, and tutorial appearIn quick succession (each ~5-10 seconds), the skill writes the remaining quadrants:```GENERATED: docs/explanation-widget-architecture.mdGENERATED: docs/howto-create-a-custom-widget.mdGENERATED: docs/tutorial-build-your-first-widget.md```Open each one. Notice they don't repeat each other:- **Explanation** leads with the problem, then the approach, then trade-offs and alternatives considered- **How-to** has prerequisites, numbered steps with exact commands, a verification section, and a troubleshooting section- **Tutorial** gets you to a working result in under 3 steps, ends with "What you built"The skill enforces these structures. If a how-to was missing a verification section, the Step 8 Quality Self-Review caught it before commit.## Step 6: Check cross-linkingEvery doc links to the others. Reference doc Related section: links to how-to and tutorial. How-to Related section: links to reference. Tutorial "What you built" section: links to reference for deeper exploration.Run a grep to verify no broken links:```bashgrep -rE '\]\([^)]*\.md\)' docs/ | head -10```Every linked file should exist. The skill's Step 7 "Cross-Document Linking & Discoverability" checks this before commit.## Step 7: See the coverage summary in the PR bodyIf you're on a feature branch with an open PR, the skill updates the PR body with a `## Documentation Generated` table:```## Documentation Generated| File | Quadrant | Description ||------|----------|-------------|| docs/tutorial-build-your-first-widget.md | Tutorial | Walk-through from install to first working widget || docs/reference-widget-service.md | Reference | Complete widget API with types, defaults, examples || docs/explanation-widget-architecture.md | Explanation | Why widgets are isolated services || docs/howto-create-a-custom-widget.md | How-to | Creating and registering custom widgets |```A reviewer opening the PR sees the table and knows immediately what kind of coverage shipped.## What you builtYou now have four documents that serve four different readers:- A newcomer to your project can read `tutorial-*.md` and get something working- An experienced user can read `howto-*.md` to accomplish a specific task- An API caller can read `reference-*.md` for exact signatures- A code reviewer can read `explanation-*.md` to understand the designEach one is short enough to maintain. Each one has a single job. The PR body shows which quadrants were covered. If you run `/document-release` later, the Diataxis coverage map will report this entity as fully covered (4/4 quadrants).## What to do next- **If you have gaps** /document-release flagged but didn't fill: run `/document-generate` again, scoped to those entities specifically.- **If you want to understand why the four quadrants exist:** read [explanation-diataxis-in-gstack.md](./explanation-diataxis-in-gstack.md).- **If you want to document one specific feature before shipping** (not the whole project): read [howto-document-a-shipped-feature.md](./howto-document-a-shipped-feature.md).- **Reference for the skill itself:** [`document-generate/SKILL.md`](../document-generate/SKILL.md).
Kvíz 14
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Proč je první fáze (Codebase Archaeology) označená jako nejdůležitější krok?
Protože kvalita dokumentace závisí na tom, co skill skutečně přečetl. Čte celé implementační soubory, testy a komentáře NOTE:/DESIGN:/WHY:, ne jen signatury. Bez této fáze by se reference a vysvětlení psaly z názvů souborů a obsahovaly by vymyšlené detaily. Číslo „Researched N files“ slouží uživateli jako důkaz, že čtení proběhlo.
2Proč skill čte i testy?
Testy odhalují okrajové případy a zamýšlené chování, které implementace jen naznačuje. Z nich se dá napsat přesná reference (co funkce vrací při prázdném vstupu) i realistický how-to. Bez nich by dokumentace popisovala jen „šťastnou cestu“.
3Proč reference vzniká jako první dokument?
Reference je faktická a úplná, takže ustálí slovník (názvy, typy, výchozí hodnoty). Ostatní kvadranty (explanation, how-to, tutorial) na ni pak odkazují a používají stejné pojmy. Kdyby vznikl tutorial první, mohl by zavést jiné názvy a dokumentace by byla nekonzistentní.
4Proč mají čtyři dokumenty různou strukturu, když jde o stejnou funkci?
Čtou je různí lidé s různým cílem: nováček chce výsledek (tutorial), zkušený uživatel chce splnit úkol (how-to), volající chce přesné signatury (reference), reviewer chce pochopit návrh (explanation). Smíchat je do jednoho textu znamená, že ho nikdo nepřečte celý. Oddělení dělá každý dokument krátkým a udržitelným.
5Proč ne každá entita dostane všechny čtyři kvadranty?
Skill je přidělí podle typu entity: CLI přepínač potřebuje reference + how-to, interní modul reference + explanation, uživatelská funkce všechny čtyři. Psaní zbytečného tutoriálu k vnitřnímu modulu by produkovalo balast, který se rychle zastará.
6Proč se skill zeptá na potvrzení, pokud plán obsahuje víc než 5 dokumentů?
Velký plán znamená hodně nových souborů v repozitáři. Potvrzení dává člověku kontrolu nad rozsahem dřív, než se soubory vytvoří, takže zbytečně nepřibude desítky souborů ke kontrole.
7Proč je doporučená volba „C — inline i standalone“?
Kombinuje objevitelnost (README/ARCHITECTURE jen stručně odkáží) a hloubku (samostatné dokumenty v docs/). Jen inline by nafoukl README, jen standalone by znamenal, že dokumentaci nikdo nenajde.
8K čemu je příkaz grep -rE '\]\([^)]*\.md\)' docs/ a co z jeho výstupu zkontrolujete?
Vypíše všechny Markdown odkazy na .md soubory v docs/. Ručně (nebo skriptem) ověříte, že každý cílový soubor existuje. Skill podobnou kontrolu dělá ve Step 7 před commitem, takže rozbitý odkaz se do PR nedostane.
9Co je v tabulce ## Documentation Generated v těle PR a proč tam je?
Tabulka s názvem souboru, kvadrantem a popisem. Reviewer podle ní okamžitě vidí, jaký druh pokrytí PR přináší, a nemusí otevírat každý soubor, aby pochopil rozsah dokumentace.
10Jak poznáte, že tutorial je napsaný dobře?
Dojde se do funkčního výsledku nejvýš ve 3 krocích a končí sekcí „What you built“ s odkazy na reference. Tutorial s 8 kroky je podle troubleshootingu v souvisejícím how-to chyba — má se zkrátit.
11Proč explanation začíná problémem a až potom přístupem?
Vysvětlení má odpovědět na „proč je to takhle navržené“. Bez znalosti problému nelze kompromisy a alternativy posoudit. Proto je pořadí problém → přístup → kompromisy → zvažované alternativy.
12Co se stane, když v projektu žádný adresář docs/ ještě není?
Nic se nerozbije: tutoriál výslovně říká, že skill adresář vytvoří. Není nutné předem znát ani terminologii Diataxis — skill výstup sám označí.
13Proč je tento postup bezpečný pro cizí repozitář?
Skill pouze čte kód a zapisuje dokumentační soubory do dohodnutých míst. Nespouští nasazení, nemění zdrojový kód a výsledek prochází běžným review přes PR. Pokud by vygenerovaný text obsahoval nepravdivé signatury, dá se to odhalit porovnáním s kódem a nahlásit chybu.
14Jak spolu souvisí /document-generate a /document-release?
/document-release audituje diff a hlásí mezery v pokrytí kvadranty, /document-generate mezery vyplňuje. Po vygenerování se /document-release spustí znovu a entita se má ukázat jako plně pokrytá (4/4).
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1Diataxis
Rámec rozdělující dokumentaci do čtyř typů podle potřeby čtenáře: tutorial, how-to, reference, explanation. Tutoriál ho používá jako osu, podle které se plánuje, co se napíše.
2Kvadrant
Jeden ze čtyř typů dokumentu v Diataxis. Plán v kroku 3 je tabulka entit × kvadrantů (nový, inline, nepotřebný).
3Scope
První „tah“: určení, co se dokumentuje (celý projekt, konkrétní entity). Při opakovaném spuštění se dá omezit jen na mezery ohlášené /document-release.
4Codebase archaeology
Krok 1 skillu: důkladné čtení repozitáře (struktura, entry-point dokumenty, implementace, testy, komentáře) před jakýmkoli psaním. Zaručuje, že dokumentace vychází z kódu.
5Partition plan
Tabulka, která pro každou entitu říká, které kvadranty se napíšou (✅ new, ✅ inline, ❌). Skill ji vypíše dřív, než začne psát.
6Entita
Cokoli z veřejné plochy projektu, co potřebuje dokumentaci: CLI přepínač, exportovaná funkce, služba, konfigurační volba, skill. Typ entity určuje, které kvadranty dostane.
7Veřejná plocha (public surface)
Vše, co používají vnější lidé nebo kód: příkazy, exporty, konfigurace, endpointy. Tutoriál požaduje aspoň jednu položku, aby bylo co dokumentovat.
8Reference doc
Faktický dokument s úplným výpisem API, typů a výchozích hodnot, 2–3 spustitelnými příklady a sekcí Related. Neobsahuje „proč“.
9Explanation doc
Dokument pro porozumění návrhu: problém, přístup, kompromisy a alternativy. Odpovídá na „proč“, na které reference záměrně nechává místo.
10How-to doc
Dokument s prerekvizitami, očíslovanými kroky s přesnými příkazy, sekcí ověření a troubleshootingem. Řeší konkrétní úkol zkušeného uživatele.
11Tutorial doc
Dokument pro nováčka, který vede k funkčnímu výsledku nejvýš ve třech krocích a končí „What you built“.
12Step 8 Quality Self-Review
Závěrečná kontrola skillu: ověřuje, že každý dokument dodržel svou strukturu (např. how-to má ověření). Zachytí část chyb před commitem, ne všechny.
13Cross-linking
Vzájemné odkazování dokumentů: reference → how-to/tutorial, how-to → reference, tutorial → reference. Step 7 kontroluje, že cíle existují.
14`GENERATED:` řádek
Výstupní zpráva skillu po vzniku souboru (GENERATED: docs/reference-widget-service.md). Slouží jako průběžný přehled, co přibylo.
15`## Documentation Generated`
Sekce v těle PR s tabulkou souborů, kvadrantů a popisů. Reviewerovi ukazuje pokrytí na první pohled.
16Coverage map
Tabulka z /document-release ukazující, které entity mají které kvadranty. Po vygenerování má ukázat 4/4 pro dotčené entity.
How-to: první produkční deploy
Jak dostat aplikaci poprvé do produkce, aby ji /setup-deploy mohl zaznamenat a /land-and-deploy ověřovat — bez vazby na konkrétního hostitele.
Popis
Co příklad řeší
/setup-deploy zapisuje konfiguraci toho, jak ověřit deploy. Když ale žádný produkční deploy neexistuje, skončí hláškou „Nothing is deployed yet“ a nic nezapíše. Tento how-to vás provede prvním nasazením, takže na konci máte živou URL, kterou /setup-deploy zaznamená a /land-and-deploy bude ověřovat.
Dokument záměrně nejmenuje žádného poskytovatele ani nástroj: popisuje obecné kroky, které platí pro statické soubory, dlouho běžící server/kontejner i funkce.
Postup
- Vyberte, kde aplikace poběží a jak se deploy spouští.
/land-and-deploysleduje jen spouštěč, který už existuje — sám ho nevytváří. Volby: automaticky při push do výchozí větve, CI workflow, deploy skript/CLI, ručně. - Vytvořte produkční služby (databáze, cache, úložiště, e-mail, platby) oddělené od vývojových a spusťte migrace dřív, než aplikace začne přijímat provoz.
- Nastavte proměnné prostředí a secrets — vypište, co aplikace čte při buildu i za běhu, nastavte je v hostiteli, do repozitáře dejte jen
.env.examples placeholdery a skutečné hodnoty zadávejte sami, ne do chatu s agentem. - První deploy — spusťte zvolený spouštěč, sledujte build a release log a zapište si přidělenou adresu.
- Doména (volitelně) — DNS záznamy (CNAME nebo A/AAAA),
dig +shortpro ověření překladu acurl -sIpro HTTPS a platný certifikát. Rozhodněte, která adresa je „produkční URL“. - Ověření — otevřete URL, projděte jeden skutečný flow, zkontrolujte health endpoint (2xx), zjistěte, jak poznat nasazenou revizi, a prohlédněte logy.
- Předání gstacku — znovu
/setup-deploy; zapíše sekci## Deploy Configurationdo CLAUDE.md a jednou vyzkouší health check a stavový příkaz.
Proč je to nejlepší a bezpečná cesta
- Nejdřív realita, potom konfigurace. Konfigurace deploye bez existujícího deploye by popisovala něco, co nelze ověřit. Proto se
/setup-deployzastaví a nic nezapíše. - Secrets mimo repozitář a mimo chat. Hodnoty by v historii gitu i v konverzaci zůstaly navždy.
.env.examples placeholdery dokumentuje, co je potřeba, a nic neprozrazuje. - Oddělené produkční služby. Sdílení databáze s vývojem by znamenalo riziko poškození produkčních dat testy.
- Health endpoint, který něco ověřuje. Fixní stránka „OK“ nepozná, že aplikace ztratila spojení s databází.
- Rozlišení „stránka se načte“ a „je nasazen správný commit“.
/land-and-deploybere načtenou stránku jen jako zdraví webu; důkaz o revizi potřebuje samostatně. - První běh
/land-and-deployje dry run. Než se stane něco nevratného, projde se pipeline nanečisto.
Zdrojový kód 1
docs/howto-bring-up-a-first-deploy.md119 řádků
# How to bring up your first production deployUse this when `/setup-deploy` stops with "Nothing is deployed yet". It walks through a first production deploy, so you finish with a live URL that `/setup-deploy` can record and `/land-and-deploy` can verify. It names no hosting provider or deploy tool; use whichever fits your project.`/setup-deploy` writes nothing at that stop. It configures how `/land-and-deploy` checks a deploy, so it needs a production deploy that already exists.## Prerequisites- The app builds and starts locally with the commands production will run.- The code is in its GitHub repository. `/setup-deploy` and `/land-and-deploy` read it through the GitHub CLI, so `gh auth status` should pass.- An account with the hosting provider you choose, with billing set up if it needs it.- Optional: a domain you control, if users won't use the host's default address.## Steps### 1. Choose where the app runsPick a host for the kind of app you have: static files, a long-running server or container, or functions. List what the app needs at runtime: the language runtime and its version, a database or other services, background jobs, and any disk that has to survive a restart.Then choose how production deploys start. `/land-and-deploy` only watches a trigger that already exists; it never creates one. When `/setup-deploy` asks how deploys are triggered, the choices are:- automatically on push to the default branch- a CI workflow in the repository- a deploy script or CLI command- manuallyA trigger that runs on merge to the default branch keeps `/land-and-deploy` hands-off. With a command trigger, nothing deploys until the command runs: `/land-and-deploy` asks you to run it after the merge, or runs it only with your explicit approval.### 2. Create the services the app depends onCreate production instances of every service the app uses, such as its database, cache, file storage, email or payments, separate from your development ones. Run the database schema setup or migrations against production before the app serves traffic.### 3. Set environment variables and secrets1. List every variable the app reads, at build time and at runtime.2. Set each one in the host's environment or secrets settings.3. Keep secret values out of the repository. Commit only an example file with placeholder values, such as `.env.example`.4. Enter secret values yourself. Don't paste them into a chat with your agent.Some hosts inject variables only at runtime. A value the build needs, such as a public client-side key, has to be available when the build runs.### 4. Run the first deployStart a deploy with the trigger you chose: push to the default branch, run the workflow, or run the command. Watch the build and release logs until they finish, and note the address the host assigns. If the build fails, fix it and deploy again before you go on.### 5. Point your domain at it (optional)1. At your DNS provider, add the records the host asks for: usually a CNAME record for a subdomain, or A and AAAA records for the root domain.2. Wait until the name resolves: ```bash dig +short app.example.com ```3. Check that HTTPS works for the domain with a valid certificate: ```bash curl -sI https://app.example.com | head -1 ```Decide which address is the production URL, your domain or the host's default address. That is the URL you give `/setup-deploy`.### 6. Check that it works1. Open the production URL in a browser and walk through one real flow, such as signing in or loading data.2. If the app has a health endpoint, check that it returns a 2xx status: ```bash curl -s -o /dev/null -w "%{http_code}\n" https://app.example.com/health ``` A useful health endpoint exercises the app, for example by reaching its database, instead of returning a fixed page.3. Make sure you can tell which revision is live: a status command that prints the deployed commit, or a page or endpoint that shows it. `/land-and-deploy` treats a page that loads as site health, not as proof that the merged commit is live.4. Check the host's logs for errors after your first requests.### 7. Hand the deploy back to gstackRun `/setup-deploy` again. If the project now has a config file for a platform it recognizes, it starts from that platform's settings; otherwise it asks. Either way, have these answers ready:- how deploys are triggered (step 1)- the production URL (step 5)- how to check that a deploy succeeded: a health check URL, a status command, the CI workflow's status, or just checking that the URL loads- the merge method your repository allows (squash, merge or rebase), and any command to run before mergingIt writes the answers to the `## Deploy Configuration` section of the project's CLAUDE.md, then tries the health check and the status command once. From then on, `/land-and-deploy` uses that section to merge your PR, watch the deploy and check production. Its first run walks you through a dry run of the pipeline before anything irreversible happens.## Verification- `/setup-deploy` ends with `DEPLOY CONFIGURATION — COMPLETE`.- The project's CLAUDE.md has the section, with your production URL: ```bash grep -A 20 "## Deploy Configuration" CLAUDE.md ```- Its health check did not print `UNREACHABLE`, and its status command did not print `COMMAND_FAILED`.## Troubleshooting**`/setup-deploy` stops at "Nothing is deployed yet" again.**That answer means there is no production deploy to record. Once the app is live, pick the answer that says how it deploys: on push, through a CI workflow, with a script or command, or by hand.**The health check fails or prints `UNREACHABLE`.**Open the URL yourself. A 404 means the health path doesn't exist, so give `/setup-deploy` a path that returns 2xx, or the plain production URL. `/setup-deploy` keeps the configuration even when this check fails, so you can fix the URL later by running it again or by editing the section in CLAUDE.md.**The app works on the host's address but not on your domain.**Check the DNS records (`dig +short <domain>`) and the certificate (`curl -sI https://<domain>`). New records can take a while to resolve everywhere.**The build works locally but fails on the host.**Compare the host's build environment with yours. A missing build-time variable or a different runtime version is the usual cause.**You deploy by running a command by hand.**Record it as the deploy trigger. After each merge, `/land-and-deploy` tells you production hasn't moved yet and asks you to run it.## Related- [`/setup-deploy`](./skills.md#setup-deploy) and [`/land-and-deploy`](./skills.md#land-and-deploy): what each skill does- [`/canary`](./skills.md#canary): post-deploy monitoring once production is live- Reference: [`setup-deploy/SKILL.md`](../setup-deploy/SKILL.md), [`land-and-deploy/SKILL.md`](../land-and-deploy/SKILL.md)
Kvíz 15
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Proč se /setup-deploy zastaví na „Nothing is deployed yet“ a nic nezapíše?
Protože slouží k zaznamenání způsobu, jak ověřit existující produkční deploy (URL, health check, stavový příkaz). Bez živého deploye by záznam obsahoval domněnky, které /land-and-deploy později vyhodnotí jako chybu nebo falešný úspěch. Dokument proto začíná tím, že nejdřív vytvoříte skutečný deploy.
2Proč musí spouštěč deploye existovat dřív, než ho /land-and-deploy použije?
/land-and-deploy pouze sleduje spouštěč; nevytváří ho. Pokud je spouštěčem push do výchozí větve nebo CI workflow, běží to samo po merge. Pokud je to ručně spouštěný příkaz, nástroj po merge řekne, že produkce se ještě nepohnula, a vyžádá vaše spuštění — nebo ho spustí jen s výslovným souhlasem.
3Proč mají být produkční služby (databáze, cache…) oddělené od vývojových?
Aby test ani omyl nezměnil produkční data a aby výpadek vývojové instance nezasáhl uživatele. Navíc se migrace schématu spouštějí na produkci dřív, než aplikace přijme provoz, takže se nikdy nespustí aplikace proti neexistujícím tabulkám.
4Proč se secrets nevkládají do repozitáře ani do chatu s agentem?
Co se jednou dostane do historie gitu nebo konverzace, se těžko maže a může se propsat do logů, cache nebo záloh. V repozitáři proto zůstává jen .env.example s placeholdery a skutečné hodnoty zadáváte sami přímo v nastavení hostitele.
5Proč dokument zdůrazňuje rozdíl mezi build-time a runtime proměnnými?
Někteří hostitelé injektují proměnné až za běhu. Hodnota, kterou potřebuje build (například veřejný klientský klíč), musí být dostupná už při buildu, jinak build selže nebo vznikne chybná aplikace. Dokument radí vypsat všechno, co aplikace čte, a nastavit to na správném místě.
6Jak ověříte, že doména funguje a je zabezpečená?
Dvěma příkazy: dig +short app.example.com ukáže, zda se jméno překládá na cílovou adresu, a curl -sI https://app.example.com | head -1 ověří, že HTTPS odpovídá s platným certifikátem. Nové DNS záznamy se mohou šířit déle, takže se čeká, než se jméno všude přeloží.
7Proč má health endpoint „cvičit“ aplikaci, například sáhnout do databáze?
Statická stránka vrátí 200 i tehdy, když je databáze nedostupná. Užitečný health check kontroluje závislosti, takže odhalí stav, kdy je proces živý, ale aplikace nefunguje. Odpověď se kontroluje příkazem curl -s -o /dev/null -w "%{http_code}\n" https://app.example.com/health.
8Proč musíte umět poznat, jaká revize je nasazená?
Načtená stránka dokazuje jen to, že nějaká verze běží. /land-and-deploy ale potřebuje vědět, že běží mergnutý commit. Proto má existovat stavový příkaz nebo stránka/endpoint, který revizi vypíše.
9Co je výstupem kroku 7 a kde se uloží?
Sekce ## Deploy Configuration v CLAUDE.md projektu s produkční URL, spouštěčem deploye, způsobem ověření úspěchu a povolenou metodou merge (squash/merge/rebase). Úspěch poznáte podle DEPLOY CONFIGURATION — COMPLETE a podle toho, že health check nevypsal UNREACHABLE a stavový příkaz COMMAND_FAILED.
10Co dělat, když health check ohlásí UNREACHABLE?
Otevřít URL ručně. 404 znamená, že cesta health endpointu neexistuje — zadejte cestu vracející 2xx, nebo samotnou produkční URL. /setup-deploy konfiguraci ponechá i při selhání kontroly, takže ji můžete opravit opakovaným spuštěním nebo úpravou sekce v CLAUDE.md.
11Aplikace funguje na adrese hostitele, ale ne na vaší doméně. Kde hledat chybu?
V DNS (dig +short <domain>) a v certifikátu (curl -sI https://<domain>). Aplikace sama je v pořádku, protože na adrese hostitele funguje; problém je v překladu jména, ve špatném záznamu nebo v neplatném certifikátu.
12Build funguje lokálně, ale na hostiteli selhává. Co je nejčastější příčina?
Rozdíl prostředí: chybí build-time proměnná nebo se liší verze runtime. Doporučený postup je porovnat build prostředí hostitele s lokálním.
13Jak má vypadat nastavení, pokud se deploy spouští ručně příkazem?
Příkaz zaznamenáte jako deploy trigger. Po každém merge pak /land-and-deploy upozorní, že produkce se ještě nepohnula, a vyžádá spuštění příkazu (nebo ho spustí po výslovném schválení).
14Proč je první běh /land-and-deploy dry run?
Merge a deploy jsou těžko vratné akce. Nanečisto se ověří, že konfigurace, spouštěč a kontroly spolu fungují, a teprve potom se provede cokoli nevratného.
15Proč dokument nejmenuje žádného konkrétního poskytovatele?
Postup se opírá o obecné kroky (host, služby, secrets, deploy, DNS, ověření), které platí všude. Vazba na jednoho hostitele by zastarala a vylučovala by ostatní. Vyžadováno je jen to, co potřebuje gstack: živá URL a způsob ověření.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1Deploy
Nasazení aplikace do prostředí, kde ji používají uživatelé. V tomto příkladu je cílem první produkční deploy, který ještě neexistuje.
2`/setup-deploy`
Skill, který zaznamená, jak se deploy spouští a ověřuje (URL, health check, stavový příkaz, metoda merge). Bez existujícího produkčního deploye se zastaví a nic nezapíše.
3`/land-and-deploy`
Skill, který merguje PR, čeká na CI a deploy a ověřuje produkci podle uložené konfigurace. Spouštěč deploye jen sleduje.
4Deploy trigger (spouštěč)
Mechanismus, který nasazení rozjede: push do výchozí větve, CI workflow, deploy skript nebo ruční krok. Musí existovat dřív, než ho /land-and-deploy sleduje.
5Produkční URL
Adresa, kterou uživatelé skutečně navštěvují — vlastní doména, nebo výchozí adresa hostitele. Právě ji zadáte do /setup-deploy.
6Secret
Citlivá hodnota (heslo, klíč, token). V tomto příkladu se zadává přímo v nastavení hostitele, nikdy do repozitáře ani do chatu s agentem.
7`.env.example`
Soubor s názvy proměnných a placeholder hodnotami, který se commituje. Dokumentuje, co aplikace potřebuje, aniž by prozrazoval skutečné secrets.
8Build-time vs. runtime proměnná
Proměnná potřebná při sestavení aplikace oproti proměnné čtené až za běhu. Někteří hostitelé injektují proměnné jen za běhu, proto musí být build-time hodnoty zajištěné zvlášť.
9Migrace
Skript, který upraví schéma produkční databáze. Spouští se před tím, než aplikace začne přijímat provoz.
10DNS záznam (CNAME, A, AAAA)
Záznam překládající jméno domény na adresu. CNAME se používá pro subdoménu, A a AAAA pro kořenovou doménu (IPv4 a IPv6).
11`dig +short`
Příkaz, který rychle ukáže, na co se doména překládá. V kroku 5 slouží k ověření, že DNS záznamy začaly platit.
12Health check / health endpoint
Adresa (např. /health), která vrací 2xx, pokud aplikace funguje. Užitečný health check ověřuje i závislosti, například databázi.
13Stavový příkaz (status command)
Příkaz nebo stránka, která vypíše nasazený commit. Dokazuje, že v produkci běží právě mergnutá revize, a ne jen nějaká.
14`## Deploy Configuration`
Sekce v CLAUDE.md, kam /setup-deploy zapíše odpovědi. Z ní pak /land-and-deploy čte URL, spouštěč, ověření a metodu merge.
15`UNREACHABLE` / `COMMAND_FAILED`
Výstupy kontrol po /setup-deploy: health check nedosáhl na URL, resp. stavový příkaz selhal. Jejich nepřítomnost je součástí ověření.
16Dry run
Zkušební průchod pipeline bez nevratných akcí. První běh /land-and-deploy jím začíná.
How-to: diagramy v dokumentech a export mimo PDF
Mermaid a excalidraw diagramy ve fenci v Markdownu, velikost a orientace obrázků, export do HTML a DOCX a přísný režim pro CI — vše offline.
Popis
Co příklad ukazuje
Dokument popisuje diagramový a multiformátový engine, který je součástí /make-pdf a /diagram. Celý běží offline: runtime mermaid a excalidraw jsou vendorované v lib/diagram-render/ a bin/gstack-render.ts je načte do prohlížeče z vašeho počítače na loopbacku jen po dobu jednoho renderu. Žádné CDN, žádná síť.
Čtyři schopnosti
1) Diagram v PDF
Stačí fence v Markdownu (musí začínat ve sloupci 0):
```mermaid title="Render pipeline"
graph LR
A[markdown] --> B[prepass]
```
make-pdf generate doc.md out.pdf vykreslí vektorový diagram (ostrý při jakémkoli zoomu, text lze označit). Zdroj mermaidu zůstává uložený v atributu data-gstack-source (base64, protože HTML komentář by --> rozbil). Fence se dá doladit volbami title, render=false, page=landscape|portrait. Syntakticky vadný diagram se vykreslí jako výrazný červený blok s chybou — dokument se přesto sestaví, ale chyba nejde přehlédnout.
2) Obrázky
Lokální obrázky se vkládají automaticky, nikdy se neořezávají a velké fotografie se zmenší na tiskové rozlišení (300 dpi). Direktivy {width=full|50%|3in} a {page=landscape|portrait} se píší hned za obrázek. Auto-landscape zařadí široký diagram na samostatnou stránku na šířku, ale heuristika je konzervativní (poměr stran ≥ 1,8, šířka přes ~2,5× obsahu a slovo jako diagram/architecture/flowchart v alt textu).
3) Export HTML a Word
--to html vytvoří jeden soběstačný soubor (SVG inline, obrázky jako data URI, žádné síťové odkazy). --to docx zachová obsah — nadpisy, tabulky, kód, seznamy a diagramy jako PNG 300 dpi s alt textem — ale ne perfektní layout.
4) Diagram z angličtiny
/diagram vytvoří trojici souborů: .mmd (zdroj pravdy), .excalidraw (ruční úpravy) a .svg/.png (do dokumentů a chatů).
Bezpečnostní výchozí chování
- Vzdálené (http/https) obrázky jsou blokované a nahrazené viditelným placeholderem, dokud nepřidáte
--allow-network. - Cesta mimo adresář Markdownu (i přes symlink) se vloží, ale s hlasitým varováním.
- Soubory nad 64 MB a nepravidelné soubory (fifo, zařízení) se změní na placeholder, aby se render nezasekl.
- V CI zajistí
make-pdf generate docs.md --strict, že všechny tyto stavy skončí nenulovým kódem místo tichého placeholderu.
Proč je to dobrý návrh
Vektorový diagram ze zdroje je udržovatelný (měníte text, ne obrázek), offline renderování zaručuje reprodukovatelný výsledek bez úniku dat na CDN a přísný režim brání tomu, aby se do publikovaných dokumentů dostaly rozbité obrázky.
Zdrojový kód 1
docs/howto-diagrams-and-formats.md151 řádků
# How to put diagrams in your documents (and export beyond PDF)This guide covers the diagram + multi-format engine that ships with`/make-pdf` and `/diagram` (v1.58.0.0+). Everything here runs fully offline:the mermaid and excalidraw runtimes are vendored in `lib/diagram-render/` andloaded into a browser by `bin/gstack-render.ts`, which serves the bundle fromyour machine on loopback for the length of one render. No CDN, no network atrender time. The browser is your Aside browser when it is open (macOS 15+);when it is not — Linux, Windows, or the app closed — the same bundle renders ingstack's own bundled browser, so it renders offline on every platform (PNGscome out at 1x on the fallback, 2x through Aside).## Render a mermaid diagram inside a PDFPut a fence in your markdown. That's it.````markdown```mermaid title="Render pipeline"graph LR A[markdown] --> B[prepass] B --> C[browser] C --> D[PDF]``````````bashmake-pdf generate doc.md out.pdf```The fence renders as a **vector** diagram (crisp at any zoom, selectabletext), with the `title` as caption and accessibility label. The raw mermaidsource is preserved base64-encoded in a `data-gstack-source` attribute on thefigure for debugging and round-trips (an HTML comment would corrupt mermaid's`-->` arrows). One catch: the fence must start at **column 0** — indentedfences (inside lists, for example) stay plain code blocks by design.**Fence options** (space-separated in the info string):| Option | Effect ||---|---|| `title="..."` | caption below the diagram + `aria-label` || `render=false` | keep the fence as a plain code block || `page=landscape` | force this diagram onto its own landscape page || `page=portrait` | veto auto-landscape for this diagram |A fence that fails to parse renders as a loud red diagnostic block with theparse error and source excerpt — your document still builds, and the erroris impossible to miss.` ```excalidraw ` fences work the same way; the body is a full `.excalidraw`scene file (what excalidraw.com saves with File → Save).## Control image size and orientationLocal images are inlined automatically (relative paths resolve against themarkdown file) and **never truncate** — every image caps at the content box.Oversized photos downscale to print resolution (300dpi at the content width),so a phone photo doesn't bloat the document.Image safety defaults: remote (http/https) images are **blocked with avisible placeholder** unless you pass `--allow-network`. An image path thatresolves outside the markdown's directory (even through a symlink) stillinlines but warns loudly. Files over 64MB and non-regular files (fifos,devices) degrade to a placeholder instead of hanging the render.Per-image directives go immediately after the image:```markdown{width=full}{width=2in}{page=landscape}{page=portrait}````width=` accepts `full`, a percentage (`50%`), or a dimension (`3in`, `8cm`,`200px`). `page=` forces or vetoes a dedicated landscape page.**Auto-landscape:** a wide, small-text, diagram-like image gets its ownvertically-centered landscape page automatically — inside an otherwiseportrait document. The heuristic is deliberately conservative (aspect ratio≥ 1.8, intrinsic width over ~2.5x the content box, and a diagram-ish altword: diagram / architecture / flowchart / chart / graph). If it doesn'tfire when you want it, add `{page=landscape}`; if it fires when you don't,add `{page=portrait}`.## Export single-file HTML or Word```bashmake-pdf generate doc.md out.html --to htmlmake-pdf generate doc.md out.docx --to docx```- **`--to html`** writes ONE self-contained file: diagrams as inline SVG, images as data URIs, zero network references (under the default offline posture — `--allow-network` deliberately keeps remote image tags live), plus a screen-reading layer (centered measure, padding). Email it, attach it, open it anywhere.- **`--to docx`** is a content-fidelity export: headings, tables, code blocks, lists, and diagrams (embedded as 300dpi PNGs with alt text) carry over. Page-perfect layout does not — that's Word's job once it's open.Heads-up: `--to` is the output format. `--format` is an old alias for`--page-size` — different thing.## Generate a diagram from English```/diagram make a flowchart of our deploy pipeline: build, test, canary, promote```The skill authors mermaid and emits a **triplet**:| File | Use it for ||---|---|| `<slug>.mmd` | the source of truth — edit and re-render || `<slug>.excalidraw` | open at excalidraw.com (File → Open), move boxes, hand back || `<slug>.svg` / `<slug>.png` | docs, issues, READMEs, chat |Flowcharts convert to fully editable excalidraw scenes. Other mermaid types(sequence, state, gantt) render to SVG/PNG fine but skip the `.excalidraw`artifact — an upstream converter limitation the skill will tell you about.For documents, embed the `.mmd` source in your markdown instead of the PNG —`/make-pdf` renders it as vector and the diagram stays editable forever.## CI: fail loud instead of shipping placeholders```bashmake-pdf generate docs.md --strict```Missing local images, blocked remote images, out-of-tree image reads (a pathor symlink resolving outside the markdown's directory), oversized files(>64MB), and non-regular files all exit non-zero instead of degrading to awarning or placeholder — for docs pipelines where a broken image shouldbreak the build.## Troubleshooting- **"diagram-render bundle not found"** → run `bun run build:diagram-render` in the gstack repo, or re-run `./setup`.- **Diagram renders but looks squished inline** → it's wide; give it room with `page=landscape` on the fence.- **A two-row "racetrack" loop instead of one long line:** mermaid subgraph trick — top-level `flowchart TB`, two subgraphs with `direction LR` and `direction RL`, connect the *subgraphs* (node-level edges across subgraph boundaries silently disable `direction`).- **"[remote image blocked]" placeholder** → remote images are never fetched by default (offline posture); the tag is replaced with a visible placeholder so the browser can't fetch it at print time either. Pass `--allow-network` to opt in.
Kvíz 15
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Proč render běží offline a runtime mermaidu/excalidrawu jsou vendorované v repozitáři?
Offline render je reprodukovatelný (stejný výsledek na každém stroji), nezávisí na dostupnosti CDN a nic neposílá ven — dokument ani jeho obsah neopustí váš počítač. bin/gstack-render.ts bundle jen na dobu jednoho renderu zpřístupní na loopbacku.
2Proč musí fence začínat ve sloupci 0 a odsazený fence se nevykreslí?
Je to záměrná volba: odsazené fence (třeba uvnitř seznamů) zůstávají obyčejným blokem kódu. Rozhodnutí zabraňuje tomu, aby se z příkladů kódu v dokumentaci náhodou stal diagram. Chcete-li diagram, dejte fence na začátek řádku.
3Proč je diagram vektorový a ne PNG?
Vektor je ostrý při jakémkoli zvětšení, text v něm lze vybírat a vyhledávat a soubor bývá menší. PNG se rastruje při konkrétním rozlišení, takže se při zvětšení rozmaže.
4Proč je zdroj mermaidu uložen base64 v atributu data-gstack-source a ne v HTML komentáři?
Mermaid používá šipky -->, které by HTML komentář předčasně ukončily (--> je konec komentáře) a rozbily dokument. Base64 v atributu je bezpečné a zároveň umožňuje diagram později ladit nebo rekonstruovat.
5Co se stane, když je diagram syntakticky chybný?
Zobrazí se výrazný červený diagnostický blok s chybou parseru a výřezem zdroje. Dokument se přesto sestaví, takže neztratíte zbytek práce, ale chybu je nemožné přehlédnout. V režimu --strict je přísnost navíc u obrázků a souborů.
6Jak funguje auto-landscape a proč je tak opatrné?
Široký, malý a diagramový obrázek dostane vlastní stránku na šířku uprostřed jinak svislého dokumentu. Spouští ho kombinace: poměr stran ≥ 1,8, vnitřní šířka přes ~2,5× obsahu a slovo jako diagram/architecture/flowchart/chart/graph v alt textu. Opatrnost zabraňuje neočekávaným otočeným stránkám; když nezabere, přidáte {page=landscape}, když zasáhne zbytečně, {page=portrait}.
7Proč se vzdálené obrázky blokují výchozím nastavením?
Bezpečnost a soukromí: načtení vzdáleného obrázku při tisku by znamenalo síťový požadavek na cizí server (únik informací o čtenáři a nespolehlivost). Tag se nahradí viditelným placeholderem [remote image blocked], aby ho prohlížeč nemohl stáhnout ani při tisku. Chcete-li je povolit, použijete --allow-network.
8Co dělá varování u cesty mimo adresář Markdownu?
Obrázek, jehož cesta (i přes symlink) vede mimo adresář dokumentu, se vloží, ale s hlasitým varováním. Chrání před nechtěným vložením cizího souboru (například citlivého obrázku) do publikovaného dokumentu. V --strict skončí rovnou chybou.
9Proč má limit 64 MB a vyloučení nepravidelných souborů?
Obří soubory by zpomalily nebo zhroutily render a nepravidelné soubory (fifo, zařízení) by ho mohly navždy zablokovat při čtení. Tyto případy se degradují na placeholder, takže render nikdy neuvízne.
10K čemu je --strict a proč patří do CI?
Chybějící lokální obrázky, blokované vzdálené obrázky, čtení mimo adresář, příliš velké a nepravidelné soubory v něm končí nenulovým exit kódem. V dokumentační pipeline má rozbitý obrázek rozbít build, ne se potichu změnit na placeholder v publikovaném PDF.
11Jak se liší --to a --format?
--to určuje výstupní formát (html, docx). --format je starý alias pro --page-size — jde o úplně jinou věc (velikost stránky). Dokument na tuto záměnu výslovně upozorňuje.
12Co přesně obsahuje výstup --to html a proč se dá poslat e-mailem?
Jediný soubor: diagramy jako inline SVG, obrázky jako data URI a žádné síťové odkazy (při výchozím offline režimu). Protože nic nenačítá zvenčí, otevře se kdekoli bez internetu a nic nechybí.
13Co --to docx zachová a co ne?
Zachová obsah — nadpisy, tabulky, bloky kódu, seznamy a diagramy jako PNG 300 dpi s alt textem. Nezachová dokonalé rozložení stránky; to se dolaďuje až ve Wordu.
14Jakou trojici souborů vytvoří /diagram a k čemu je která?
<slug>.mmd je zdroj pravdy (upravit a znovu vykreslit), <slug>.excalidraw se otevře na excalidraw.com pro ruční úpravy a <slug>.svg/.png jsou do dokumentů, issue a chatů. Do dokumentů se doporučuje vkládat .mmd zdroj, ne PNG, aby diagram zůstal vektorový a editovatelný.
15Proč se pro nefunkčně vypadající diagram doporučuje page=landscape?
Široký diagram vložený do svislé stránky se zmenší, takže vypadá „stlačeně“. page=landscape mu dá vlastní stránku na šířku a vrátí čitelnost.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1Mermaid
Textový jazyk pro diagramy (flowchart, sequence, state, gantt). V příkladu slouží jako zdroj diagramu ve fenci s jazykem mermaid.
2Excalidraw
Nástroj na ručně kreslené diagramy. fence s jazykem excalidraw obsahuje celý scénový soubor; /diagram z flowchartů generuje editovatelný .excalidraw.
3Fence
Ohraničený blok v Markdownu otevřený třemi zpětnými apostrofy a jménem jazyka (zde mermaid). Takový fence se vykreslí jako diagram, pokud začíná ve sloupci 0.
4Vektorový diagram
Diagram vykreslený jako SVG: ostrý při jakémkoli zvětšení, s vyberatelným textem. Opak rastrového PNG.
5`data-gstack-source`
HTML atribut na figuře, ve kterém je base64 zdroj mermaidu. Slouží k ladění a rekonstrukci; HTML komentář by --> rozbil.
6`make-pdf`
Binárka, která převádí Markdown na PDF (a s --to na HTML nebo DOCX). Obsahuje diagramový engine.
7`/diagram`
Skill, který z popisu v přirozeném jazyce vytvoří mermaid a trojici souborů .mmd, .excalidraw, .svg/.png.
8Auto-landscape
Automatické zařazení širokého diagramu na samostatnou stránku na šířku. Řídí ho konzervativní heuristika; přepisují ji direktivy page=.
9Direktiva `{width=…}` / `{page=…}`
Syntaxe hned za obrázkem, která mění šířku (full, 50%, 3in) nebo orientaci stránky (landscape, portrait).
10`--allow-network`
Přepínač, který povolí načítání vzdálených obrázků. Bez něj jsou blokované a nahrazené placeholderem (offline postoj).
11`--strict`
Přísný režim pro CI: chybějící, blokované, příliš velké nebo mimo-adresářové obrázky způsobí nenulový exit kód místo varování.
12Data URI
Obrázek zakódovaný přímo do HTML (data:image/png;base64,…). Díky tomu je --to html jediný soběstačný soubor.
13Loopback render
bin/gstack-render.ts servíruje bundle na loopbacku jen po dobu jednoho renderu. Nic nejde ven a nic se nestahuje z CDN.
14Aside vs. fallback prohlížeč
Render běží v prohlížeči Aside (macOS 15+), pokud je otevřený; jinak v bundlovaném prohlížeči gstacku, takže funguje i na Linuxu a Windows. PNG je na fallbacku 1×, v Aside 2×.
15Content-fidelity export
Typ exportu (DOCX), který zachová obsah a strukturu, ale ne přesné rozložení stránek.
16Placeholder
Viditelná náhrada za obrázek nebo diagram, který nešlo vložit (zablokovaný vzdálený obrázek, příliš velký soubor). Dokument se sestaví, ale problém je vidět.
How-to: zdokumentovat funkci před vydáním
Audit pokrytí dokumentací nad diffem, doplnění mezer přes /document-generate a ověření, že se mezery uzavřely — ještě před merge.
Popis
Co příklad řeší
Funkce je implementovaná a commitnutá na větvi, merge ještě neproběhl. Chcete vědět, co v dokumentaci chybí, a mezery zaplnit. /ship relevantní audit dokumentace spouští sám; samostatné /document-release použijete, když se chcete k auditu vrátit, a /document-generate, když potřebujete napsat chybějící stránky.
Postup
- Audit pokrytí —
/document-releaseprojde diff proti základní větvi, vytáhne nové veřejné plochy (skills, CLI přepínače, konfigurace, endpointy, moduly) a každou ohodnotí podle čtyř kvadrantů Diataxis. Výstupem je coverage map. Položky bez jakéhokoli pokrytí jsou kritické mezery, položky jen s referencí běžné mezery. - Přečtení mezer — z mapy, případně ze sekce
### Documentation Debtv těle PR (pokud PR existuje). U každé položky je napsáno, který kvadrant chybí. - Doplnění —
/document-generates rozsahem omezeným na označené entity; skill povinně nejdřív čte kód a potom píše chybějící dokumenty. - Ověření — znovu
/document-release; dříve prázdná políčka mají být zelená a dluh prázdný nebo omezený na vědomě odložené položky.
Ověření výsledku
Zkontrolujete čtyři věci: audit shrnuje projité a změněné dokumenty (a existující PR má sekci ## Documentation), dluh nemá kritické mezery, vygenerované soubory se čistě otevřou a odkazují na sousedy a grep -rE '\]\([^)]*\.md\)' docs/ nenajde odkaz na neexistující soubor. Tyto kontroly nenahrazují code review, testy ani závěrečné ověření v /ship.
Proč je to nejlepší postup
- Audit míří na diff, ne na celý projekt. Řeší jen to, co tato změna přidala.
- Dluh je pojmenovaný a viditelný. Reviewer ho vidí v PR a nic nezůstane „v hlavě“.
- Generování je oddělené od auditu. Nejdřív se zjistí, co chybí; psaní probíhá až nad vyjmenovanými entitami.
- Uzavírací smyčka. Druhý audit prokáže, že zásah zabral.
- PR není nutné. Bez PR se jen přeskočí aktualizace jeho těla, audit proběhne.
Typické potíže
Hláška „No public surface changes detected“ ještě neznamená hotovo — mohly se změnit instrukce k instalaci, testování nebo workflow. Označený kvadrant nemusí odpovídat vašemu očekávání; audit je vodítko, ne omezení. Tutorial s osmi kroky je třeba zkrátit. A vygenerovaná reference s vymyšlenými signaturami je chyba skillu, kterou je třeba nahlásit s ukázkou textu a skutečného kódu.
Zdrojový kód 1
docs/howto-document-a-shipped-feature.md105 řádků
# How to document a feature before it shipsThis is the pre-merge documentation workflow: the feature is implemented and you want to audit coverage and fill gaps. `/ship` already runs the relevant documentation audit before publication; use standalone `/document-release` on a committed feature branch to revisit it, then `/document-generate` for missing pages.## Prerequisites- gstack installed (`./setup` complete; verify with `which gstack` or by typing `/` in Claude Code and seeing skills listed)- The committed feature branch is checked out, before merge- Optional: an existing GitHub or GitLab PR lets standalone `/document-release` update its body with the coverage mapNo PR is required to audit. `/ship` runs its audit before creating or updating the PR; a standalone invocation without a PR skips the PR-body update.## Steps### 1. Audit current coverageRun:```/document-release```The skill walks your diff against the base branch, extracts new public surface (skills, CLI flags, config options, API endpoints, new modules), and scores each entity across the four Diataxis quadrants. You'll see a coverage map like:```Coverage map: [entity] [reference?] [how-to?] [tutorial?] [explanation?] /new-skill ✅ AGENTS.md ❌ ❌ ❌ --new-flag ✅ README ✅ README ❌ ❌ FooProcessor ❌ ❌ ❌ ❌```Items with zero coverage are **critical gaps**. Items with only reference coverage are **common gaps**. The audit reports both; when a PR exists, it also adds a `### Documentation Debt` subsection for reviewers.If `/document-release` reports everything is covered, you're done. Skip the rest of this how-to.### 2. Read the reported documentation gapsUse the audit's coverage map and gap summary. If a PR exists, open `## Documentation` → `### Documentation Debt` in its body. Each item is tagged with the Diataxis quadrant that would fill it:```### Documentation Debt- ⚠️ /new-skill — has reference in AGENTS.md but no how-to example in README. Diataxis quadrant: how-to.- ⚠️ FooProcessor — zero coverage. Diataxis quadrants: reference, explanation.```This is the input to the next step. Each line tells you what's missing and which quadrant fills it.### 3. Fill the gaps with /document-generateRun:```/document-generate```When the skill asks about scope, tell it the specific entities flagged in the debt section. The skill reads the codebase (its Step 1 archaeology phase is mandatory), partitions by Diataxis quadrant, and writes the missing docs.You can also let the skill auto-discover: if /document-release passed you the gaps explicitly (it does this when chained), `/document-generate` already knows what to write.### 4. Verify the gaps closedRe-run `/document-release`:```/document-release```The coverage map should now show the previously-flagged entities with green checkmarks in the previously-empty quadrants. Reported documentation debt, including the PR-body section when present, should be empty or reduced to items you intentionally deferred.## VerificationRead the audit output and, when present, the PR body. Confirm:1. The audit summarizes the docs reviewed and changed; an existing PR has a `## Documentation` section with a doc-diff preview.2. The reported documentation debt lists zero critical gaps (or only items you knowingly deferred).3. Each generated doc file in `docs/` opens cleanly and cross-links to siblings (reference → how-to → tutorial → explanation).4. Run `grep -rE '\]\([^)]*\.md\)' docs/` and verify no link points to a missing file.These checks complete the documentation pass, with any deferred gaps recorded. They do not replace `/ship`'s code review, tests or final verification.## Troubleshooting**`/document-release` reports "No public surface changes detected."**There may be no new public surface, but still check affected setup, testing, architecture and workflow instructions. A completed audit can report current documentation; an empty public-surface map alone is not that audit.**The Diataxis quadrant tag on a gap doesn't match what you'd expect.**The skill uses an entity taxonomy to decide which quadrants matter (CLI flags want reference + how-to; internal modules want reference + explanation; user-facing features want all four). If you disagree, you can override by hand-editing the docs after generation. The audit is a guide, not a constraint.**`/document-generate` writes a tutorial that takes 8 steps to reach a working result.**Tutorials should hit a working result in 3 steps or fewer. Re-run the skill and ask it to compress, or hand-edit. The Step 8 Quality Self-Review catches some of these but not all.**You want to document a feature but no PR exists yet.**Run standalone `/document-release` on the committed feature branch; it can audit without a PR and skips the PR-body update. Or run `/ship`, which includes the audit before publication.**A generated reference doc has hallucinated API signatures.**File a bug. The skill's Step 1 archaeology is supposed to read implementation files end-to-end, not just signatures, specifically to prevent this. Include the generated text and the actual code so we can trace why the archaeology missed it.## Related- **Tutorial: first time using `/document-generate`:** [tutorial-document-generate.md](./tutorial-document-generate.md)- **Why gstack uses the Diataxis framework:** [explanation-diataxis-in-gstack.md](./explanation-diataxis-in-gstack.md)- **Reference for the audit skill:** [`document-release/SKILL.md`](../document-release/SKILL.md)- **Reference for the generation skill:** [`document-generate/SKILL.md`](../document-generate/SKILL.md)
Kvíz 14
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Proč audit pracuje nad diffem proti základní větvi a ne nad celým projektem?
Cílem je zdokumentovat to, co tato změna přidala. Audit celého projektu by hlásil starý dluh, který s aktuální změnou nesouvisí, a zahltil by reviewera. Diff navíc přesně identifikuje novou veřejnou plochu.
2Co všechno se počítá jako „veřejná plocha“, kterou audit hledá?
Nové skills, CLI přepínače, konfigurační volby, API endpointy a nové moduly. Právě to uživatelé nebo ostatní kód použijí, a proto to potřebuje dokumentaci.
3Jaký je rozdíl mezi kritickou a běžnou mezerou?
Kritická mezera je entita bez jakéhokoli pokrytí (nula kvadrantů). Běžná mezera má jen referenci (například zmínka v AGENTS.md), ale chybí jí how-to, tutorial nebo vysvětlení. Audit hlásí obojí, kritické mají přednost.
4Proč audit označuje u každého dluhu kvadrant Diataxis?
Aby bylo jasné, jaký typ dokumentu chybí a co napsat. „Chybí how-to“ vede k jinému textu než „chybí explanation“. Je to přímý vstup pro /document-generate.
5Musí existovat PR, aby šlo audit spustit?
Ne. Samostatné /document-release funguje na commitnuté větvi bez PR a jen přeskočí aktualizaci těla PR. /ship audit spouští před vytvořením nebo aktualizací PR.
6Proč musí /document-generate před psaním číst kód (archaeology)?
Aby reference a vysvětlení vycházely z implementace, ne z domněnek. Povinné čtení celých souborů (ne jen signatur) je ochrana proti vymyšleným signaturám. Pokud se přesto vymyšlená signatura objeví, jde o chybu skillu a má se nahlásit s ukázkou.
7Proč se po vygenerování znovu spouští /document-release?
Uzavírá smyčku: prokáže, že dříve prázdné kvadranty jsou teď pokryté a dluh zmizel nebo zbyl jen u vědomě odložených položek. Bez druhého auditu nemáte důkaz, že zásah fungoval.
8Jak poznáte, že odkazy ve vygenerovaných dokumentech nevedou do prázdna?
Příkaz grep -rE '\]\([^)]*\.md\)' docs/ vypíše odkazy na .md soubory a vy ověříte, že cílové soubory existují. Vygenerované dokumenty mají na sebe odkazovat v pořadí reference → how-to → tutorial → explanation.
9Co znamená hláška „No public surface changes detected“?
Že se nezměnila veřejná plocha (žádný nový přepínač, skill…), ale neznamená to, že dokumentace je aktuální. Mohly se změnit instrukce k instalaci, testům, architektuře nebo workflow; ty se musí zkontrolovat zvlášť.
10Proč audit nenahrazuje /ship a jeho kontroly?
Dokumentační průchod je jen jedna část vydání. Review kódu, testy a závěrečné ověření řeší /ship. Samotná kontrola dokumentace neříká nic o správnosti kódu.
11Co dělat, když kvadrant přidělený mezeře nesedí?
Skill používá taxonomii entit (CLI přepínač = reference + how-to, interní modul = reference + explanation, uživatelská funkce = všechny čtyři). Nesouhlasíte-li, upravíte dokumentaci ručně — audit je vodítko, ne omezení.
12Proč má tutorial vyžadovat nejvýš 3 kroky k funkčnímu výsledku?
Tutorial je pro nováčka; příliš dlouhá cesta ho odradí. Pokud skill napíše tutorial s osmi kroky, spustí se znovu s pokynem ke zkrácení, nebo se upraví ručně.
13Jak se postupuje, když funkce nemá PR, ale chcete ji zdokumentovat?
Spustíte standalone /document-release na commitnuté větvi, nebo rovnou /ship, který audit zahrnuje před publikací. PR tedy není předpoklad.
14Kdo rozhoduje, které odložené mezery smí zůstat?
Člověk. Ověření požaduje nula kritických mezer „nebo jen položky, které vědomě odkládáte“. Skill mezery nevynucuje potichu zavřít; odklad musí být zaznamenaný jako dluh.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1`/document-release`
Skill, který audituje dokumentaci proti diffu, vytvoří coverage map a v existujícím PR doplní sekci o dokumentačním dluhu.
2`/document-generate`
Skill, který po povinném čtení kódu napíše chybějící dokumenty podle kvadrantů Diataxis.
3Coverage map
Tabulka entit × kvadrantů, která u každé nové funkce ukazuje, kde už dokumentace existuje (✅) a kde chybí (❌).
4Veřejná plocha
To, co funkce odhaluje navenek: skill, CLI přepínač, konfigurační volba, endpoint, modul.
5Kritická mezera
Entita bez jakéhokoli pokrytí v žádném kvadrantu.
6Běžná mezera
Entita, která má jen referenci, ale chybí jí how-to, tutorial nebo explanation.
7Documentation Debt
Podsekce ### Documentation Debt v těle PR, která vyjmenovává chybějící dokumentaci spolu s kvadrantem, který by ji vyplnil.
8Diataxis kvadrant
Jeden ze čtyř typů dokumentu: reference, how-to, tutorial, explanation. Audit podle nich skóruje pokrytí.
9Základní (base) větev
Větev, proti které se počítá diff (typicky main). Audit řeší jen změny od ní.
10Feature branch
Commitnutá větev s funkcí před merge. Tento how-to se spouští právě na ní.
11`/ship`
Skill, který vydává změnu: testy, review, dokumentační audit, verzování, push a PR. Dokumentační audit v něm běží před publikací.
12Archaeology
Povinný první krok /document-generate: čtení struktury, implementace, testů a komentářů, než se napíše jediný řádek dokumentace.
13Cross-link
Odkaz mezi dokumenty (reference → how-to → tutorial → explanation). Kontroluje se grepem a zajišťuje, že dokumentace tvoří souvislou síť.
14Quality Self-Review
Závěrečná kontrola skillu, že dokumenty dodržely svou strukturu. Nezachytí všechno, proto je tu ještě ruční ověření.
15Hallucinated signature
Vymyšlená signatura funkce v dokumentu, která v kódu neexistuje. Archaeology jí má předejít; pokud se objeví, jde o chybu k nahlášení.
16Doc-diff preview
Náhled změn dokumentace v sekci ## Documentation těla existujícího PR, který reviewerovi ukáže, co se v textu změnilo.
How-to: testování iOS aplikací (GStack iOS)
Skutečný iPhone přes USB, debug most v aplikaci, démon na Macu a volitelně vzdálený agent přes Tailscale — bez simulátoru, XCTest ani WebDriverAgent.
Popis
Co příklad ukazuje
Celý řetězec pro QA iOS aplikace na skutečném zařízení: do aplikace se vloží kanonické Swift šablony (balíček DebugBridge), iPhone se připojí přes USB a agent (Claude Code lokálně, nebo libovolný HTTP agent přes Tailscale) ho ovládá — pořizuje screenshoty, čte accessibility strom, klepe, posouvá, píše text a ukládá/obnovuje stav aplikace.
Architektura v jednom obrázku
Vzdálený agent ──tailnet (volitelně)──▶ gstack-ios-qa-daemon (Mac, bun/TS)
│ USB CoreDevice, IPv6 tunel
▼
StateServer v aplikaci (jen loopback)
- StateServer v aplikaci (
DebugBridge, jen#if DEBUG) poslouchá na::1a127.0.0.1portu 9999 a je chráněný bearer tokenem. Jednorázový boot token leží v souboru s oprávněním 0600 vtmp/aplikace (nikdy vos_log); démon ho zkopíruje a do ~5 sekund rotuje, takže pozdější kopie je mrtvý credential. - Mac démon zprostředkuje provoz přes tunel CoreDevice, který
xcrun devicectlotevře po připojení spárovaného zařízení. - Tailscale režim otevírá oddělený listener s capability tiery (observe ⊂ interact ⊂ mutate ⊂ restore), které se vynucují per session token. Tokeny vydává výhradně majitel Macu přes
gstack-ios-qa-mint.
Postup
- Vygenerování balíčku —
gstack-ios-qa-regen --app-source … --bridge-dir …zkopíruje explicitní allowlist šablon, vygenerujeStateAccessor.swifta zapíše verzi; opakování se stejným zdrojem je rychlý, bajtově stejný cache hit. Balíček přidáte jako lokální závislost pouze pro Debug a vApp.init()zavoláteDebugBridgeUIWiring.installAll()aDebugBridgeManager.shared.start(...). - Build a instalace —
xcodebuilds-allowProvisioningUpdatesa vaším Team ID, potomxcrun devicectl device install appaprocess launch. - Démon — buď ho spustí
/ios-qa, nebogstack-ios-qa-daemon(vypíšeREADY: port=… pid=…). Drží exkluzivní flock na~/.gstack/ios-qa-daemon.pid, takže dvě sezení se nepoperou. - Ovládání zařízení — HTTP endpointy
/screenshot,/elements,/state/snapshot,/tap,/swipe,/type,/state/restore; mutace vyžadují hlavičkyAuthorization: BeareriX-Session-Id. - Vzdálený agent (volitelně) —
--tailnet,gstack-ios-qa-mint grant --remote … --capability …, krátkodobý session token přesPOST /auth/mint. - Vydání —
/ios-cleanodstraní závislost a#if DEBUGnapojení pro čistý diff.
Bezpečnost je vrstvená
- Release build bridge nenalinkuje: podmínka
.when(configuration: .debug)vPackage.swiftaDebugBridgeTouch.mzkompilovaný jen za#if TARGET_OS_IOS && DEBUG(prázdná jednotka překladu v Release). - StateServer je loopback-only vždy, i ve vzdáleném režimu; identitu ověřuje Mac, protože iPhone nemá jak ověřit Tailscale identitu.
- Snapshot je opt-in: jen vlastnosti označené komentářem
// @Snapshotable; tokeny a PII se nikdy neexportují. Restore má dvě fáze (nejdřív validace všeho, potom přiřazení na MainActor). - Audit: autentizované mutace se zapisují do
~/.gstack/security/ios-qa-audit.jsonl, odmítnuté pokusy doattempts.jsonl.
Proč je to nejlepší cesta
Testuje se přesně to, co vidí uživatel: skutečný dotyk na skutečném zařízení. Žádný simulátor nemůže „driftovat“, žádný placený testovací servis, vše běží na Macu, iPhonu a bezplatném Apple developer účtu.
Zdrojový kód 1
docs/howto-ios-testing-with-gstack.md255 řádků
# How to test iOS apps with GStack iOSThis is the end-to-end walkthrough for the iOS QA capability that ships with gstack: install the canonical Swift templates into your app, connect a real iPhone over USB, and drive it from any agent (Claude Code locally, or any HTTP-capable agent over Tailscale). No simulators, no XCTest harness, no WebDriverAgent.Everything below has been verified end-to-end on a real iPhone 17 Pro Max running iOS 26.5. The same flow works on any iOS 16+ device.## What you'll need- macOS with Xcode 16.0+ installed (`xcrun devicectl --version` must succeed). Xcode 16 ships the CoreDevice tunnel `devicectl` uses to reach the device over USB.- A real iPhone or iPad running iOS/iPadOS 16 or later (iPad Stage Manager and multi-window layouts are not device-verified yet). Unlocked, paired with your Mac, with **Developer Mode** enabled in Settings → Privacy & Security.- An Apple developer team — the free personal team works fine for live-device debug deploys. You'll need the team ID (e.g. `623FYQ2M88`), not the certificate ID. Find it in Xcode → Settings → Accounts → your Apple ID → team list. The setup signs the app for your device on first deploy via `-allowProvisioningUpdates -allowProvisioningDeviceRegistration`.- gstack installed (`./setup` complete; `gstack-ios-qa-regen` and `gstack-ios-qa-daemon` must be on PATH).- Bun runtime on PATH (`bun --version`). The Mac-side daemon is a bun process.For the optional remote-agent (Tailscale) mode, you'll additionally need Tailscale installed on the Mac with `/var/run/tailscale.sock` readable.## Architecture in one breath```┌─────────────────┐ tailnet (opt) ┌──────────────────────┐ USB CoreDevice ┌─────────────────────┐│ Remote agent │ ─────────────────▶ │ gstack-ios-qa-daemon │ ──────────────────▶ │ iOS app StateServer ││ (Claude, GPT, │ bearer + session │ (Mac, bun/TS) │ IPv6 ULA tunnel │ (loopback only) ││ OpenClaw, ...) │ │ │ │ │└─────────────────┘ └──────────────────────┘ └─────────────────────┘```- iOS app embeds a `StateServer` (`DebugBridge` SPM library, `#if DEBUG` only) listening on `::1` + `127.0.0.1` port 9999. Bearer-token gated. The one-use boot token lives in a 0600 file in the app's `tmp/` (never `os_log`); the daemon copies it out and rotates it within ~5 seconds, which deletes the file, so a later copy is a dead credential. If the app cannot write the file, it logs `NOT READY` and `/healthz` carries `boot_token_error`.- Mac daemon brokers traffic over the CoreDevice IPv6 tunnel that `xcrun devicectl` opens automatically when a paired device is connected.- In Tailscale mode, the daemon exposes a separate listener bound to your tailnet IP, with capability tiers (observe / interact / mutate / restore) enforced per session token. Tokens are minted explicitly by the Mac owner via `gstack-ios-qa-mint`; remote callers never auto-allowlist.The iOS `StateServer` is loopback-only **always**, even in remote mode. Identity validation happens Mac-side because the iPhone has no way to validate a Tailscale identity.## Step 1: Generate the DebugBridge packageRun `/ios-qa` from the app root, or invoke the same deterministic regenerator directly:```bashgstack-ios-qa-regen \ --app-source "$PWD/Sources/YourApp" \ --bridge-dir "$PWD/DebugBridge"```The command copies an explicit allowlist of canonical templates into the local`DebugBridge/` Swift package, generates`DebugBridgeGenerated/StateAccessor.swift`, and writes the installed version to`DebugBridgeGenerated/.gstack-version`. It excludes generated output from itsown schema hash, so rerunning it with unchanged source is a fast, byte-stablecache hit. It also removes the explicit legacy generated-file set from olderflat harness layouts so stale bridge sources cannot shadow the package.1. Add `DebugBridge/` as a local package dependency. Depend on the `DebugBridgeUI` product only in Debug configuration; `DebugBridgeCore` and `DebugBridgeTouch` come in transitively.2. Add `DebugBridgeGenerated/StateAccessor.swift` to the app target.3. In your `@main` App init, install the UIKit resolvers before starting the server, then register the generated accessor. Replace the example state/accessor names with the type the generator found: ```swift #if DEBUG import DebugBridgeCore #if canImport(UIKit) import DebugBridgeUI #endif #endif // Inside App.init(), after appState is initialized: #if DEBUG #if canImport(UIKit) DebugBridgeUIWiring.installAll() #endif DebugBridgeManager.shared.start( appState: appState, register: AppStateAccessor.register ) #endif ```The three SwiftPM targets split as: `DebugBridgeCore` is cross-platform (so `swift build` on a CI Mac host can validate the bulk of the code without UIKit), `DebugBridgeUI` and `DebugBridgeTouch` are iOS-only (they link UIKit). `DebugBridgeTouch` is Objective-C — it carries the KIF-derived UITouch synthesis with the iOS 18+ `_UIHitTestContext` fix that makes SwiftUI Button taps actually fire.The structural Release-build guard is layered. The `.when(configuration: .debug)` clause in `Package.swift` means SwiftPM refuses to link any `DebugBridge*` target in a Release build, so the bridge cannot ship to TestFlight even if you forget to clean up. On top of that, `DebugBridgeTouch.m`'s private-API touch synthesis is compiled behind `#if TARGET_OS_IOS && DEBUG` (with `DEBUG` defined for that target only in the debug configuration via `cSettings` in `Package.swift`), so a Release compile of the touch bridge emits an empty translation unit — zero private symbols in the binary even if the linker guard were bypassed.## Step 2: Build + install to the deviceFrom the app's project directory:```xcodebuild \ -scheme YourAppScheme \ -configuration Debug \ -destination 'generic/platform=iOS' \ -derivedDataPath /tmp/build \ -allowProvisioningUpdates -allowProvisioningDeviceRegistration \ CODE_SIGN_STYLE=Automatic \ DEVELOPMENT_TEAM=YOUR_TEAM_ID \ build```Then install + launch:```UDID=$(xcrun devicectl list devices 2>/dev/null | awk 'NR>2 && $0!="" {print $(NF-2); exit}')xcrun devicectl device install app --device "$UDID" /tmp/build/Build/Products/Debug-iphoneos/YourApp.appxcrun devicectl device process launch --device "$UDID" --terminate-existing your.bundle.id```If the phone is locked you'll get `FBSOpenApplicationServiceErrorDomain error 1 — Locked`. Unlock and retry. First-time installs surface a Trust dialog on the phone; tap Trust, then re-run.## Step 3: Start the Mac-side daemonTwo options.**Option A — let the skill spawn it.** Run `/ios-qa` in Claude Code from anywhere; the skill spawns the daemon on demand, bootstraps the tunnel, rotates the boot token, and exposes the device through the proxy. Cleanest path for local-USB use.**Option B — start it yourself.** Run:```gstack-ios-qa-daemon```The daemon prints `READY: port=<n> pid=<pid>` once both loopback listeners are bound. The default port is 9099. Spawners can read that line with a ~5 second timeout to confirm readiness; you can also point `curl` at the printed port.Either way the daemon takes an exclusive flock on `~/.gstack/ios-qa-daemon.pid` — running it twice from two Claude Code sessions is safe; the second invocation discovers the running daemon's port and joins.Set these env vars to target a specific device or bundle:```GSTACK_IOS_TARGET_UDID=248C3A58-B843-5BDB-8F5D-89ADB7D7BF6AGSTACK_IOS_TARGET_BUNDLE_ID=com.yourorg.yourappGSTACK_IOS_DAEMON_PORT=9099 # loopback listener port; default 9099GSTACK_IOS_LAUNCH_ENV='{"DEBUG_BRIDGE":"1"}' # optional: env for the app when the daemon launches it````GSTACK_IOS_LAUNCH_ENV` is for apps whose debug bridge (or anything else) isgated on an environment variable. It is a JSON object of string to string, andthe daemon passes it to `xcrun devicectl device process launch--environment-variables` on every launch it performs, including the one forcedrelaunch below. It only takes effect when the daemon launches the app; an appthat is already running keeps the environment it started with. Invalid JSON, anon-string value, or a `GSTACK_` key (reserved for the debug bridge) refuses thelaunch with `IOS_LAUNCH_ENV_INVALID` instead of starting the app without it.If `GSTACK_IOS_TARGET_UDID` is unset, the daemon picks the best paired,available iPhone or iPad, preferring a wired device. When two devices tie (aniPhone and an iPad both on USB), it refuses to guess: the bootstrap error listseach device with its UDID and prints a ready`export GSTACK_IOS_TARGET_UDID=<udid>` line.The daemon keeps a healthy rotated tunnel for its lifetime. When the CoreDeviceroute drops (`503 device_disconnected` / `504 upstream_timeout`), it re-resolvesthe tunnel address for the same UDID and probes the running app with the bearerit already holds, so the app keeps its state. It bootstraps again only when theapp rejects that bearer (401, the app was relaunched), the app is not running(one normal launch), or a different device is now selected; the old bearer isnever sent to another device. A tap or other mutation whose response was lostis never replayed.If a newly started daemon reaches an already-running target whose one-use boottoken was consumed by an earlier daemon, it verifies the bundle owner, forcerelaunches that target once, waits for a fresh token, verifies ownership again,and rotates normally.## Step 4: Drive the deviceOnce the daemon is running, you have an HTTP surface at `http://127.0.0.1:9099` (or `[::1]:9099`). The skill flow does this for you, but the raw endpoints are:| Endpoint | What it does | Auth ||---|---|---|| `GET /healthz` | Version probe. | none (loopback) || `POST /auth/rotate` | Daemon-only; rotates the boot token to an in-memory-only value. | boot token || `POST /session/acquire` | Acquire the per-device session lock. Returns `{session_id, ttl_seconds}`. | bearer || `POST /session/release` | Release the lock. | bearer + session || `GET /screenshot` | Capture a PNG of the active window. Returns `{png_base64: "..."}`. | bearer || `GET /elements` | Accessibility-tree snapshot. | bearer || `GET /state/snapshot` | Dump every `// @Snapshotable` field as JSON. | bearer || `POST /state/restore` | Validate the full snapshot, then restore it on MainActor. | bearer + session, mutate tier || `POST /tap` `{x,y}` | Synthesize a real UITouch at window coordinates. SwiftUI Buttons fire. | bearer + session, interact tier || `POST /swipe` `{from_x,from_y,to_x,to_y}` | Scroll the nearest enclosing UIScrollView. | bearer + session, interact tier || `POST /type` `{text}` | Set text on the current first responder. | bearer + session, interact tier |Mutating requests require both an `Authorization: Bearer <token>` header AND an `X-Session-Id` header. Read endpoints (`/screenshot`, `/elements`, `GET /state/*`) only need the bearer.The state snapshot is opt-in per field via a standalone generator markercomment immediately above a property. It is intentionally not a propertywrapper, so it compiles cleanly with Observation:```swift@Observablefinal class AppState { // @Snapshotable var username: String = "" var authToken: String = "" // never exported}```Unmarked fields never appear in the snapshot, which keeps tokens, PII, andauth state out of recorded fixtures by default. A marked field must be awritable instance `var` on a file-scope observable class, with an explicit typeand an internal or public setter. Supported snapshot types are JSON-nativescalars (`String`, `Bool`, signed/unsigned integer widths, `Float`, `Double`,`CGFloat`), arrays, String-keyed dictionaries, and Optional compositions ofthose types. Snapshot keys must be unique across observable classes. Thegenerator reports and stops on invalid declarations, custom values, implicitlyunwrapped Optionals, nested observable classes, or duplicate keys instead ofemitting broken or lossy Swift. Restore uses two phases: every model validatesthe complete input first, and only then are assignments applied on MainActor.## Step 5: Make remote agents work (optional)To let an agent on another machine drive the device, run the daemon with `--tailnet`:```gstack-ios-qa-daemon --tailnet```The daemon probes `/var/run/tailscale.sock` first; if the socket is missing or unreadable, it refuses to open the tailnet listener at all (loopback still runs). Remote mode never half-starts.Then mint a session token for the identity that should be able to connect:```gstack-ios-qa-mint grant --remote 'alice@example.com' --capability interactgstack-ios-qa-mint grant --remote 'tag:ci' --capability mutate --ttl 86400 --note 'nightly'gstack-ios-qa-mint list```Capability tiers are nested: `observe` (read endpoints only) ⊂ `interact` (taps, swipes, type) ⊂ `mutate` (`POST /state/*`) ⊂ `restore` (`POST /state/restore`). Pick the smallest tier that does the job. The allowlist file is at `~/.gstack/ios-qa-allowlist.json` (mode 0600) — the daemon reads it on every `/auth/mint` request, so changes take effect immediately without restarting.The remote agent then hits `POST /auth/mint` against the daemon's tailnet listener. The daemon canonicalizes the caller's identity via tailscaled's WhoIs endpoint, checks the allowlist, and returns a short-lived session token (1 hour default, 24 hour cap). Every authenticated mutating request lands in `~/.gstack/security/ios-qa-audit.jsonl`; rejected requests land in `~/.gstack/security/attempts.jsonl`.## Step 6: Ship a release buildBefore you ship to TestFlight or the App Store, run `/ios-clean`. It removes the `DebugBridge` SPM dependency and strips the `#if DEBUG` wiring from your `@main` App. The structural guard in `Package.swift` (`condition: .when(configuration: .debug)`) means a Release build wouldn't link the bridge even if you forgot to clean up, but `/ios-clean` gives you a tidy diff to review and ship.## Common failures| Symptom | What broke ||---|---|| `xcodebuild` fails with `Could not locate device support files for iOS X.Y` | Run `xcodebuild -downloadPlatform iOS` to fetch the device support package for your iPhone's iOS version (~8GB). || Install succeeds, `process launch` fails with `Locked` | The phone is locked. Unlock and retry. || First install on a paired device fails with no clear error | The phone needs to Trust the Mac. Open Settings → General → VPN & Device Management on the phone and confirm. || `Developer Mode` toggle missing from Settings → Privacy | Connect the device to Xcode → Window → Devices and Simulators once, or try any `devicectl device install` against it. iOS will surface the toggle after the first attempt. || `xcrun devicectl device copy from` returns ERROR 7000 | The source path is wrong — boot token lives at `tmp/gstack-ios-qa.token` inside the app's data container (NSTemporaryDirectory), not at the path's root. || Bootstrap fails with `multiple_devices` | More than one iPhone/iPad is connected. Run the printed `export GSTACK_IOS_TARGET_UDID=<udid>` and restart the daemon. || Launch refused with `(IOS_LAUNCH_ENV_INVALID)` | `GSTACK_IOS_LAUNCH_ENV` is not a JSON object of string to string, or sets a `GSTACK_` key. Fix or unset it and restart the daemon; see [troubleshooting](troubleshooting.md#ios-launch-env-invalid). || `boot_token_unavailable ... could not write tmp/gstack-ios-qa.token` | The app could not write its boot-token file. Fix the app's `tmp/` directory and relaunch the app. || A SwiftUI `DragGesture` or `Canvas` ignores taps and swipes on iOS 26 | Synthesized in-process touches do not reach SwiftUI gesture recognizers on iOS 26, and `/swipe` only scrolls a `UIScrollView`. See "Known limits" in the `/ios-qa` skill for the input-routing workaround. || `/healthz` returns 200 but `/tap` returns ok:true with no UI change | The phone is paired but the StateServer port may have changed across launches. Re-resolve the CoreDevice IPv6 (`dscacheutil -q host -a name '<DeviceName>.coredevice.local'`). || `403 identity_not_allowed` from `/auth/mint` | The remote caller's identity isn't on the Mac's allowlist. Run `gstack-ios-qa-mint grant --remote <identity> --capability interact` on the Mac. || Daemon won't open the tailnet listener | Tailscale isn't installed, or `/var/run/tailscale.sock` is unreadable. Fix Tailscale, then restart the daemon. Loopback still runs in the meantime. || SwiftUI Button tap returns `ok:true` but the action never fires | You're on iOS 17 or older where `_UIHitTestContext` doesn't exist. The DebugBridgeTouch implementation falls back to plain `hitTest:` which doesn't resolve into SwiftUI's gesture container. Update to iOS 18+ on the device, or tap a UIKit control instead. |## What this gets youYou can write an agent loop in any language that speaks HTTP. Take a screenshot, ask a model what to do, send a tap. Capture state snapshots before and after to record deterministic fixtures for `/ios-fix` regression tests. Add a colleague to the allowlist and they drive your iPhone from their laptop over Tailscale without ever touching the hardware. Plug the same daemon into CI by minting a `tag:ci` session token with mutate-tier capability and a 24-hour TTL.The whole stack is a Mac you already own, an iPhone you already own, a free Apple developer account, and gstack. No paid testing service. No simulator drift. The thing the user sees is what the agent drives.
Kvíz 16
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Proč se testuje na skutečném iPhonu přes USB, a ne v simulátoru?
Dokument to označuje za hlavní výhodu: agent ovládá přesně to, co vidí uživatel. Žádný simulátor nemůže driftovat (jiné chování než zařízení), nepotřebuje se XCTest harness ani WebDriverAgent a nic se neplatí třetí straně. Vše běží na Macu, telefonu a bezplatném účtu Apple developer.
2Proč je StateServer v aplikaci vždy jen na loopbacku (::1 a 127.0.0.1)?
iPhone nemá jak ověřit Tailscale identitu volajícího, takže ověření probíhá na Macu. Kdyby StateServer poslouchal na síti, mohl by ho zavolat kdokoli v dosahu. Loopback znamená, že se k němu dostane jen proces na stejném zařízení, tj. most z Macu přes CoreDevice tunel.
3K čemu je boot token a proč ho démon do ~5 sekund rotuje?
Boot token je jednorázový přístup, kterým se démon poprvé přihlásí. Leží v souboru s oprávněním 0600 v tmp/ aplikace (nikdy v os_log). Démon ho zkopíruje a rotuje na hodnotu jen v paměti; rotací se soubor smaže, takže pozdější kopie je mrtvý credential. Zkracuje se tím okno, kdy by token mohl někdo zneužít.
4Jak je zajištěno, že debug most nepřijde do TestFlight nebo App Store?
Dvěma vrstvami: v Package.swift je .when(configuration: .debug), takže SwiftPM v Release DebugBridge* cíle vůbec nenalinkuje, a DebugBridgeTouch.m s private-API syntézou dotyků je za #if TARGET_OS_IOS && DEBUG, takže Release vytvoří prázdnou jednotku překladu bez privátních symbolů. Navíc /ios-clean dá před vydáním čistý diff.
5Proč jsou capability tiery vnořené (observe ⊂ interact ⊂ mutate ⊂ restore)?
Každý vyšší tier zahrnuje nižší a dává větší sílu: observe jen čte, interact klepe/píše, mutate mění stav, restore přepisuje celý stav. Princip nejmenších oprávnění říká vybrat nejmenší tier, který úkol zvládne; třeba nightly CI s mutate a 24h TTL místo plného přístupu.
6Proč musí mutace mít bearer token i hlavičku X-Session-Id?
Bearer prokazuje, že volající smí s démonem mluvit; session id prokazuje, že drží zámek zařízení získaný přes /session/acquire. Díky tomu nemohou dva agenti současně klepat na jedno zařízení a mutace bez zámku se odmítnou. Čtecí endpointy (screenshot, elements, GET state) vystačí s bearerem.
7Co zaručí flock na ~/.gstack/ios-qa-daemon.pid?
Že na jednom Macu běží nejvýš jeden démon. Druhé spuštění z jiného sezení Claude Code zjistí běžící démon, najde jeho port a připojí se k němu. Je tedy bezpečné ho spustit víckrát.
8Proč je snapshot stavu opt-in přes // @Snapshotable a ne automatický?
Automatický export by do fixtures mohl dostat tokeny, osobní údaje nebo auth stav. Neoznačená pole se v snapshotu nikdy neobjeví, takže citlivé hodnoty zůstanou venku ve výchozím nastavení. Marker je komentář, ne property wrapper, aby se bez problémů kompiloval s Observation.
9Proč restore stavu probíhá ve dvou fázích?
Nejdřív každý model zvaliduje celý vstup a teprve potom se přiřazení provedou na MainActor. Vadný snapshot tak nenechá aplikaci napůl obnovenou. Generátor navíc odmítne neplatné deklarace (nested observable, duplicitní klíče, implicitně unwrapped Optional) místo vygenerování ztrátového Swiftu.
10Jak vzdálený agent dostane přístup a proč ne automaticky?
Majitel Macu vydá záznam příkazem gstack-ios-qa-mint grant --remote <identita> --capability <tier>. Vzdálený agent pak zavolá POST /auth/mint; démon identitu kanonizuje přes WhoIs od tailscaled, zkontroluje allowlist a vrátí krátkodobý session token (1 h, strop 24 h). Allowlist (~/.gstack/ios-qa-allowlist.json, mód 0600) se čte při každém požadavku, takže změna platí hned. Vzdálení volající se nikdy neprohlásí za důvěryhodné sami.
11Co se stane, když Tailscale není nainstalovaný nebo je socket nečitelný?
Démon odmítne otevřít tailnet listener vůbec (vzdálený režim se nikdy nespustí jen napůl), ale loopback dál běží. Nemůže tedy vzniknout napůl zabezpečené vzdálené rozhraní.
12Kam se logují mutace a odmítnuté pokusy a proč dva soubory?
Autentizované mutace jdou do ~/.gstack/security/ios-qa-audit.jsonl (co se skutečně provedlo), odmítnuté pokusy do ~/.gstack/security/attempts.jsonl (kdo se pokusil a neuspěl). Oddělení usnadňuje auditu odpovědět na „co se změnilo“ i „kdo zkoušel nepovolený přístup“.
13Proč SwiftUI Button tap vyžaduje iOS 18+ a co se stane na iOS 17?
DebugBridgeTouch používá syntézu UITouch odvozenou z KIF s opravou _UIHitTestContext (iOS 18+). Na starších verzích kontext neexistuje, hit-test se vrací k obyčejnému hitTest:, který nedohledá gesture container SwiftUI, takže tap vrátí ok:true, ale akce se nespustí. Řešení: aktualizovat zařízení, nebo klepnout na UIKit ovládací prvek.
14Co zkusit, když process launch selže s Locked?
Telefon je zamčený. Odemknout a zopakovat. Při první instalaci se navíc na telefonu objeví dialog Trust; po potvrzení se příkaz spustí znovu.
15Jak se řeší chyba multiple_devices?
Démon odmítne hádat, když jsou připojena dvě zařízení se stejnou prioritou (například iPhone a iPad na USB). Chybová hláška vypíše UDID každého a hotový řádek export GSTACK_IOS_TARGET_UDID=<udid>; po jeho spuštění se démon restartuje.
16Proč GSTACK_IOS_LAUNCH_ENV odmítne klíč začínající GSTACK_?
Takové klíče jsou rezervované pro samotný debug most. Neplatný JSON, nestringová hodnota nebo klíč GSTACK_ ukončí spuštění chybou IOS_LAUNCH_ENV_INVALID místo spuštění aplikace bez požadovaného prostředí — selže hlasitě, ne tiše.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1DebugBridge
Swift balíček vložený do aplikace jen pro Debug. Obsahuje StateServer a nástroje pro dotyky, screenshoty a snapshot stavu.
2StateServer
HTTP server uvnitř aplikace na ::1 a 127.0.0.1 portu 9999 chráněný bearer tokenem. Provádí příkazy z démona.
3`gstack-ios-qa-daemon`
Mac proces v Bunu, který přes USB tunel zprostředkuje provoz mezi agentem a aplikací. Poslouchá na loopbacku (výchozí port 9099) a volitelně na tailnetu.
4CoreDevice tunel
IPv6 tunel, který xcrun devicectl otevře po připojení spárovaného zařízení. Přes něj démon dosáhne na aplikaci.
5`devicectl`
Příkaz Xcode 16+ (xcrun devicectl) pro práci se zařízením: seznam, instalace aplikace, spuštění procesu.
6Boot token
Jednorázový token v souboru tmp/gstack-ios-qa.token (0600). Démon ho zkopíruje a rotuje, čímž se soubor smaže.
7Rotace tokenu
Nahrazení boot tokenu novou hodnotou držící se jen v paměti (POST /auth/rotate), aby starý token přestal platit.
8Session lock
Zámek zařízení získaný přes /session/acquire, který vrátí session_id a TTL. Mutace bez něj se odmítnou.
9Capability tier
Úroveň oprávnění session tokenu: observe, interact, mutate, restore (každá zahrnuje předchozí).
10Tailnet
Soukromá síť Tailscale. Se --tailnet démon otevře další listener vázaný na tailnet IP pro vzdálené agenty.
11`gstack-ios-qa-mint`
Nástroj majitele Macu pro správu allowlistu: grant, list. Bez něj vzdálený volající nic nezíská.
12WhoIs (tailscaled)
Dotaz na tailscaled, který pro volajícího vrátí kanonickou identitu; pak se porovná s allowlistem.
13`// @Snapshotable`
Komentářový marker nad vlastností, která se smí exportovat do snapshotu stavu. Neoznačené vlastnosti zůstávají mimo.
14MainActor
Swift actor hlavního vlákna UI. Restore na něm přiřazuje hodnoty až po úspěšné validaci celého vstupu.
15`.when(configuration: .debug)`
Podmínka v Package.swift, kvůli které SwiftPM nalinkuje DebugBridge jen v Debug konfiguraci.
16`/ios-clean`
Skill, který před vydáním odstraní závislost DebugBridge a #if DEBUG napojení v @main App.
QA bez webové stránky (CLI, API, joby, webhooky)
Stejné příkazy /qa a /qa-only pro software bez prohlížeče: explorační testování s důkazy, regresní testy, které selžou před opravou, a bezpečné hranice fixture.
Popis
Co příklad ukazuje
/qa a /qa-only se nepoužívají jen pro weby. Stejně jim zadáte CLI, API, job, worker nebo webhook. Začnete v repozitáři s dokumentovaným nativním příkazem a izolovanou lokální fixture, pojmenujete cíl a chování, které chcete ověřit. Dokument uvádí dva vzorové prompty:
/qa-only— otestuje CLI na validní a nevalidní vstup, exit kódy, stdout/stderr a zrušení; jen hlásí, nic nemění. U každého nálezu uvede přesný příkaz, očekávaný a skutečný výsledek a co zůstalo neověřené./qa— otestuje lokální webhook a worker, zkoumá duplicitní doručení a obnovení po částečném selhání; reprodukované chyby zachytí v nativních regresních testech a teprve potom je opraví.
Jak QA postupuje
- Oznámí rozsah: který povrch, jaké nástroje a jaká oprávnění k zápisu bude používat. CLI ani API prohlížeč nepotřebují; browser cíle zachovávají skutečné testování v prohlížeči; audity vývojářské zkušenosti se načtou jen tehdy, když jde o onboarding, instalaci nebo ergonomii.
- Prozkoumává, ne střílí naslepo. Před každým dalším průzkumným krokem uloží krátkou poznámku
exploration-NNN.json(předchozí výsledek, testovaný předpoklad, další příkaz). Závěrečná zpráva na ně odkazuje. - Každý nález musí být reprodukovatelný. Nový test musí před opravou selhat a po opravě projít.
/qa-onlytesty jen navrhne. - Co chybí, se přizná. Pokud chybí nativní nástroje nebo bezpečná fixture, zpráva pojmenuje blokátor a neověřené kontrakty; nevymýšlí si úspěch ani neinstaluje další framework.
Hranice a pojistky
- Efekty zůstávají uvnitř fixture; před kontaktem s externí službou se QA ptá.
- Produkční přístup a destruktivní nebo externí efekty vyžadují konkrétní povolení.
- Omezená exploration používá spustitelný deadline guard (ne odhad času): odmítne pozdní sondy a zastaví vlastní popředí na limitu. Nedokončené kontroly zůstanou ve zprávě viditelné.
- Běžné
/reviewa/shipspouštějí omezenou verzi automaticky i pro malé diffy bez plánu a webového serveru; krátký smoke test nikdy neznamená vyčerpávající QA. - Každý ship spouští také dokumentační audit; jasné faktické opravy se zahrnou do kontrolované změny, rizikové přepisy potřebují souhlas, a selhání auditu zastaví postup. Verzování, git a PR vlastní ship, ne dokumentační helper.
Proč je to nejlepší a bezpečné
Unit testy chrání logiku, integrační a e2e testy chrání skutečné hranice, které mocky skrývají. Požadavek „test musí před opravou selhat“ je důkaz, že test opravdu chytá tu chybu. Důkazní poznámky dělají exploration auditovatelnou a fixture drží vedlejší efekty pod kontrolou.
Zdrojový kód 1
docs/qa-without-a-webpage.md44 řádků
# QA without a webpageUse the same commands for browser and non-browser software. Start in a repositorywith its documented native command and an isolated local fixture; name the targetand the behavior you want checked. For example:```text/qa-only Test this repo's CLI using its documented local fixture. Check valid and invalid input, exit codes, stdout/stderr, and cancellation. Report only; do not change code or tests. For each finding, include the exact command, expected and actual results, and which checks remain untested. Keep requests inside the fixture; ask before contacting an external service./qa Test this repo's local webhook and worker fixture. Explore duplicate deliveries and recovery after a partial failure. Keep all effects inside the fixture; preserve reproduced bugs in native regression tests before repairing them.```QA first tells you which surface, tools and write permissions it will use. A CLI orAPI does not need a browser. Browser targets keep real browser testing; developerexperience audits load only when onboarding, installation or ergonomics are in scope.If the native tools or safe fixture are unavailable, the report names the blockerand untested contracts instead of inventing a pass or installing another framework.Exploration means learning from each result and choosing the next useful challenge,not running random commands. Before the next discovery probe, QA saves a short`exploration-NNN.json` evidence note with the previous result, the assumption beingtested and the next command. The final report links these notes; they do not requirean extra chat message between probes. A discovered bug must be reproducible, and its new testmust fail for the bug before the repair and pass afterward. Unit tests protect logic;integration and end-to-end tests protect real boundaries that mocks would hide.`/qa-only` proposes those tests without writing them.Normal `/review` and `/ship` run a bounded version on changed behavior and nearbyrisks automatically, including small diffs without a plan or web server. Existingfix/test approval rules still apply. Missing dependencies, denied actions and timelimits remain visible coverage gaps; a short smoke pass never means exhaustive QA.Production access and destructive or external effects require specific permission.Bounded exploration uses an executable deadline guard, not an estimated clock: itrefuses late probes and stops owned foreground work at the limit. Unfinished checksstay visible in the report. Required plan checks remain outside the review/ship smokebudget. See [QA deadlines](reference-qa-deadlines.md) for command, platform andcleanup limits.Every ship also runs the existing documentation audit, including repeat ships andexisting PR updates. Clear factual corrections join the final checked change; riskyrewrites need approval. A failed audit stops for recovery or explicit acceptance ofthe named risk rather than silently dropping its result. Ship owns versioning, Gitand PR publication; the docs helper does not commit or push independently.
Kvíz 14
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Proč lze stejné příkazy /qa a /qa-only použít i pro CLI, API nebo webhook?
Protože QA neprovádí jen klikání v prohlížeči, ale zkoumá chování přes nativní nástroje daného povrchu: příkazy, exit kódy, stdout/stderr, HTTP volání. Před začátkem oznámí, jaký povrch a nástroje použije. CLI ani API prohlížeč nepotřebují, zatímco browser cíle dál testují skutečným prohlížečem.
2Jaký je rozdíl mezi /qa a /qa-only?
/qa-only pouze hlásí — nálezy, důkazy a navržené regresní testy, ale nic nezapisuje do kódu ani testů. /qa navíc reprodukované chyby zachytí v nativních regresních testech a teprve potom je opraví. Volba závisí na tom, zda chcete jen zprávu, nebo i opravu.
3Proč musí nový regresní test před opravou selhat a po ní projít?
Test, který prošel vždycky, nic nedokazuje — mohl by testovat něco jiného. Selhání před opravou prokazuje, že test skutečně chytá reprodukovanou chybu, a průchod po opravě, že oprava zabrala. Je to jediný způsob, jak mít jistotu, že regrese nevznikne znovu.
4K čemu jsou soubory exploration-NNN.json?
Jsou to krátké důkazní poznámky: výsledek předchozí sondy, testovaný předpoklad a další příkaz. Dělají z průzkumu úsudek, ne náhodné příkazy, jsou auditovatelné a závěrečná zpráva na ně odkazuje. Nevyžadují zprávu v chatu mezi sondami, takže neruší.
5Proč musí být práce omezená na izolovanou lokální fixture?
Aby test nezpůsobil skutečné vedlejší efekty — nezměnil produkční data, neodeslal e-mail ani nezavolal placenou externí službu. Fixture drží všechny efekty uvnitř; pro externí službu se QA musí zeptat.
6Co se stane, když chybí nativní nástroje nebo bezpečná fixture?
Zpráva pojmenuje blokátor a seznam neověřených kontraktů. QA nevymýšlí úspěch („vše prošlo“) a neinstaluje jiný testovací framework, aby se vyhnulo problému. Nepravdivý úspěch by byl horší než přiznaná mezera.
7Jak funguje deadline guard a proč není jen odhad času?
Je to spustitelná pojistka: odmítne pozdní sondy a zastaví vlastní popředí na limitu. Odhad času by agent mohl nedodržet, kdežto guard to vynutí kódem. Nedokončené kontroly zůstanou ve zprávě jako viditelné mezery.
8Proč krátký smoke pass nikdy neznamená vyčerpávající QA?
Omezená verze v /review a /ship testuje změněné chování a blízká rizika v časovém rozpočtu. Chybějící závislosti, odepřené akce a časové limity zůstanou jako coverage gaps ve zprávě, takže nikdo nemůže tvrdit, že je „všechno otestováno“.
9Jaký je rozdíl mezi unit, integračním a e2e testem podle dokumentu?
Unit testy chrání logiku. Integrační a end-to-end testy chrání skutečné hranice (procesy, síť, úložiště), které by mocky skryly. Webhook s duplicitním doručením se proto ověřuje na reálné hranici, ne na mocku.
10Proč se zkoumá duplicitní doručení a obnovení po částečném selhání u webhooků a workerů?
Jsou to typické chyby distribuovaných systémů: doručení se může opakovat a worker může spadnout uprostřed práce. Zpracování musí být idempotentní a obnovitelné. Tyto scénáře odhalí chyby, které se v šťastné cestě neukážou.
11Co musí obsahovat každý nález ve zprávě?
Přesný příkaz, očekávaný a skutečný výsledek a seznam toho, co zůstalo neověřeno. Díky tomu je nález reprodukovatelný a vidíte, kde pokrytí končí.
12Kdy je potřeba výslovné povolení?
Pro produkční přístup a pro destruktivní nebo externí efekty. Bez konkrétního povolení QA zůstává v izolované fixture.
13Co dělá dokumentační audit, který běží při každém shipu?
Zkontroluje relevantní dokumentaci i při opakovaných shipech a aktualizaci existujícího PR. Jasné faktické opravy se připojí k závěrečné zkontrolované změně, rizikové přepisy potřebují schválení, a selhaný audit zastaví postup k obnovení nebo výslovnému přijetí pojmenovaného rizika.
14Proč dokumentační helper necommituje a nepushuje sám?
Verzování, git a publikaci PR vlastní ship — jeden majitel zabraňuje konfliktům a nechtěným commitům. Helper jen připraví změnu dokumentace, o jejím zařazení rozhoduje ship.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1`/qa`
Skill, který prozkoumá chování (browser, API, CLI, job, worker, webhook), reprodukuje chyby, dokáže regresní test a opraví je. Ví, že stejné příkazy platí i bez webu.
2`/qa-only`
Varianta, která stejným způsobem zkoumá, ale nic nezapisuje — jen hlásí a navrhuje regresní testy.
3Fixture
Izolované lokální prostředí s testovacími daty, v němž se testuje. Drží všechny vedlejší efekty uvnitř, aby test nepoškodil nic skutečného.
4Povrch (surface)
Druh rozhraní, které se testuje: prohlížeč, CLI, API, job, worker, webhook. QA před začátkem oznámí, který použije.
5Exploration
Cílené zkoumání, kdy se z výsledku učíte a vybíráte další užitečnou výzvu; opak náhodného spouštění příkazů.
6`exploration-NNN.json`
Důkazní poznámka uložená před další sondou: předchozí výsledek, testovaný předpoklad a další příkaz.
7Regresní test
Test, který zachytí reprodukovanou chybu, aby se nevrátila. Musí před opravou selhat a po ní projít.
8Exit kód
Číselný výsledek procesu (0 = úspěch). U CLI se kontroluje spolu se stdout a stderr.
9Webhook
Volání, které cizí služba pošle vaší aplikaci při události. Může se doručit opakovaně, proto se testuje duplicitní doručení.
10Worker / job
Proces na pozadí zpracovávající úlohy. Zkouší se jeho obnovení po částečném selhání.
11Duplicitní doručení
Situace, kdy tutéž zprávu dostanete víckrát. Zpracování má být idempotentní, jinak vzniknou dvojí efekty.
12Deadline guard
Spustitelná pojistka, která odmítne pozdní sondy a zastaví vlastní popředí na limitu, místo aby spoléhala na odhad času.
13Coverage gap
Viditelně pojmenovaná mezera: kontrola, která se nestihla, byla odepřena nebo nemá potřebné závislosti.
14Smoke pass
Krátký rychlý průchod nejdůležitějších věcí. V /review a /ship běží automaticky, ale není vyčerpávající QA.
15Nativní regresní test
Test v testovacím nástroji, který projekt už používá, ne v nově instalovaném frameworku.
16Blokátor
Důvod, proč testování nejde provést (chybí nástroj nebo fixture). Zpráva ho pojmenuje, místo aby předstírala úspěch.
GBrain s gstackem: rychlá prohlídka
Čtyři způsoby nastavení „mozku“ pro agenta, synchronizace kódu, trust politika per repozitář a synchronizace paměti gstacku s ochranou před úniky secrets.
Popis
Co příklad ukazuje
GBrain je paměť a sémantické vyhledávání, které agent používá místo hrubého grep. Tato stránka je zkrácená verze USING_GBRAIN_WITH_GSTACK.md a provede vás čtyřmi věcmi: nastavení, udržování aktuálního indexu, politika důvěry per repozitář a synchronizace paměti gstacku.
1) Nastavení — čtyři cesty (/setup-gbrain)
| Cesta | Kdy se hodí |
|---|---|
| Supabase, existující URL | váš cloudový agent už mozek vytvořil; vložíte Session Pooler URL a tento notebook používá stejná data |
| Supabase, auto-provision | vložíte Personal Access Token; skill vytvoří projekt, počká na zdraví, získá pooler URL a předá ji do gbrain init (~90 s) |
| PGLite lokálně | žádné účty ani síť, ~30 s; izolovaný mozek jen na tomto Macu; později /setup-gbrain --switch |
| Vzdálený gbrain MCP | mozek běží na jiném stroji (Tailscale, ngrok, LAN); vložíte MCP URL a bearer token; volitelně s lokálním PGLite pro symbolové vyhledávání kódu |
Po init skill nabídne registraci gbrain jako MCP serveru pro Claude Code (claude mcp add gbrain -- gbrain serve), takže gbrain search, gbrain put apod. jsou plnohodnotné typované nástroje, ne volání shellu.
2) Udržování aktuálního mozku (/sync-gbrain)
Z libovolného repozitáře znovu zaindexuje kód. Výchozí je inkrementální režim, --full je plný reindex, --dry-run je náhled. Skill zaregistruje aktuální adresář jako federovaný zdroj (gbrain sources add), spustí gbrain sync --strategy code a zapíše do CLAUDE.md projektu blok ## GBrain Search Guidance, aby agent preferoval gbrain search/code-def/code-refs před Grepem. Blok se automaticky odstraní, pokud selže kontrola schopností — žádné zastaralé pokyny na nenainstalované nástroje.
3) Politika důvěry per vzdálený repozitář
read-write— agent hledá i zapisuje nové stránky zpětread-only— hledá, ale nikdy nezapisuje (ideální pro konzultanta s více klienty: nezanese práci klienta A do mozku při práci v repozitáři klienta B)deny— žádná interakce s gbrain
Skill se zeptá jednou na repozitář a rozhodnutí platí napříč worktrees i větvemi stejného remote.
4) Synchronizace paměti gstacku
Jiná funkce na stejné infrastruktuře soukromého repozitáře: gstack-artifacts-init volitelně posílá stav gstacku (learnings, CEO plány, design docs, retra, profil vývojáře) do soukromého git repozitáře, aby paměť sledovala vás mezi stroji. Při prvním použití je jednorázová otázka na soukromí (vše na allowlistu / jen artefakty / vypnuto) a obranná vrstva v podobě skeneru secrets, který zablokuje AWS klíče, tokeny, PEM bloky a JWT dřív, než opustí stroj.
Proč je to dobré a bezpečné
Mozek jde nastavit bez účtů (PGLite) nebo ve sdíleném cloudu; per-repo politika brání kontaminaci dat mezi klienty; skener secrets zachytí chybu dřív, než data odejdou; a samočisticí blok v CLAUDE.md zaručuje, že pokyny vždy odpovídají nainstalovaným nástrojům. V Conductoru, který odstraňuje ANTHROPIC_API_KEY a OPENAI_API_KEY, se použijí proměnné GSTACK_ANTHROPIC_API_KEY a GSTACK_OPENAI_API_KEY, které gstack za běhu povýší na kanonické názvy.
Zdrojový kód 1
docs/gbrain-quick-tour.md34 řádků
# GBrain with gstack: the quick tourThe short version of [USING_GBRAIN_WITH_GSTACK.md](../USING_GBRAIN_WITH_GSTACK.md), which has every scenario, flag, helper bin and troubleshooting step. This page is what the README used to say.```bash/setup-gbrain```Four paths, pick one:- **Supabase, existing URL** — your cloud agent already provisioned a brain; paste the Session Pooler URL, now this laptop uses the same data.- **Supabase, auto-provision** — paste a Supabase Personal Access Token; the skill creates a new project, polls to healthy, fetches the pooler URL, hands it to `gbrain init`. ~90 seconds end-to-end.- **PGLite local** — zero accounts, zero network, ~30 seconds. Isolated brain on this Mac only. Great for try-first; migrate to Supabase later with `/setup-gbrain --switch`.- **Remote gbrain MCP** — your brain runs on another machine (Tailscale, ngrok, internal LAN) or a teammate's server; paste an MCP URL and bearer token. Optionally pair with a local PGLite for symbol-aware code search in split-engine mode. Best for cross-machine memory without standing up a local DB.After init, the skill offers to register gbrain as an MCP server for Claude Code (`claude mcp add gbrain -- gbrain serve`) so `gbrain search`, `gbrain put`, etc. show up as first-class typed tools — not bash shell-outs.**Keeping the brain current.** Run `/sync-gbrain` from any repo to re-index its code into gbrain (incremental by default, `--full` for a full reindex, `--dry-run` to preview). The skill registers the cwd as a federated source via `gbrain sources add`, runs `gbrain sync --strategy code`, and writes a `## GBrain Search Guidance` block to your project's CLAUDE.md so the agent prefers `gbrain search`/`code-def`/`code-refs` over Grep. The block is removed automatically if the capability check fails — no stale guidance pointing at tools that aren't installed.**Per-remote trust policy.** Each repo on your machine gets one of three tiers:- `read-write` — agent can search the brain AND write new pages back from this repo- `read-only` — agent can search but never writes (best for multi-client consultants: search the shared brain, don't contaminate it with Client A's work while in Client B's repo)- `deny` — no gbrain interaction at allThe skill asks once per repo. The decision is sticky across worktrees and branches of the same remote.**GStack memory sync (different feature, same private-repo infra).** Optionally pushes your gstack state (learnings, CEO plans, design docs, retros, developer profile) to a private git repo so your memory follows you across machines, with a one-time privacy prompt (everything allowlisted / artifacts only / off) and a defense-in-depth secret scanner that blocks AWS keys, tokens, PEM blocks, and JWTs before they leave your machine.```bashgstack-artifacts-init```**Running gstack in Conductor?** Conductor explicitly strips `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` from every workspace's process env, so paid evals and gbrain embeddings won't work out of the box. Set `GSTACK_ANTHROPIC_API_KEY` and `GSTACK_OPENAI_API_KEY` in Conductor's workspace env config instead — gstack's TS entry points promote them to canonical names at runtime. Full details and the contributor checklist for adding the import to new entry points: [Conductor + GSTACK_* env vars](../USING_GBRAIN_WITH_GSTACK.md#conductor--gstack_-env-vars).
Kvíz 14
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Podle čeho si vyberete jednu ze čtyř cest /setup-gbrain?
Podle toho, kde má mozek být. Existující Supabase URL, pokud ho už vytvořil váš cloudový agent. Auto-provision, pokud chcete nový cloudový mozek (stačí PAT, ~90 s). PGLite, pokud chcete vyzkoušet bez účtů a sítě (~30 s, jen tento Mac). Vzdálený MCP, pokud mozek běží na jiném stroji nebo u kolegy. Lokální PGLite lze později přesunout přes /setup-gbrain --switch.
2Proč je PGLite dobrý pro první zkoušku?
Nepotřebuje žádný účet ani síť a nastaví se za ~30 sekund. Mozek je izolovaný jen na tomto Macu, takže nic neovlivní ostatní. Pokud se osvědčí, dá se později migrovat na Supabase.
3Co přesně dělá auto-provision přes Supabase?
Po vložení Personal Access Tokenu skill vytvoří nový projekt, čeká, až bude zdravý, stáhne pooler URL a předá ji gbrain init. Celé to trvá zhruba 90 sekund. Token vkládáte vy; nic se nevytváří bez vašeho tokenu.
4Proč registrovat gbrain jako MCP server?
Příkazem claude mcp add gbrain -- gbrain serve se gbrain search, gbrain put a další objeví jako typované nástroje první třídy, ne jako shellová volání. Agent je spolehlivěji vybírá, dostává strukturované výsledky a nemusí skládat příkazy do bash.
5Jaký je rozdíl mezi inkrementální synchronizací, --full a --dry-run?
Výchozí inkrementální reindexuje jen změny. --full přeindexuje všechno (po větších změnách nebo při podezření na nesoulad). --dry-run ukáže, co by se stalo, a nic nezapíše.
6Co zapíše /sync-gbrain do CLAUDE.md a proč?
Blok ## GBrain Search Guidance, který agentovi říká, že má preferovat gbrain search, code-def a code-refs před Grepem u sémantických otázek. Díky tomu se po synchronizaci chová agent správně bez ruční konfigurace.
7Proč se blok Search Guidance po neúspěšné kontrole schopností sám odstraní?
Aby v CLAUDE.md nezůstaly zastaralé pokyny ukazující na nástroje, které nejsou nainstalované. Agent by se jinak snažil volat neexistující příkazy. Blok existuje jen tehdy, když ho nástroje opravdu podporují.
8Co znamenají tři trust tiery read-write, read-only a deny?
read-write: agent hledá i zapisuje nové stránky. read-only: hledá, ale nikdy nezapisuje. deny: žádná interakce s gbrain. Skill se zeptá jednou na repozitář a volba platí napříč worktrees a větvemi téhož remote.
9Proč je read-only ideální pro konzultanta s více klienty?
Konzultant může prohledávat sdílený mozek, ale nezanese do něj práci klienta A, když pracuje v repozitáři klienta B. Zápis by smísil důvěrná data klientů; read-only tomu předchází.
10Proč se rozhodnutí o důvěře ukládá per remote, ne per adresář?
Jeden repozitář může mít více worktrees a větví. Politika vázaná na remote platí pro všechny stejně, takže stejný repozitář nikdy nezíská jinou úroveň přístupu jen proto, že jste ho otevřeli jinde.
11Co je „GStack memory sync“ a čím se liší od gbrain?
Je to jiná funkce na stejné infrastruktuře soukromého repozitáře: posílá do soukromého git repozitáře stav gstacku (learnings, CEO plány, design docs, retra, profil vývojáře), aby paměť sledovala vás mezi stroji. Gbrain je naopak vyhledávatelný index kódu a stránek.
12Jak se chrání soukromí při synchronizaci paměti?
Dvěma vrstvami: jednorázová otázka při prvním použití (vše na allowlistu / jen artefakty / vypnuto) a skener secrets (defense-in-depth), který zablokuje AWS klíče, tokeny, PEM bloky a JWT dřív, než opustí stroj.
13Proč Conductor vyžaduje proměnné GSTACK_ANTHROPIC_API_KEY a GSTACK_OPENAI_API_KEY?
Conductor z procesového prostředí každého workspace záměrně odstraňuje ANTHROPIC_API_KEY a OPENAI_API_KEY, takže placené evaly a embeddings gbrain by bez nich nefungovaly. Vstupní body gstacku proto za běhu povýší GSTACK_* varianty na kanonické názvy.
14Kdy se hodí vzdálený gbrain MCP se split-engine režimem?
Když mozek běží jinde (Tailscale, ngrok, LAN, server kolegy) a vy chcete paměť sdílenou mezi stroji bez lokální databáze, ale zároveň symbolové vyhledávání kódu. Spárujete ho s lokálním PGLite: sdílený mozek pro paměť, lokální pro kód.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1GBrain
Paměť a sémantické vyhledávání pro agenta. Z kódu a stránek umí odpovídat na „kde se řeší X“ lépe než Grep.
2`/setup-gbrain`
Skill pro první nastavení gbrain; nabídne čtyři cesty (Supabase existující, auto-provision, PGLite, vzdálený MCP).
3`/sync-gbrain`
Skill pro opětovnou indexaci kódu repozitáře do gbrain a zápis bloku Search Guidance do CLAUDE.md.
4Supabase
Hostovaný Postgres. V příkladu slouží jako cloudové úložiště mozku buď přes existující URL, nebo přes auto-provision.
5Session Pooler URL
Připojovací URL poolu spojení Supabase, kterou gbrain init používá.
6Personal Access Token (PAT)
Token účtu, kterým skill vytvoří nový projekt Supabase při auto-provisionu.
7PGLite
Lokální vestavěný Postgres bez účtů a sítě. Mozek je pak izolovaný jen na tomto Macu.
8MCP server
Rozhraní, přes které agent volá nástroje jako typované funkce. gbrain serve zpřístupní search, put a další.
9Federovaný zdroj
Repozitář zaregistrovaný příkazem gbrain sources add, aby jeho kód byl prohledávatelný mozkem.
10`gbrain sync --strategy code`
Příkaz, který indexuje kód zdroje. Používá ho /sync-gbrain.
11`## GBrain Search Guidance`
Blok v CLAUDE.md s pokynem preferovat gbrain před Grepem. Odstraní se, pokud kontrola schopností selže.
12Trust politika (tier)
Úroveň důvěry per vzdálený repozitář: read-write, read-only nebo deny. Platí napříč worktrees a větvemi.
13Worktree
Další pracovní kopie téhož repozitáře. Trust politika se u ní dědí od remote.
14`gstack-artifacts-init`
Příkaz, který zapne synchronizaci paměti gstacku do soukromého git repozitáře.
15Skener secrets
Obranná kontrola, která před odesláním zablokuje AWS klíče, tokeny, PEM bloky a JWT.
16Conductor
Prostředí, které ze workspace odstraňuje API klíče. Proto se v něm používají proměnné GSTACK_ANTHROPIC_API_KEY a GSTACK_OPENAI_API_KEY.
Praktické používání AI: skills, modely, rozpočet a triky
Jak AI dovednosti používat užitečně a bezpečně: kdy se skill spouští sám, který model na co, jak ohraničit náklady, jak pustit běh bez dozoru a které návyky se osvědčily.
Popis
O čem je závěrečný díl
Předchozích osm příkladů ukázalo jednotlivé oblasti gstacku. Tento díl je shrnuje do praktických návyků: jak s AI dovednostmi (skills), modely a nástroji pracovat, aby výsledek byl užitečný, předvídatelný a bezpečný. Zdroje níže jsou dokumenty z docs/; kde jde o obecnou praxi, která v repozitáři zapsaná není, je to výslovně označeno.
Stav ověření: lokálně nainstalovaný Claude Code má verzi 2.1.312 a modely v
docs/model-policy.mdjsouclaude-fable-5-1(frontier) aclaude-opus-5-5(smart). Jména modelů, verze a ceny se mění rychle, proto je vždy ověřte v aktuální dokumentaci poskytovatele — offline výběr v gstacku sám upozorňuje, že neprokazuje dostupnost modelu na vašem účtu.
1) Skills jako role a kdy se spouštějí samy
Skill je slash příkaz (např. /review, /qa, /ship), který agentovi přidá postup konkrétní role. Klíč proactive říká, jak daleko smí gstack jít bez vašeho příkazu:
| Hodnota | Co se spouští samo |
|---|---|
core (výchozí) | jen /office-hours, /review, /qa, /ship |
all | jakýkoli skill, jehož účel odpovídá zadání |
off | nic; ani nabídky typu „spustit /X?“ |
Skill, který pojmenujete, se spustí vždy. Nastavení se mění přes gstack-config set proactive core|all|off a platí od dalšího spuštění skillu.
Praktický tip: pokud používáte víc balíčků skills najednou, zůstaňte u core, aby si dovednosti nekonkurovaly. Chcete-li úplnou kontrolu, použijte off a příkazy pište sami.
2) Správný model na správnou práci
Pravidlo z docs/model-policy.md: frontier model na zpochybnění plánu, smart model na implementaci. Jde o doporučení, ne o tvrzení, že jeden model vyhrává vždy; vaše volba má přednost a doporučení nikdy samo nepřepne běžící sezení ani nezmění nativní konfiguraci hostitele.
gstack-models list
gstack-models resolve --role plan-review --provider openai
gstack-config set plan_review_tier smart # levnější tier pro review
gstack-config set plan_review_tier host # použít nativní nastavení CLI
Poznámky: nastavení se projeví při další invokaci bez nového renderu skills; neplatný zápis se odmítne a ponechá předchozí hodnotu; vadné známé nastavení výběr zastaví, místo aby se tiše ignorovalo; vypršený deadline u Codex review znamená chybějící pokrytí, ne dokončené review.
3) Rozpočet: /ship --token-cap
/ship --token-cap 25M (nebo GSTACK_SHIP_TOKEN_CAP=25M) ohraničuje spotřebu jednoho běhu a těžké segmenty předává podřízeným s čerstvým kontextem. Je to admission cap, ne tvrdý strop: práce se přijme jen tehdy, když used + rezervace + neznámé poplatky + projekce + rezerva na závěr + režie zastavení <= cap. Přesně na hranici se práce přijme, o token víc ne. Protože host nelze zastavit uprostřed tahu, může běh skončit nad capem o chybu odhadu už přijaté práce. Bez nastaveného capu se spotřeba jen měří a vypisuje. Řádek BUDGET: ukazuje used, reserved, unknown, admission_cap, meter a verdikt continue|delegate|stop.
4) Běh bez dozoru
Rodičovský agent spustí skill s GSTACK_SESSION_KIND=unattended a čte artefakty, ne prózu. V tomto režimu nejsou žádné prompty (nevyřčený souhlas znamená off), nic se nepublikuje ani nesynchronizuje (vynuceno u zapisovačů, ne jen v pokynech) a otázky se rozhodují takto: s doporučenou volbou se vybere doporučená a zapíše do decisions.jsonl jako kind: "auto"; otázka bez doporučení, souhlas, destruktivní či nevratná volba a závěrečná brána se zapíšou jako kind: "approval", status: "pending" a běh na nich skončí. Skill nikdy sám neschválí a nepublikuje.
5) Neptat se na to, co lze změřit
Dokument proactive.md zavádí pravidlo: otázka, jejíž odpověď skill může pozorovat, nepatří uživateli. Je-li změna rychlejší, liší-li se dva rendery, přijme-li endpoint payload nebo selhává-li test, spustí se to a výsledek se oznámí. Platí pro pozorování lokální, jen pro čtení a zdarma; akce měnící stav, sahající do živého či cizího systému nebo stojící peníze zůstává na vašem schválení. Uživateli přijdou jen produktové a preferenční otázky — už se změřenými možnostmi.
6) Obecné návyky (mimo repozitář, ověřená praxe)
Toto v dokumentech gstacku není zapsáno jako pravidlo, ale osvědčilo se s Claude Code obecně:
- CLAUDE.md jako paměť projektu: příkazy pro build/test, konvence a zákazy; krátké a aktuální (zastaralé pokyny škodí víc než žádné).
- Dejte agentovi ověřitelný cíl: test, který má projít, nebo příkaz s očekávaným výstupem. „Hotovo“ pak není názor.
- Malé samostatné commity: každý spustitelný a vratný; snadno se prověřují i vracejí.
- Nejdřív plán, potom kód u netriviální změny; plán se dá nechat zpochybnit druhým modelem.
- Secrets nikdy do chatu ani do repozitáře.
- Čistý kontext: dlouhé heavy kroky patří podřízenému agentovi s čerstvým kontextem; nesmíchávejte nesouvisející úlohy v jednom sezení.
- Nedůvěřujte, ověřujte: výstup AI čtěte jako návrh; spusťte testy, projděte diff a nepřijímejte tvrzení „není to naše chyba“ bez důkazu.
Zdrojový kód 4
docs/proactive.md76 řádků
# Proactive skill suggestionsgstack notices what stage you are in (a new idea, a diff to review, "does thiswork?", time to land it) and can invoke the matching skill without you typingits slash command. The `proactive` config key says how far that goes.| Value | What auto-invokes | Who it is for ||-------|-------------------|---------------|| `core` (default) | `/office-hours`, `/review`, `/qa` and `/ship` only. Every other skill waits for you to type it, unless a skill you ran hands off to it (`/office-hours` offering the next review). | Most people, and anyone running gstack beside another skill pack: the four core skills are the ones users praise, and the others no longer compete with another pack's niche skills. || `all` | Any skill whose purpose matches your request. | You use gstack on its own and want the whole sprint suggested. || `off` | Nothing. gstack never suggests or auto-invokes a skill, not even by asking "want me to run /X?". | You type every command yourself. |`true` and `false` still work as the older spellings of `all` and `off`, so aconfig written before the `core` default keeps its behavior; `gstack-skill-start`reports them to the skill as `all` and `off`. A hand edit may be quoted, upper-caseor commented (`proactive: "OFF" # mine`), and the YAML yes/no family (`yes`, `on`,`1`; `no`, `none`, `0`, `disabled`, `never`) reads as `all` or `off`, in`gstack-config set` as well, so a typed opt-out never fails open.```bashgstack-config get proactive # core, all, off (or a legacy true/false)gstack-config set proactive all # suggest every matching skillgstack-config set proactive off # suggest nothinggstack-config set proactive core # back to the default```A skill you name is always invoked, whatever the setting, and so is a skill thata running skill invokes itself (`/ship` dispatching `/document-release`). Thesetting governs unasked suggestions, and an in-skill *offer* to run another skillis one: under `off`, `/office-hours` recommends the next review in one lineinstead of offering to launch it, and the one-time first-runtips stay quiet. The change takes effect on the next skill run; no `./setup` isneeded, because every skill reads `PROACTIVE` from `gstack-skill-start` at thestart of each run and the router (`/gstack`) applies it to its routing rules. Avalue gstack does not know (a hand-edited `proactive: maybe`) reads as `core`.Two surfaces follow the setting only in part. The first is the `## Skill routing`section gstack offers to append to your project's CLAUDE.md. Under `off` the offer isnot made, because those rules are the auto-invocation you turned off (a sectionalready in CLAUDE.md stays; delete it yourself). Under `core` the offeredsection still lists every routing rule and tells the host to invoke anymatching skill. If you accepted it before the `core` default, trim that sectionto the four core rules (or delete it and let gstack offer it again); making theoffered section follow `core` is tracked in #3446.The second is the full skill descriptions, which a `--catalog-mode=full` buildand the non-Claude hosts keep. Non-core skills still say "Proactively suggestwhen ..." there, and that text does not change with the setting, so a hostthat picks skills from those descriptions can still reach them under `core`.The default Claude build uses one-line descriptions without that sentence.#3446 tracks that too.gstack asks once, after the telemetry question, which of the three you want;if you stored `off` before that, it takes the answer as given and does not ask."Say stop suggesting" in a session runs `gstack-config set proactive off` for you.If collisions with other skill packs keep coming up under `core`, the fallbackGarry approved on 2026-10-25 is `off` by default.## Questions a skill asks on its ownThe setting above governs which skills gstack offers unasked. A second rulegoverns what a running skill may ask you unasked: a question whose answer theskill could observe is not yours to answer. Whether a change is faster, whethertwo renders differ, whether an endpoint accepts a payload, whether a test stillfails: each of those is settled by running the thing (time it, render both,call it, run the test) and reporting the result, not by a prompt. That holdsfor observations that are local, read-only and free; a call that changes state,reaches a live or third-party system or spends money is still yours to approve.That extends the one-way-door rule in `/plan-tune`, which covers destructive,architectural and security questions, to spend and third-party reach. The onlyquestions that come to you are product and preference calls (what the productshould do, what you want, what you are willing to spend or risk), and theyarrive with the observation already in hand so the choice is between measuredoptions. `/plan-tune` applies the same rule when it audits the question log: anobservable question is a defect in the asking skill, not a preference to tune.
docs/model-policy.md291 řádků
# Model policyUse a frontier model to challenge a plan, then a smart model to build it.These are curated recommendations, not a claim that one model wins every task.User choices take precedence, and a recommendation never switches the runningsession or edits the host's native configuration.| Tier | Default job | Anthropic | OpenAI || --- | --- | --- | --- || `frontier` | Independent plan review | `claude-fable-5-1` | `gpt-6-astra` || `smart` | Implementation recommendation | `claude-opus-5-5` | `gpt-6.1-sol` |## Inspect and change your policyThis quickstart assumes gstack is installed. It uses no network, credentials orpaid model calls. Run it from the project's repository root in Bash, Git Bash or MSYS:automated outside reviews use that directory. Inspection from a subdirectoryreflects that subdirectory's native settings and may differ. If your install is vendoredor elsewhere, set `GSTACK_ROOT` to that installed gstack runtime instead.```bashif [ -x "$HOME/.claude/skills/gstack/bin/gstack-models" ]; then GSTACK_ROOT="$HOME/.claude/skills/gstack"elif [ -x "${CODEX_HOME:-$HOME/.codex}/skills/gstack/bin/gstack-models" ]; then GSTACK_ROOT="${CODEX_HOME:-$HOME/.codex}/skills/gstack"else printf '%s\n' 'Upgrade the gstack install for your host, then rerun this quickstart.' >&2 exit 1fi"$GSTACK_ROOT/bin/gstack-models" list"$GSTACK_ROOT/bin/gstack-models" resolve --role plan-review --provider openai```The output explains the selected model and which setting won. It also showscatalog verification metadata. Offline selection does **not** prove that a CLIis installed, that your account can use the model, or that a vendor's currentcatalog has been checked.Choose the less expensive review tier, then inspect the effective result:```bash"$GSTACK_ROOT/bin/gstack-config" set plan_review_tier smart"$GSTACK_ROOT/bin/gstack-models" resolve --role plan-review --provider openai```Pin a provider's model within a tier, or reset a pin to the shipped default:```bash"$GSTACK_ROOT/bin/gstack-config" set model_frontier_openai gpt-6-astra"$GSTACK_ROOT/bin/gstack-config" set model_frontier_claude claude-fable-5-1"$GSTACK_ROOT/bin/gstack-config" unset model_frontier_openai"$GSTACK_ROOT/bin/gstack-config" unset plan_review_tier```To keep using native CLI model settings for plan reviews:```bash"$GSTACK_ROOT/bin/gstack-config" set plan_review_tier host```Settings apply to the next invocation without rerendering skills. An invocationalready being checked keeps its selected model through execution. Configurationuses the existing [gstack state root](state-root.md), not a new per-repositorysettings file. Invalid writes are rejected and leave the previous value intact;use `unset`, not an empty value, to restore a default.A malformed known setting (for example `plan_review_tier = smart`) stopsselection rather than acting as an absent key. Correct or remove the named linein the reported config file; `unset` only removes correctly spelled `key:` records.Codex plan-review readiness and dispatch share one deadline. Readiness isbudgeted half the remaining time, with the existing termination grace. A slowpreflight leaves less time for the review instead of extending the caller'slimit. An expired deadline starts no new command and means missing reviewcoverage, not a completed review.## Settings and precedence| Key | Default | Accepted value || --- | --- | --- || `plan_review_tier` | `frontier` | `frontier`, `smart`, `host` || `implementation_tier` | `smart` | `frontier`, `smart` || `model_frontier_claude` | Catalog's Anthropic frontier model | Explicit Anthropic model identifier || `model_frontier_openai` | Catalog's OpenAI frontier model | Explicit OpenAI model identifier || `model_smart_claude` | Catalog's Anthropic smart model | Explicit Anthropic model identifier || `model_smart_openai` | Catalog's OpenAI smart model | Explicit OpenAI model identifier |For plan reviews, a model named for that invocation wins over`GSTACK_CLAUDE_MODEL` or `GSTACK_CODEX_MODEL`. That environment override wins overthe selected tier's configured model, which wins over the shipped catalog.Generic coding-model settings do not silently select a cheaper plan reviewer;choose `host` mode when that is the behavior you want.In `host` mode, Codex keeps its existing native-config resolution, including`CODEX_HOME`, active profiles and the `exec` versus native `review` distinction.Claude can delegate model selection to its CLI without forcing `--model`; theinspector reports that delegation rather than inventing an exact model ID.Actual returned model usage remains separate from the requested model.Implementation recommendations use a model explicitly requested for that job,then the configured implementation tier and its provider override, then thecatalog. Outside-review environment overrides do not change implementationrecommendations. Known Claude Code and Codex hosts recommend their own provider;an unknown or multi-provider host can show both choices.Custom endpoints and partner platforms need an explicitly compatible model or`host` mode. Gstack does not guess that public API IDs work with Bedrock, Vertex,Foundry or a custom Codex provider. A model identifier passing syntax validationis not proof of account availability. See [provider recovery](troubleshooting.md#model-policy-provider).Detection is conservative, not a replacement for the CLI's settings engine.Claude checks environment, user settings, project/shared/local settings, localsettings at the repository and worktree's main checkout, and local managed files.Codex checks environment, user/active-profile settings and system configuration;project-local Codex config is not inspected.Any detected local custom-route signal requires an explicit model, even ifnative trust or precedence rules might suppress it. Server-managed or MDMpolicy and extra native CLI flags are not visible to this check; `--help` andJSON output list these limits. Use an explicit compatible model for those cases,or `host` mode for plan reviews. Implementation recommendations require anexplicit implementation model rather than delegating to a hidden native choice.## Reasoning effortCodex calls carry a `model_reasoning_effort`. It follows the same shape as themodel: a per-request flag on `/codex`, a per-run environment override, then astored setting, then the default each gate ships with.| Order | Source | Set it with || --- | --- | --- || 0 | `/codex ... --effort <level>` (this request only; `/codex` alone) | `/codex review --effort medium` || 1 | `GSTACK_CODEX_EFFORT` (this shell, this run) | `export GSTACK_CODEX_EFFORT=max` || 2 | `codex_effort` in config.yaml | `gstack-config set codex_effort low` (`unset` restores the defaults) || 3 | the gate's default | nothing: `high` for reviews, plan reviews and `/codex` review and challenge; `medium` for `/codex` consult and design direction |Levels: `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `ultra`. Support ismodel-dependent, so an unsupported level for your model fails at request timethrough the usual model error. An invalid value never reaches Codex:`gstack-config set` rejects it, and `gstack-codex-probe run-with-timeout --effort<default>` (which resolves the order above and appends the flag) stops the callbefore anything is sent, naming the source to fix. `gstack-codex-probecheck-effort <default>` prints the same resolution without a call.For one request, `/codex review --effort medium` (or `--effort=<level>`; `--xhigh` isshorthand for `--effort xhigh`) outranks the other three, including an exported`GSTACK_CODEX_EFFORT`, and changes nothing that persists. The flag counts onlydirectly after `/codex` or its mode word, among the leading flags (`-m`/`--model`,`--role`, in any order) and before the prompt text; a later `--effort` is part of theprompt, and `/codex` says so. A Consult follow-up resolves its effort afresh. `/codex` passes the level to the probe as `--request-effort`,so an unknown level stops before any Codex call, naming the flag.`/spec`'s quality gate keeps `medium` inside its 120-second budget whatever youset, because a higher effort would spend the time the gate is sized for.`gstack-models list` prints the effective effort and where it came from(`--json`: `codexEffort`). The Claude Code runner takes no effort setting.### Review effort tiersEvery reviewer that can block a ship runs at `full` effort on the lane'smodel: the core checklist, each specialist, the Red Team, the nativeadversarial pass and the fix-check. `gstack-review-plan` names eachdispatch's effort, and `host` for the outside voice (its provider and`codex_effort` above). Only work that cannot block runs `light`, the samemodel at a medium or low setting and never a cheaper model family: the coverage,plan-completion and docs audits, decision-trail reviewers and watchers(`AUDIT_EFFORT:` in the plan's output). A paid replay showed why reviewers stayat full: a medium-effort fix-check missed a fail-open in gate code that the samecheck at full effort caught. A host that cannot set a subagent's effort runs itat its default. `gstack-config set review_effort_tiers off` (default `on`)runs the audits and watchers at the host default too([review-policy.md](review-policy.md#review-depth)).## Which workflows use the tiers?The plan-review role applies to autoplan's CEO, design, DX and engineeringoutside voices; standalone CEO, engineering, developer-experience and designplan reviews; and the spec quality gate. Existing reasoning effort, accessrestrictions, timeouts, review gates and `codex_reviews` consent remain in force.The host selects the opposing provider independently from the tier. Claude Codeuses the Codex wrapper; Codex uses the Claude Code wrapper. A model's name doesnot establish which harness is running.Manual opposing-model wrappers can opt into `--role plan-review`. Ordinarycode reviews, live design reviews, design consultation, office-hours secondopinions and documentation reviews retain their existing model-selectionbehavior. Historical no-role defaults, eval actors/judges, cheap helper modelsand setup-time behavioral overlays do not follow this catalog.Before the first affected paid plan review after upgrade, gstack explains theindependent frontier default and the winning source, with `smart` and `host`alternatives. Inspection does not mark that notice as seen. Disabled outsidereviews stay disabled; an unavailable model is reported, never silently replaced.## First completed outside reviewPolicy setup and a completed review are different milestones. Install andauthenticate the opposing CLI using the [host setup instructions](../README.md#install--about-30-seconds)before invoking a paid review. From Claude Code, use `/codex consult --roleplan-review`. From Codex, use `/claude-code consult --role plan-review` (or itsinstalled namespaced name). Ask it to challenge the plan and supply the full plantext. Consult is prompt-driven and works before there is a repository diff;Challenge mode is for reviewing code changes.Confirm the announced selection, the provider's actual result and the coveragestatus. A resolved model, a successful availability probe or a native fallbackis not a completed outside review. An unusable explicit choice needs a repairat the source named in the error; changing a lower-priority tier cannot overridean environment pin. See [selection recovery](troubleshooting.md#model-policy-selection).## Machine-readable inspection`gstack-models` with no arguments is `list`. Both `list` and `resolve` accept`--json`. Plan-review resolution requires `--provider anthropic|openai`;implementation resolution can omit the provider to return both recommendations.```bash"$GSTACK_ROOT/bin/gstack-models" resolve --role plan-review --provider anthropic --json"$GSTACK_ROOT/bin/gstack-models" resolve --role implementation --json```JSON output is one document with `schemaVersion: 1`, a `selections` array andstructured errors on failure. Human diagnostics go to stderr. Exit `0` meansvalid resolution, including host delegation; `1` means configuration orselection failure; `2` means invalid usage. Neither inspection nor resolutionwrites notice markers, probes a model or fetches vendor sources.## Keeping shipped recommendations currentThe model-policy freshness workflow runs weekly and supports manual dispatch.It checks official Anthropic and OpenAI recommendation and deprecation sources,without provider credentials or paid model calls. Normal PR checks use offlinefixtures; a vendor outage does not make unrelated PRs fail.In GitHub Actions, select **Model-policy freshness** to run it manually. From agstack checkout, `bun scripts/model-policy-freshness.ts` performs the same publicsource check without changing an issue; unlike `gstack-models`, it uses thenetwork. The workflow's guarded `--publish` path owns issue updates. Its JSONreport and job summary retain the source evidence.The report's primary status distinguishes `current`, `update-candidate` and`unknown/source-unavailable`. Its separate `evidenceStatus` marks retainedsuccessful evidence `stale` after thirty days; a failed fetch remains unknownin the headline even when that retained evidence is stale.Newer or newly recommended models are candidates,not automatic replacements. A support promise such as “not sooner than” is nota scheduled retirement, and an incidental model mention is not a new default.This evidence covers public API recommendations, not partner-platform entitlement.One Actions-bot-owned tracking issue preserves the successful check's catalog/source/parser identity and any unresolved lifecycle findings. Healthy state remainsreadable when the issue is closed. A failed or partial check cannot erase a knownretirement, borrow a success from an older catalog, or pretend its evidence isfresh. A catalog rollback reopens historical findings for a model put back inuse. Only current default-branch runs may update that issue; copied markers inuser-owned issues are not trusted state.A documented retain decision preserves the current default, but does not make avendor mismatch `current`: the advisory issue stays open, or reopens, while thatcandidate remains. Record retain rationales in issue comments, which the workflownever edits, rather than racing a scheduled update to the issue body.Thirty-day staleness means an absence of trustworthy freshness evidence, notthat a model was released thirty days ago. An unchanged recommendation does notrequire a date-only catalog commit or a monthly paid benchmark. The recordednext-check due date helps maintenance, but a workflow that never runs cannotalert on its own absence.### Maintainer update checklist1. Check the latest freshness run and its due date. Resolve missing, corrupt or source-unavailable evidence before declaring the catalog current.2. Verify the official recommendation and lifecycle evidence. Triage announced retirement/removal within one working day, stale/unavailable evidence within seven days and discretionary update candidates within thirty days.3. Open a catalog change with the source URLs, exact model IDs and qualification evidence, or record why the current default should remain. Never edit users' personal pins or silently substitute another provider.4. Confirm CLI model/profile support and tool/reasoning compatibility. Keep the pinned test runtimes and benchmark rulers stable. A required CLI upgrade is a separate reviewed change, not an automatic side effect of discovery.5. Predeclare any budgeted baseline/candidate comparison using existing eval machinery, fixed prompts/panels and unchanged thresholds. Keep every attempt, measure useful and unsupported findings, latency and available usage, and do not treat vendor marketing or a creation timestamp as quality evidence.6. Pass the affected free checks and selected workflow evaluations, review the change, and ship it through the normal release process. Only unpinned role-bearing defaults follow the new shipped catalog.The workflow does not open an automatic model-upgrade PR, merge changes, switchactive sessions, alter benchmark models or schedule paid evaluations.
docs/ship-budget.md159 řádků
# /ship token budget and fresh-context handoffs`/ship --token-cap 25M` (or `GSTACK_SHIP_TOKEN_CAP=25M`) bounds what one /ship run spends, andlong runs hand their heavy segments to fresh-context children. The helper is`bin/gstack-ship-budget`; the skill's procedure is `ship/sections/budget-handoff.md`.There is no default cap: without one, /ship meters usage when it can and prints it, andnothing else changes.## What the cap guaranteesIt is an **admission cap**, not a hard ceiling. Before every step and every dispatch batch,`check` admits the work only when used + open reservations + unknown charges + projection + tail reserve + stop overhead <= capExactly at the cap is admitted; one token over is not. A parallel review batch is reserved asone sum before any of it starts. Admitted work can still cost more than its projection, andgstack cannot stop a host mid-turn from bash, so a run can finish above the cap by themisprojection of work already admitted. The tail reserve (default 2M, `--reserve <n>`) keepsroom for the receipt steps, and the stop overhead (calibrated) keeps room to stop cleanly.## Quickstart**Capy.** Read the root counter in one execute program that returns only that number:```jsreturn (await tools.thread.get({ thread_id: "this" })).cost.tokens;```then```bashgstack-ship-budget start --record <record> --token-cap 25M --reading <n>gstack-ship-budget check --run <id> --step 6 --next 7 --reading <n> [--prior-reading <n from your previous call>]```The counter rolls up every subagent of the thread, outside voices included; Capy exposes noper-subagent counter, so other work in the same thread counts too (it only stops earlier).**Claude Code.** `gstack-ship-budget start --record <record> --token-cap 25M --session <id>`. Without thesession id, `start --meter claude` prints a nonce: echo it once, then rerun with `--nonce <value>`.The helper reads the session journal, its subagent journals and the journals of headlesschildren it launched; you never pass `--reading`.**Anywhere else.** `--meter estimate` projects with the calibration and prints `meter=estimate`.With a cap set and no readable meter, start refuses([BUDGET_METER_UNAVAILABLE](troubleshooting.md#budget-meter-unavailable)).## The BUDGET line BUDGET: used=<n> reserved=<n> unknown=<n> admission_cap=<n|none> tail=<n> unit=<u> meter=<m> epoch=<n> call=<n|unknown> next=<id> projected=<n> verdict=continue|delegate|stop| Field | Meaning ||---|---|| `used` | Metered usage since start (all epochs), or settled estimates under `meter=estimate` || `reserved` | Open reservations: admitted steps, started dispatches, and each open child's sub-cap counted as max(sub_cap, child_used), never both || `unknown` | Charges the meter cannot see (an external-CLI outside voice on Claude Code), counted at their reservation || `admission_cap` | The cap, or `none` || `tail` | Tail reserve plus stop overhead, held back from every admission || `unit`, `meter`, `epoch` | The meter contract: `capy-tokens` (root counter), `claude-usage-tokens` (journal usage), `estimate-tokens`; a meter change opens a new epoch || `call` | The per-call charge: two Capy readings in consecutive calls, or the last Claude Code call's usage || `next`, `projected` | What the check was for and its calibrated projection || `verdict` | `continue` (exit 0, prints `RESERVATION:` under a cap), `delegate` (exit 0), `stop` (exit 3) |Any exit other than 0 means the next step does not start. Exit 2 is a usage or validationerror on stderr with the code, the value and the repair. GSTACK_RESULT appears only on a stop,an incomplete close and a child's return; /ship's real terminal line stays Step 22's.## DispatchesUnder a cap, `gstack-review-log --start` refuses a dispatch without an unspent, one-shotreservation ([BUDGET_CHECK_SKIPPED](troubleshooting.md#budget-check-skipped)):```bashgstack-ship-budget check --run <id> --step 9 --next dispatch:specialist,red-team --reading <n>gstack-review-log --start review --reservation <id>```Roles are review-depth's: `specialist`, `red-team`, `adversarial-native`, `outside-voice`,`fix-check`. `--finish <token>` settles the reservation at the dispatch's completion receipt.`close` audits after the fact: each review-log row of the run with no reservation gets oneBUDGET_CHECK_SKIPPED line and the run ends status=incomplete for the owner to accept(`close --approved-by <who> --words "<their words>"`); a reservation is never created after the fact.## DelegationAt start, a per-call charge of 100k or more delegates the whole /ship. Before Step 7 and beforeStep 12, 150k or more (or an unknown charge) delegates the next segment (7–11.5, 12–22):1. `gstack-ship-budget handoff --run <id> --from 12 --to 22 --base origin/<base> --reading <n>` writes a brief (mode 0600, under the run directory) with the pins (HEAD, merge base, working tree, reviewed tree), the record with its six headings and start tokens, the decisions in scope with the owner's words, the decision trail, the budget and the return contract. It reserves the child's sub-cap: min(cap − used − reserved − tail, the segment estimate), or `--sub-cap`.2. The child is a Capy subagent on the shared machine, or on Claude Code `gstack-ship-budget launch --in <brief>`: a background `claude -p` (resolved through lib/claude-bin.ts) with explicit permission flags and the return file named.3. The child runs `verify-handoff` first; a moved pin refuses ([HANDOFF_PIN_MOVED](troubleshooting.md#handoff-pin-moved)). It admits against its sub-cap with child_used = reading − reading at handoff, is the only writer of the record, and never delegates again: a delegate rule stops it. It ends with `return` (at most 40 lines).4. `gstack-ship-budget reconcile --run <id> --return <file> --reading <n>`; idempotent per handoff hash, so a duplicate return charges nothing twice. A refused, incomplete or interrupted child exits 3: regenerate the handoff or stop.`--delegate never` turns delegate into stop for hosts without children.## Stop and resumeA stop prints STOP: reason=budget_exhausted spent=<n> reserved=<n> unknown=<n> admission_cap=<n> next=<id> projected=<n> RECOVER: /ship --resume <record> --token-cap <used + reserved + unknown + projected tail> GSTACK_RESULT: skill=ship status=incomplete run=<dir>Raising the cap is the owner's call; the resume journals who raised it and their words:```bashgstack-ship-budget resume --record <record> --token-cap <n> --approved-by Garry --words "raise it to finish" --reading <n>```Every command takes `--run` or `--record`; runs are never found by branch or directory, and a/ship without `--resume` or `--continue` always starts a new run. The ledger and record aremirrored to a private Drive checkpoint (`GSTACK_SHIP_BUDGET_CHECKPOINT_DIR`, else theproject-user Drive folder on Capy) bound to the run id and their hashes, so after a machinechange `resume --run <id>` restores both. A corrupt ledger([BUDGET_LEDGER_INVALID](troubleshooting.md#budget-ledger-invalid)) is rebuilt from therecord's block with `--rebuild-from-record`; open reservations are then charged as unknown.## Calibration`lib/ship-budget-calibration.json` holds per-meter constants (per call, per dispatch, stopoverhead, calls and dispatches per step) fitted from metered runs: each constant is thelargest observation times 1.5, rounded up to 10,000 tokens. The leave-one-out test(test/ship-budget-calibration.test.ts) covers the per-call constant only, the one observedacross three runs; per-dispatch has two observations and stop overhead one. Only the Capymeter has observations; the Claude Code and estimate units are seeded from it until aClaude-metered /ship completes.## Token cap and USD spend capA lane's `--spend-cap` (USD) bounds paid gates and evals through lib/spend-ledger.ts; `--token-cap`bounds the /ship run's model tokens through its own ledger. They are independent: set bothwhen a lane runs paid gates inside /ship, and neither converts into the other.## Claiming savingsSavings count completed ships only. Preregister the comparison with `/eval-plan` (arms, bars,stop rules) before claiming a saving from the cap or from delegation.## Result codes[BUDGET_CAP_REACHED](troubleshooting.md#budget-cap-reached) ·[BUDGET_READING_MISSING](troubleshooting.md#budget-reading-missing) ·[BUDGET_READING_REJECTED](troubleshooting.md#budget-reading-rejected) ·[BUDGET_METER_UNAVAILABLE](troubleshooting.md#budget-meter-unavailable) ·[BUDGET_LEDGER_INVALID](troubleshooting.md#budget-ledger-invalid) ·[BUDGET_CHECK_SKIPPED](troubleshooting.md#budget-check-skipped) ·[HANDOFF_PIN_MOVED](troubleshooting.md#handoff-pin-moved)
docs/unattended.md700 řádků
# Unattended runs: the artifact contractA gstack skill runs *unattended* when a parent agent starts it with`GSTACK_SESSION_KIND=unattended` and reads its artifacts instead of its prose.This page is the contract between that parent and the run: what the sessionkind changes, which files a run writes, how the parent decides whether the runfinished, and how it reads the result without reading any markdown.The session kinds are: `interactive` (a human answers prompts), `headless`(`GSTACK_HEADLESS`, `CI`, the eval harness; a question BLOCKs), `spawned`(an orchestrator subagent; the recommended option is auto-chosen) and`unattended` (this page). `unattended` is honored only as the explicit`GSTACK_SESSION_KIND=unattended` override, which outranks `GSTACK_HEADLESS`so a parent can drive a run inside CI. Nothing in the test or eval harness setsit, so `headless` keeps its BLOCK semantics.## What the session kind changes`gstack-skill-start` prints `SESSION_KIND: unattended`,`UNATTENDED_SESSION: true` and the `unattended-session` instruction block(`GSTACK_INSTRUCTION_BEGIN: unattended-session <session-id>` through`GSTACK_INSTRUCTION_END`), then applies these rules for the whole skill:- **No prompts.** The update check, upgrade offer, telemetry and sync consent, onboarding tips and routing blocks are suppressed exactly as they are for `spawned`. An unanswered consent is `off`.- **No publishing or sync, enforced at the writers.** Usage analytics are not written (`TELEMETRY_WRITE: skipped (unattended session)`), the artifacts repo is neither pulled nor pushed (`ARTIFACTS_SYNC: skipped (unattended session; mode=<m> queue=<n> retained)`), the sync spool is not fed (`gstack-brain-enqueue` is a no-op, and `gstack-review-log` says `review-log: sync skipped (unattended session)` on stderr), and `gstack-skill-end` drains nothing. Inherited enabled settings and pending queue work are left for the next human session. The upgrade offer becomes one line at skill end, read from the local cache: `UPGRADE_AVAILABLE: <version>; run /gstack-upgrade` (`<version>+<n> (main at <sha>)` when main moved <n> commits past the checkout without a new version).- **Questions decide themselves, gates do not.** A question with a `(recommended)` option takes it and appends the choice to `decisions.jsonl` with `kind: "auto"`. A question with no recommendation, any consent, any destructive or irreversible option, and the final approval gate are appended with `kind: "approval"` and `status: "pending"`. The skill ends at its next gate with the pending list rendered; it never approves and never publishes.- **State root durability is reported.** `STATE_ROOT: <path> durable=yes|no` (`no` when the host sets `GSTACK_EPHEMERAL=1`). On an ephemeral root the run says `learnings: skipped (state root is ephemeral; set GSTACK_STATE_ROOT)` and `timing: analytics skipped (...)` instead of writing to a disk that vanishes. Point `GSTACK_STATE_ROOT` at a durable directory when you want cross-run history (see [state-root.md](state-root.md)).- **The autoplan publication guard is named, not faked.** On hosts that do not execute Claude Code hooks, and in every unattended session, `gstack-skill-start` prints `autoplan guard: not enforced by this host; publication order is unverified (GUARD_NOT_INSTALLED)` once. `gstack-artifact validate` requires that line in an unattended run's `review-record.md`. Claude Code's deny-on-absent behavior is unchanged.An unknown `GSTACK_SESSION_KIND` value coerces to `interactive` and says so:`SESSION_KIND: interactive (unknown kind '<x>')`.## The terminal lineA run that writes a record ends with one line the parent greps:```GSTACK_RESULT: skill=<name> status=<status> run=<dir>````status` is one of `complete`, `gate_pending`, `incomplete`, `interrupted` or`refused`; `run` is where the run's record is. `/autoplan`always ends `gate_pending` when it reaches the final gate, because the gate iswritten and never approved. Pure queries (`gstack-artifact schema`,`gstack-gate render`) print no result line.Not every workflow writes this line or a run directory today:- **`/autoplan`** writes the full run directory below through `gstack-autoplan`, and `gstack-artifact validate` checks it. It is the only skill with steps and helpers that write `run.json`, `decisions.jsonl` and `gate.json`.- **Workflow commands** `gstack-pregate`, `gstack-regen`, `gstack-restamp` and `gstack-ship-queue` print their own line, with `run=` naming their own record (the pregate receipt, the regen worktree, the restamp journal, the queue record), not a run directory.- **A refused launch.** Any skill whose install check refuses it at startup prints `GSTACK_RESULT: skill=<name> status=refused run=-` and stops.- **`/ship`** ends with `gstack-ship-receipt result --pr <n>` (or `--body .gstack/tmp/ship-receipt.md` after the handoff section), which binds the receipt to the branch head, writes the run record and prints `GSTACK_RESULT: skill=ship status=complete run=<dir>`. That line and that record are the machine-readable READY evidence; [What /ship leaves for a parent](#ship-evidence) below is the whole contract (the refused and incomplete lines, the one publication an unattended run may make, the `review_loop` counters, the outside voice on Capy and the `CARRY:` lines).- **Every other workflow skill** (`/review`, `/qa`, `/design-review`, `/spec`, `/land-and-deploy` and the rest) gets the session rules above (no prompts, approvals stay pending, nothing published), but has no step that writes a run directory or prints the line, so a parent should not wait for either. `/eval-plan` asks for a `gate_pending` line at its spend gate, but no helper writes its `gate.json` yet (`gstack-gate` renders and parses a gate list; it does not create one). `/cso` skips the shared startup, so these session rules do not reach it at all. Read each skill's own record instead: the review-log rows (`gstack-review-read`) for `/review` and the `qa-report-*.md` file for `/qa`. For a `/ship` run from before the result line, read the receipt instead: when the run did not push (an unattended run must not), read the receipt file in the child's checkout with `gstack-ship-receipt read --body .gstack/tmp/ship-receipt.md --json`; use `gstack-ship-receipt read --pr <n> --json` only once a PR exists. In both cases compare the receipt's `head` to the branch SHA (`git rev-parse HEAD` in the child's checkout): `read` does not check that the receipt is current, so an older PR's receipt reads as valid; `result` does.Every workflow command shares one exit table: `0` ok, `1` fail, `2` usage,`3` refused or needs a flag. Error lines end with a result code in parentheses,for example `findings.jsonl:12: ... (ARTIFACT_SCHEMA)`; each code has an anchorin [troubleshooting.md](troubleshooting.md#unattended-runs-and-artifacts) witha `fix:` clause. Grep the code, not the prose.<a id="ship-evidence"></a>## What /ship leaves for a parentOne section for everything a parent (a Captain, a crew thread, a merge queue)reads after an unattended `/ship`: the READY evidence, the review loop'scounters, the outside voice's record, and the carry across a base merge.### The READY evidence: `gstack-ship-receipt result``/ship` Step 22 runs `gstack-ship-receipt result --pr <n>` (or `--body.gstack/tmp/ship-receipt.md` after the handoff section). It binds the receiptin the PR body (or the handoff file) to HEAD, writes`<state root>/ship/runs/<utc>-<head12>/` and prints the terminal line:```GSTACK_RESULT: skill=ship status=complete run=<dir>```The run directory holds `ship-receipt.md` (the block, copied) and`ship-run.json` with `head`, `pr`, `base`, `version` (`"none"` for arepository with no version source, [ship-policy.md](ship-policy.md#ship-receipt)),`queue_mode`, `session_kind`, `receipt` (the copied block's path) and`receipt_source`. It is a /ship record, not the `run` v1 manifest below, soread it directly; `gstack-artifact validate` does not apply. A parent's mergecheck is then mechanical: take `run=` from the last result line, read`ship-run.json`, compare its `head` to the PR head, and quote the`SHIP_RECEIPT: pr=<n> head=<head12> …` line in the READY block.`gstack-ship-queue ready`, `train build` and `verify --train` make the samecomparison from the PR body ([ship-policy.md](ship-policy.md#ship-before-ready)).The other endings, each greppable: when gh cannot read the PR,`GSTACK_RESULT: skill=ship status=incomplete run=-` (exit 1); a receipt that ismissing or names another head, `GSTACK_RESULT: skill=ship status=refused run=-`with `QUEUE_RECEIPT_MISSING` or `QUEUE_RECEIPT_STALE` on stderr (exit 3), theline a run that stops before publication prints itself; and `result --pr <n>`refuses `QUEUE_RECEIPT_STALE` when HEAD is not the PR's pushed head.The one publication the unattended rules allow: when an open PR for the branchexists and HEAD is its pushed head, Step 18 takes the pr-body section'sexisting-PR path and posts the body (receipt first) and title through`gstack-post`. It never runs `pr-create`, never pushes a commit and never runs`gh pr ready`; a branch with no open PR, or whose PR head is not HEAD, takesthe handoff section. When the run committed anything (a CHANGELOG entry,generated tests), the parent pushes those commits itself, then reruns thereceipt write, the body post and `result` at the pushed head: a receipt for anunpushed head is `QUEUE_RECEIPT_STALE` to the queue.### The review loop's countersThe receipt's `review_loop` object, written from `gstack-review-scope summary--since <REVIEW_SINCE>`, is the loop's machine-readable outcome: `passes`(Step 9 full passes this ship ran, 1 or 2; up to 3 under `review_scope: all`),`blocking_found` (distinct blocking findings across them), `deferred`(blocking findings in unchanged code filed as issues, Step 11's late defersincluded), `noted`, `fixed` and `scope`. Thesummary line a parent reads prints it as `passes=<n> blocking_found=<k>deferred=<m>`; the PR body lists the deferred issues under `## Deferredfindings` and the below-floor items under `## Review notes`. A pass that findsnothing is `NO FINDINGS` from every reviewer and a pass with no edits, whichis the loop's exit, never a failed review ([review-policy.md](review-policy.md)).Three counters appear only when the run recorded them: `fix_checks` (fix-checkrows, never passes), `dispatches` (reviewer dispatches by role) and`est_input_tokens` (prompt plus diff bytes the dispatches read, / 4, a relativeestimate and never a bill).### Report lengthA parent reads many lanes, so length is a cost it pays per lane. A READY blockholds its required lines plus at most 150 words; a completion report holds atmost 300 words; a subagent brief names the files to read instead of pastingthem. Evidence goes in files the report points to. Waits go on operations,never on polling wakes.### Token caps and fresh-context handoffsA parent bounds a /ship run with `--token-cap <n>` (or `GSTACK_SHIP_TOKEN_CAP`).It is an admission cap: /ship meters usage, reserves every step and dispatchbatch before it starts, and stops `status=incomplete` with a `RECOVER:` lineinstead of starting work that would cross the cap. Long runs hand Steps 7–11.5and 12–22 to fresh-context children. The flow, the BUDGET line and the resultcodes are in [ship-budget.md](ship-budget.md).### The outside voice on CapyStep 11's outside adversarial review prefers the Codex CLI. On a Capy machinethe Codex CLI is normally absent (selecting a model in Capy installs andauthenticates no CLI), and the accepted outside voice is then a subagentrunning a different model family from the parent: a full outside voice, notdegraded coverage, as long as the model that reviewed is recorded. Itsreview-log row is the same row every Step 11 pass writes(`ship/sections/adversarial.md`): `skill: "adversarial-review"`,`phase: "adversarial"`, `source` naming the runner that actually reviewed(the outside provider that reviewed, with the model recorded, for thecross-family subagent; `codex` for completed Codex CLI output, as`ship/sections/adversarial.md` prescribes),`outside_provider` (the provider the host would have used, as the generatedprose names it), `outside_status` (`completed` for a finished outside pass;`unavailable` when neither the CLI nor a subagent completed, the cause on the`gstack-outside-voice run:` stderr line and in `<out>.meta.json` rather thanin the row; `disabled` under`codex_reviews: disabled`), `status`(`clean`, `issues_found` or `unavailable`), `completed`, `converged`, and thesubagent's model recorded with the pass (`gstack-outside-voice run --runnerhost-subagent --result <file> --model <id> --prompt <file> --out <file>` bindsit; the row's text names it where the host reports it). The native in-host adversarialsubagent writes its own row with `source: "in-host"`; native completion nevercredits outside coverage. A parent reads the rows with`gstack-review-read` and treats `outside_status: unavailable` as missingcoverage, not as a clean outside review.### The carry across a base merge or a test-only fixWhen the parent merges the base in or fixes a test after the receipt waswritten, it runs `gstack-ship-receipt carry --pr <n> --base <base> --dry-run`instead of another /ship; on `CARRY: would carry` it runs `gstack-pregate` at HEADand reruns carry with `--pregate .gstack/tmp/pregate.json`. `CARRY: carried from <old> to <new> (<reason>)` plus the`GSTACK_RESULT: skill=ship status=complete run=<dir>` line means the receiptnow names HEAD with a `carry` object holding the `git range-diff` evidence, and`ship-run.json` gains `carried_from` and `carry_reason`; the `review_loop`counters are kept, because the reviewed product diff is unchanged. `CARRY:current` means nothing moved. `CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)`,`(RECEIPT_CARRY_TREE_MISMATCH)` or `(RECEIPT_CARRY_REFUSED)` with the refusedresult line means the product diff changed, or history was rewritten onto atree no review saw, so /ship runs again;`(RECEIPT_GIT_TOO_OLD)` means the machine's git predates 2.39 and cannot run`patch-id --verbatim` ([ship-policy.md](ship-policy.md#receipt-carry)).## The run directory`/autoplan` writes these files; the next section shows how a parent reads them.| File | Schema | Contents ||------|--------|----------|| `run.json` | `run` v1 | The manifest: `run` id, `status`, `required_phases`, each phase's `native` and `outside` outcome (`status`, `model`, `provider`), input `snapshot` hashes, `counts`, every artifact's `path` (relative to the run directory) and `sha256`, `session_kind`, `gate_rev`, `deviations`, `consumed_by`. || `decisions.jsonl` | `decisions` v1 | One row per decision: `id` (`<run>-<label>` at gate revision 1, `<run>-r<rev>-<label>` after a reopen, since labels restart at each gate), `title`, `options`, `recommended`, `kind` (`auto`, `approval`, `user_challenge`), `status` (`pending`, `approved`, `overridden`, `rejected`), `gate_rev`, and once answered `chosen`, `answered_at`, `reply`. || `findings.jsonl` | `findings` v1 | One row per reviewer finding: `id`, `phase`, `voice` (`native`/`outside`), `model`, `severity`, `title`, `disposition`, `plan_items`, `native_counterpart` (string or null), `source`. Rows share the review-log row shape, so `gstack-review-log --findings` derives review status from this file. || `tasks.jsonl` | `tasks` v2 | Implementation tasks with `id`, `title`, `status`, `depends_on`, `findings` (ids in `findings.jsonl`), `blocked_by`, `acceptance`, optional `pr`/`item`/`tier`. || `timing.json` | `timing` v1 | Per-phase `started_at`, `ended_at`, `wall_s`, `outside_s`, `native_s`; `started_at` and `total_wall_s` for the run; the Phase 0 `estimate`. || `plan.md` | prose | The `## Implementation plan` section, with `## URGENT, outside this plan` written above it. || `review-record.md` | prose | The review record and decision audit trail; carries the `GUARD_NOT_INSTALLED` line in an unattended run. || `gate.json` | see `gstack-gate --help` | The final gate list `/autoplan` renders and parses. |Ids are run-bound: every row's `id` starts with `<run>-`, and `run.json` is theonly place the run id is declared. `gstack-artifact schema <name>` prints theJSON Schema for any of `findings`, `decisions`, `tasks`, `timing`, `run`,`pregate` and `ship-receipt`; `schema --list` prints the names.## How a parent consumes a run1. **Decide whether the run finished.** For an `/autoplan` run directory, `gstack-artifact validate <dir>/run.json` is the deterministic completion check (a `/ship` `run=` directory holds `ship-run.json`, read directly as described above). It exits `0` and prints `ARTIFACT_VALID: run=<id> status=<status>` only when the manifest parses and matches its schema, every required phase and each reviewer voice has a terminal outcome, every listed artifact exists inside the run directory with the recorded hash, every JSONL file parses row by row against its schema with run-bound unique ids, task dependencies and finding references resolve without cycles, `counts` agree with the files, and (unattended) the guard line is present. Otherwise it exits `1` with one error line per problem and `ARTIFACT_INVALID: <n> error(s)`; `--json` returns the same as `{ valid, run, status, run_dir, errors[] }`. A run that was interrupted shows up here as `ARTIFACT_RUN_INTERRUPTED`, never as a partial success.2. **Read the terminal line.** `grep '^GSTACK_RESULT:' <log> | tail -1`. With `status=gate_pending`, the gate is in the artifacts; nothing was approved.3. **List what is pending.** ```bash jq -c 'select(.status=="pending")' <dir>/decisions.jsonl gstack-gate render <dir>/gate.json --all # the numbered list and reply grammar, every page ```4. **Answer the gate** by composing the reply grammar (`rec`, `as-is`, `<id><option>` tokens such as `d3b uc1a`, or `rec except <tokens>`; bare yes/no is rejected) and feeding it back with the gate revision you read: ```bash gstack-gate parse <dir>/gate.json --reply "rec except d3b" --gate-rev 1 --json gstack-gate decisions <dir>/gate.json --reply "rec except d3b" --gate-rev 1 >> <dir>/decisions.jsonl ``` A stale revision is `GATE_REV_STALE` and a reply with unparsed tokens is `GATE_REPLY_UNPARSED`; both exit `1` and write nothing.5. **Read findings and tasks without the prose.** ```bash jq -c 'select(.severity=="Critical" and .disposition!="accepted")' <dir>/findings.jsonl jq -r '.id + "\t" + .title' <dir>/tasks.jsonl gstack-artifact urgent <dir>/findings.jsonl # the URGENT block, or "None." ```6. **Acknowledge consumption** so a second parent (or a retry) can tell the run was already read: `gstack-artifact ack <dir>/run.json --consumer <id>` is idempotent and records `consumed_by` in the manifest.## Driving `/autoplan` from a parent: `gstack-autoplan`On a host where the parent dispatches the reviewers itself (Capy, anyorchestrator without a Claude Code harness), `bin/gstack-autoplan` is theexplicit, durable state machine for the whole run. The parent never reads thereview record; it runs a loop over two commands and reads the printed lines.A parent on any host reads `autoplan/DRIVER.md` (its path is printed as`DRIVER:` by `gstack-autoplan --help` and the first `next`) instead ofautoplan/SKILL.md: the phase order, the artifact contract and the gate protocolin about a hundred lines, generated from the code.```bashAP=bin/gstack-autoplan$AP next --out <dir> --plan <plan.md> [--ui|--no-ui] [--developer-tool] [--no-dx] [--light] [--spend-cap <usd>]# PHASE: ceo snapshot=<sha> order=ceo,design,dx,eng# SCOPE: ui=yes (...) dx=yes (detected: ...) source=ui:detected,dx:detected# DRIVER: <root>/autoplan/DRIVER.md# Skipped sections: none (scope: ui=yes,dx=yes,source=ui:detected,dx:detected; checklist=loaded)# ATTEMPT: <run>-a1 phase=ceo voice=native prompt=<dir>/ceo-native-prompt.md result=<dir>/ceo-native.a1.md model_family=...# ATTEMPT: <run>-a2 phase=ceo voice=outside prompt=<dir>/ceo-outside-prompt.md result=<dir>/ceo-outside.a2.md model_family=differs from the native reviewer# SPEND: spent=0.00 reserved=0.00 unknown=0(0.00) worst_case=0.00 cap=none# GSTACK_RESULT: skill=autoplan status=awaiting_result run=<dir>```The first `next` prints `SCOPE: … source=ui:<flag|marker|detected>,dx:<…>`and, when CLI flags differ from the plan's marker, `SCOPE_PIN: add <!--gstack-autoplan-scope: … --> as the first line of <file>`; gstack never writesthe plan.1. **Dispatch each `ATTEMPT:`.** The native voice is a subagent on the parent's own model given the prompt file; the outside voice is a subagent on another model family, or `bin/gstack-outside-voice run --runner codex-cli|api --prompt <file> --out <file> [--model <id>]`, which prints `OUTSIDE_STATUS: <status> provider=<runner> model=<id> family=<f>`. Every reviewer writes its result to the printed `result=` path under the RESULT FORMAT below. `next` is idempotent: it reprints open attempts and never redispatches on its own (`EXECUTION_UNKNOWN` lists attempts whose process died without a result; `--redispatch <attempt>` mints a fresh one and `release --attempt <id>` returns its reservation).2. **Submit each result exactly once.** ```bash $AP submit --out <dir> --phase ceo --voice native --result <dir>/ceo-native.a1.md --model <id> --attempt <run>-a1 $AP submit --out <dir> --phase ceo --voice outside --result <dir>/ceo-outside.a2.md --model <id> --attempt <run>-a2 [--runner host-subagent (default)] [--usage-usd <n>] # BOUND: <run>-a1 phase=ceo voice=native model=<id> findings=7 sha256=<result hash prefix> # PHASE_CLOSED: ceo confirmed=4 disagree=1 new=2 native_only=1 coverage=both ``` Submit seals the bytes it bound as `<phase>-<voice>.<attempt>.bound.md` (read-only); a later write to the reviewer's file changes nothing bound, and another attempt's result file is refused (`ATTEMPT_MISMATCH`). Binding checks the receipt line against the phase snapshot (`RESULT_RECEIPT_MISSING`), parses the canonical findings fence (`RESULT_FINDINGS_MISSING`), refuses an outside model from the native family (`MODEL_FAMILY_CONFLICT`), and refuses a second bind of the same attempt or a bind while the phase is not awaiting it (`ATTEMPT_MISMATCH`, `PHASE_NOT_AWAITING`, exit 3). Both voices in closes the phase: the reconciliation (`confirmed` / `unverified` / `disagree` / `new` per outside finding, with disagreement and resolution kept separate) is written to `<phase>-consensus.{json,md}`, and every later phase's prompts (DX, design and Eng alike) carry each closed predecessor's consensus as data; a phase refuses to open without one (`CONSENSUS_MISSING`).3. **Loop `next` until `status=gate_pending`.** Eng always runs last. The gate (`gate.json`, `gate_rev`) lists user challenges as approval items, disagreements as auto items and `p1` plan approval; nothing is approved.4. **Answer the gate** with the reply grammar and the revision you read: ```bash $AP answer --out <dir> --gate-rev 1 --reply "rec" --by human # every recommendation, plan changes included (APPLY: ...; amend_pending) $AP answer --out <dir> --gate-rev 1 --reply "as-is" --by human # APPROVED: keeps every direction, no new paid phase $AP answer --out <dir> --gate-rev 1 --reply "rec except d1b" --by agent:<id> --owner-reply "<owner's words>" ``` `--by human` means the owner typed the tokens; `--by agent:<thread or id>` means an agent relayed them, and then `--owner-reply` (or `-` for stdin, `--owner-reply-file <path>`) stores the owner's words verbatim (`OWNER_REPLY_REQUIRED`); owner words that parse to different choices are refused (`GATE_OWNER_REPLY_MISMATCH`). An unattended run refuses an answer without `--by` (`ANSWER_BY_REQUIRED`, exit 3) and records the value as `answered_by` on every decision row and in the review record's gate line, so a gate an agent closed is distinguishable from one the owner closed. `gstack-autoplan recommend` changes one recommendation before relay; it bumps the gate's `rec_rev`, and a later `rec` needs the `--rec-hash` from the render the owner saw (`GATE_REC_STALE`). Every `GATE:` line is followed by `GATE_SPEND:` and `GATE_REC_COST:` (also `gate_cost` in `--json`; see `autoplan/DRIVER.md`). A user challenge both voices raised on a confirmed finding (a title match, not file:line proximity alone, which is `unverified`) with the same `changes` value is recommended as `b` only with one shared proposal: a `--reconcile` record naming it, or the same remedy from both voices. Different or missing remedies keep `a`, and option b shows both verbatim with the basis. `rec` (alias `all`) takes every recommendation, so it accepts the items recommended `b`. Every accepted plan change prints `APPLY: <decision id> <title> -> <chosen text>` and becomes a pending amendment: `next` refuses with `PLAN_AMEND_PENDING` and `export` refuses a `complete` run until `revise --incorporates` names it, or `revise --settle <id>` settles a packaging or ordering change that needs no plan edit. A stale revision (`GATE_REV_STALE`, exit 3), bare `yes`/`no`, or a conflicting reply (`GATE_REPLY_UNPARSED`) writes nothing. A reply that leaves approval items pending records only the answered auto items and keeps the gate; a later reply never overwrites an earlier answer. An accepted change reopens nothing at answer (status `amend_pending`); `revise` reopens each phase whose reviewed plan changed plus Eng, archives their prompts and consensus as `*.r<rev>.*` (sealed `*.bound.md` results stay in place), and the next gate is `gate_rev + 1`; `p1d` reruns every phase on the current plan; `p1e` ends `incomplete`.5. **Export and validate.** `$AP export --out <dir>` writes `plan.md` (with the `## URGENT, outside this plan` block first), `review-record.md`, `tasks.jsonl`, `decisions.jsonl`, `findings.jsonl`, `timing.json` and `run.json`; then `gstack-artifact validate <dir>/run.json` and the consumption steps above apply unchanged. `$AP status --out <dir>` and `resume` work after the run directory moves (paths are re-rooted; journal paths are run-relative). With `GSTACK_AUTOPLAN_CHECKPOINT_DIR` set (on Capy, `gstack-config set autoplan_checkpoint drive` defaults it to the private project-user Drive folder; unset, the first `next` prints the export line), a run at rest, after each bound voice and after each phase transition publishes an immutable, hash-listed generation under `<dir>/<run>/generations/` and switches `current.json` to it (the previous generation is kept; a stale copy never replaces a newer one; a directory overlapping the run is refused with `CHECKPOINT_OVERLAP`; a failure is a `CHECKPOINT: failed` warning that leaves the command's exit code alone). `$AP checkpoints --from <dir>` lists generations with their hash status, and `$AP resume --out <new dir> --from <dir>/<run>` restores the newest valid one after validating the staged run (`CHECKPOINT_INVALID`).Concurrency and recovery: every state write is a locked read-modify-write(`run.lock`; a second writer sees `RUN_LOCKED`), attempts are journaled to`attempts.jsonl` before dispatch, and a parent killed before or after a`submit` resumes with `next` without a duplicate charge(`test/autoplan-run-recovery.test.ts`, `test/autoplan-run-concurrency.test.ts`,`test/autoplan-answer-invalidation.test.ts`). `--spend-cap` admits each attemptthrough `spend.json` (`SPEND_CAP_EXCEEDED` refuses, exit 3); host-subagentspend is `unknown` and counted in `worst_case`. `--deadline <min>` makes the`run` subcommand cancel the children it started and marks the run`interrupted`.### RESULT FORMAT (what every reviewer file must contain)Each prompt file ends with this contract; `submit` enforces it.1. The first line is exactly `INPUT: <phase> <snapshot sha256>` (the receipt that binds the result to the snapshot both voices reviewed).2. The review is prose, then one fenced block of canonical findings, one JSON object per line: `{"id":"F1","severity":"High","title":"...","file":"...","line":12,"fix":"..."}` inside a ```` ```gstack-findings ```` fence. `severity` is Critical | High | Medium | Low | Informational; `"user_challenge": true` marks a recommended change to the plan's stated direction and needs `"changes": "scope" | "cost" | "direction"` (what accepting it changes); `"urgent": true` with `"suggested_owner"` marks a security or data-loss finding the plan does not own. An empty fence means no findings; a missing fence is refused.3. The whole result is written to the printed `result=` path.### Outside-voice runners| Runner | Access | Record label | Needs ||---|---|---|---|| `codex-cli` | repository, read-only, executes here | `repository review` | `codex` on PATH and logged in (`bin/gstack-codex-login` reads `OPENAI_API_KEY` from stdin) || `api` | supplied input only | `supplied-input review` | `--model <id>` and `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`; never silently equal to a repository review || `host-subagent` | the host's | `host-dispatched review` | `--result <file>` the subagent wrote, `--model <id>`; spend `unknown` |`bin/gstack-outside-voice runners` prints each runner's availability on thismachine; `family <model>` prints the model family `submit` compares. A completed`api` or `host-subagent` review is a full outside voice in the record, labeledby its runner. Result codes: `EXECUTION_UNKNOWN`, `RUN_LOCKED`,`RUN_NOT_INITIALIZED`, `PHASE_NOT_AWAITING`, `ATTEMPT_MISMATCH`,`RESULT_RECEIPT_MISSING`, `RESULT_FINDINGS_MISSING`, `MODEL_FAMILY_CONFLICT`,`SPEND_CAP_EXCEEDED`, `CONSENSUS_MISSING`, `OUTSIDE_RUNNER_UNAVAILABLE`(anchors in [troubleshooting.md](troubleshooting.md)).### Hand-run records, revised plans and admission- **Hand-run reviews.** `submit --record <file>` binds a review that did not follow the RESULT FORMAT: the `gstack-findings` fence, one findings table (Severity and Title columns), one severity-tagged list (`- [High] title`) or a `No findings.` line. Without its `INPUT:` line it binds only with `--attest "<reason>"` and `--attempt <id>` (receipt `attested`; refused after a later `revise`), and `gstack-artifact validate` prints `attested=<n>`. `--attempt` may be omitted when exactly one attempt is open. `submit --voice outside --unavailable "<reason>"` (or `--failed`) closes the phase `native_only` once native is bound; `next` and `resume` never redispatch it.- **Revising the plan in the same run.** Edit the source plan, then `$AP revise --out <dir> --plan <file> [--incorporates <decision id,...>]`. Every phase whose reviewed Implementation-plan hash differs reopens (plus Eng); newly in-scope phases are added; archives keep `.r<rev>` names with `.v<k>` only on collision; a revise at `gate_pending` makes the next gate `gate_rev + 1`. `--incorporates` discharges only the named amendments and refuses an unchanged plan; `revise --out <dir> --withdraw <decision id>` drops one as a journaled owner decision. `next` prints `PLAN_CHANGED` and `answer` prints `PLAN_SOURCE_CHANGED` when the source plan moved since the snapshot. A plan without both `## Implementation plan` and `## Review record` refuses with `PLAN_SECTIONS_INVALID`; `next --scaffold` reviews a copy with the missing heading added. `resume` completes an interrupted revise.- **Admission and upgrades.** `next`, `submit`, `answer`, `revise`, `export` and `run` refuse on a Capy host (`GSTACK_CAPY=1`) without an ok install verdict for this checkout, HEAD and workflow at `$GSTACK_INSTALL_VERDICT` (`INSTALL_UNVERIFIED`), and in any unattended session when the running Bun is below gstack's supported minimum (`RUNTIME_BELOW_MINIMUM`); the decision is the same one `gstack-skill-start` makes (see Install admission); `GSTACK_ALLOW_UNSUPPORTED_RUNTIME=1` overrides and records a run deviation. `status` and `resume` are never gated. A run directory written by an older gstack prints `GSTACK_VERSION_CHANGED` once and moves forward (legacy decision ids are renamed and journaled); one written by a newer gstack is refused.### Carry-forwardA gate revision after the first (`gate_rev` 2 and later, written after a`revise`) is answered with the owner's recorded words from the revision beforeit when nothing new needs their decision. `gstack-autoplan` prints`CARRIED: gate_rev=<n> <- gate_rev=<m> words="<their words>" by=<relayer> reason=<why>`,then the usual `APPROVED:` lines, and journals `gate_carried`. The carry needsall of: the earlier gate approved (`p1a` or `p1b`) with `rec` or "do it"(not item tokens), no item there left pending, and the owner's wordsrecorded; that gate was not itself carried; every accepted change incorporatedor settled; the plan file's bytes equal those recorded at the gate or at the`revise` that took the changes (any later edit refuses, an ELI5-only oneincluded); no urgent oroutside-plan finding open; and every new gate item one of the cases below.Anything else prints `CARRY: no (<why>)` (journal `carry_refused`) and the gategoes to the owner as before. `--no-carry-forward` on the first `next` turns itoff for the run.- **"do it".** When the owner's words were "do it" (their words, not a `captain:` relay of them), a new `auto` item that changes no scope, cost or direction, whose recommended option changes no plan text, and is no round or budget grant takes its recommendation. The decision row gets `carried_under: do it`, the output prints `CARRIED_UNDER_DO_IT:` per item, and the approval record lists them as "taken under "do it", not seen by the owner". `rec` carries no new item.- **Unreviewed post-cap delta.** A "plan changed after <phase> cap" item recommending `a` (accept) is read by one reviewer before it carries. `CARRY_CHECK:` names the attempt and the prompt (the delta against `plan-at-gate.r<m>.md`, the accepted changes, the full plan); the run reserves the estimate in `spend.json` and refuses when it is over `--carry-check-cap <usd>` (default 5) or the run's cap. Dispatch it to a model family other than the plan reviewers', then `check --out <dir> --attempt <id> --result <file> --model <id>` (`--same-family "<why>"` when no other family is available). A High or Critical finding, or `--unavailable "<reason>"`, leaves the gate for the owner. The verdict is saved as `carry_check` on `gate.json`, on the decision rows (`carry_check`) and in `<dir>/decisions.tsv`. A pending check is void, its reservation released and the gate left for the owner, when the owner answers the gate, the plan is revised, a new gate is written, or the delta changed after dispatch.Carried rows keep `answered_by: agent:gstack-autoplan` and name their source(`carried_gate_from`, `carried_gate_rev`, `carried_answered_by`);`gstack-approvals import --autoplan` writes the carried gate as its own row,and `gstack-owner-brief render --captain` opens with "Nothing pending.Carried forward from gate_rev <m>", followed by any items taken under "do it"without being shown to the owner.## Owner brief`gstack-owner-brief render --out <dir>` is what the owner sees at the finalgate, interactive or unattended: one page built from `gate.json`,`decisions.jsonl` and `findings.jsonl` (`BRIEF_INPUT_MISSING` when one isabsent). It opens with the `URGENT, outside this plan` block, then aplain-language summary (phases closed, findings accepted, how many decisionstake their default, the cycle time; `--summary <file>` or `<dir>/summary.md`replaces the generated sentence with the run's own), then the numbereddecisions through the gate list: seven per page (`--page N`), stable ids,each `auto` item annotated with the default taken if unanswered, each`approval` item `pending until you answer` or `decided <id><letter> on <date>`.It carries a `Cost so far:` sentence (spent, worst case, cap, and the estimate forthe phases `rec` can reopen); `render --captain` puts it in a `### Cost` section abovethe relaying-agent trailer. The last line names `review-record.md`, where the full review lives, and the`gstack-autoplan answer` call that answers the page. `--write` also saves`brief.md` in the run directory. `/autoplan` Phase 4 presents this outputverbatim and writes the former long report to `review-record.md`.After the final gate, `gstack-owner-brief close --out <dir> --plan <file>`rewrites every `draft direction stands until the owner decides` line in the planto the decided option and date (`DRAFT_DIRECTION: line <n> <id> rewritten`);lines whose decision is still pending stay and are reported as`DRAFT_DIRECTION_UNRESOLVED` (exit 1). `gstack-autoplan answer` runs the samerewrite when a reply completes the gate (journal event `draft_directions_closed`).## Lane done: pregate, the sealed guard and the handoff linesA lane under a coordinator runs `gstack-pregate run --allow-repo-commands` onits branch before it reports done (the unit tier on the changed files plusthe repo's guards, [docs/pregate.md#guards](pregate.md#guards)). In a repowhose `.gstack/pregate.json` has a `sealed` key it runs `gstack-pregate sealed`before any push or PR creation, since a PR tool may not run local hooks. Itshandoff carries, right after the `GSTACK_RESULT` line, the `gstack: ok|fail<rev>` line and then the `PREGATE:` line. The coordinator contract(`gstack-autoplan contract`) states the same rule word for word.## Timing`/autoplan` prints `ESTIMATE: ...` at Phase 0 (`gstack-autoplan-timingestimate --run <id> --out <dir>`, medians of the last ten recorded runs perphase, or `no history`), records each phase close (`gstack-autoplan-timingclose`), and prints the `CYCLE:` line at the final gate (`gstack-autoplan-timingsummary`). A close without an explicit start measures from the previous phase'send, else from the run start. The cross-run history lives at`<state root>/analytics/autoplan-timing.jsonl` and is skipped, with a printedline, on an ephemeral state root.## Reference run`test/fixtures/multi-agent-wave/reference-run/` is a complete unattended`/autoplan` run (the one that produced this wave's plan) and validates clean.`test/fixtures/multi-agent-wave/INCIDENTS.md` records what went wrong while itwas produced by hand and which validator rule now catches each incident.## Install admissionAn unattended run, and a `GSTACK_SESSION_KIND=spawned` run with `GSTACK_CAPY=1`,starts only on a supported Bun and, on a Capy machine (`GSTACK_CAPY=1`, set bythe installer's `GSTACK_LAUNCH` line), with a passing install verdict for thischeckout, its HEAD and the workflow. Otherwise `gstack-skill-start` prints`INSTALL: fail runtime|verdict — <detail>; fix: <command> (<CODE>)` and`GSTACK_RESULT: skill=<s> status=refused run=-`, and exits 3; stop and run thefix. `GSTACK_ALLOW_UNSUPPORTED_RUNTIME=1` admits anyway (`INSTALL_VERDICT:overridden`), recorded as a deviation. TypeScript entrypoints use`checkInstallAdmission` from `lib/install-verdict.ts`; the Bash side is`bin/gstack-install-verdict.sh`. See [capy-install.md](capy-install.md#the-launch-line).## The decision trailA long or unattended run keeps one tab-separated trail of its decisions at`<run dir>/decisions.tsv`, written through `gstack-decision-trail <file><phase> <decision> <why> <evidence> <result>`, so the parent reads what the runchose and why without the transcript. The helper stamps the time, writes theheader once, flattens each cell to one line and quotes a cell that startswith `=`, `+`, `-` or `@`, so evidence lifted from a PR title or a filenamecannot run as a formula when a reviewer opens the file in a spreadsheet.Log the forks, not the keystrokes: an approach chosen or dropped, a unit donewith its verification result, a revert and what triggered it, a blocker, onerow per iteration of a loop. Evidence is a pointer that resolves (a commit, aPR, `file:line`, an artifact path), never prose. A run that joins a trailother runs wrote (a pickup after a crash, a replacement machine, a later turnof the same thread) first runs `gstack-decision-trail start <file> <run id>`,which appends a `start` row naming the earlier rows and the run; appends with`--run <id>` refuse (`DECISION_TRAIL_START_REQUIRED`) until that row is thenewest start row, and `start` is a no-op when it already is, so a rerun of thesame step writes nothing twice.Before it hands back, the run audits the trail against what it did: every rowof its own stretch (from its `start` row to the next run's) maps to a realdecision or action, every evidence pointer resolves and shows what the rowclaims, and a fork or abandoned approach that shaped the result but is notlogged gets a row. The audit corrects the log, never the story: no row isedited or removed, an invented or wrong row stays and a new row supersedes itwith what actually happened. Then a reviewer on a different model family fromthe one that did the work (a Capy subagent on another family, or the outsidevoice) reads the trail and the transcript and flags what the owner should lookat: decisions with weak or missing evidence, verification claimed withoutproof, choices that look risky in hindsight, gaps a skim would miss. The run'sfinal report ends with an `Attention` section that opens with `reviewed by<model>` on its own line and lists each flag against its rows; `No flags` is avalid body, a missing model line is not. Self-review does not stand in forthis. `decisions.jsonl` stays the typed record `gstack-artifact` validates; thetrail is the plain one a person reads, and `column -s$'\t' -t decisions.tsv`renders it in a terminal.## What an unattended session may doA parent that starts a skill with `GSTACK_SESSION_KIND=unattended` grants itexactly this much, and the run asks for nothing beyond it. Anything outside thelist is an approval item: appended to `decisions.jsonl` with `kind: "approval"`and `status: "pending"`, named in the handoff, never taken.- **Merge: never.** The run ends at a receipt bound to the pushed head (`SHIP_RECEIPT`, [ship-policy.md#ship-before-ready](ship-policy.md#ship-before-ready)) or at a pending gate. Merging is the controller's act ([captain.md](captain.md)); a green check list, an approval, or a prompt that says "merge when green" does not move it to the lane. The same holds for enabling auto-merge, adding the PR to a merge queue, or `gh pr ready` on a PR the run did not open.- **Force-push: its own branch only, after a rebase the plan named, with a pinned lease.** The branch is one the run created or was handed in its prompt, never the base. The rebase is one the plan, the slot call or a `/modernize` disposition names before it happens, not one the run decides on its own; `git range-diff <old base>..<old head> <new base>..<new head>` runs before the push and its output goes in the handoff. The push is `git push --force-with-lease=<branch>:<sha observed before the rebase> origin <branch>`: a bare `--force-with-lease` protects only against commits this clone never fetched, and a plain `--force` is never allowed. A rejected lease means the remote moved: fetch, read what landed, and start the disposition again. `/ship` itself never rebases or force-pushes, and an unattended `/modernize` stops at its verdict; this route is for a run whose plan or slot call named the rebase before it started.- **Tests: the methods the repository's instructions name, without asking first.** AGENTS.md or CLAUDE.md, the named Setup commands, `package.json` scripts and the pregate configuration define the set; running one of them needs no question. A method outside the set (a framework the repo does not use, paid work past the stated cap, anything that touches a shared or production system, a test that writes outside the checkout) is pending.- **Proof is what the run saw itself.** Command output, a test that failed before the fix and passes after it, a screenshot, a file read in this session. A handoff note, an earlier PR comment or a parent's summary is context to recheck, not evidence; the handoff says which claims were rechecked and which were not.`/ship`'s handoff section (`ship/sections/handoff.md`) points here, so a lanereads the grant where it reports done.
Kvíz 15
Nejdřív si odpověď promyslete, potom ji odkryjte.
1Co přesně řídí klíč proactive a jaké má hodnoty?
Určuje, které skills smí gstack spustit nebo nabídnout bez vašeho příkazu. core (výchozí) spouští jen /office-hours, /review, /qa a /ship; all jakýkoli odpovídající skill; off nic, ani nabídky. Staré hodnoty true/false se čtou jako all/off. Skill, který sami pojmenujete, se spustí vždy.
2Proč je výchozí core a ne all?
Čtyři základní skills jsou ty nejpoužívanější a nekolidují s ostatními balíčky dovedností. Při all by gstack mohl soutěžit s cizími skills o stejné zadání. Dokument dokonce zmiňuje jako záložní plán off jako výchozí, pokud by kolize pokračovaly.
3Proč neznámá hodnota proactive: maybe skončí jako core, ale opt-out (no, 0, never…) jako off?
Je to záměr „fail closed“ pro opt-out: ručně napsané no, none, 0, disabled či never se čtou jako off, takže opt-out nikdy neselže do povolení. Hodnota, které gstack nerozumí, se vrací k bezpečnému výchozímu core.
4Jaké je doporučené dělení práce mezi frontier a smart modelem?
Frontier model pro nezávislé zpochybnění plánu, smart model pro implementaci. Jde o kurátorské doporučení, ne tvrzení, že jeden model vyhrává vždy. Vaše volba má přednost a doporučení nikdy samo nepřepne běžící sezení.
5K čemu je gstack-models resolve a co neprokazuje?
Offline vysvětlí, který model byl vybrán a které nastavení rozhodlo, a ukáže metadata o ověření katalogu. Neprokazuje, že je CLI nainstalované, že váš účet model smí používat ani že byl zkontrolován aktuální katalog dodavatele — to musíte ověřit sami.
6Co udělá gstack s chybně napsaným nastavením, například plan_review_tier = smart?
Výběr se zastaví, místo aby klíč fungoval, jako by nebyl nastaven. Je třeba opravit nebo odstranit pojmenovaný řádek. unset odstraní jen správně napsané záznamy key:. Chyba nahlas, ne tiše, brání neviditelně špatné konfiguraci.
7Proč je --token-cap „admission cap“ a ne tvrdý strop?
Host nelze zastavit uprostřed tahu z bashe. Cap proto kontroluje před přijetím práce podle součtu spotřeby, rezervací, neznámých poplatků, projekce, rezervy a režie zastavení. Přijatá práce může stát víc než odhad, takže běh může skončit mírně nad capem. Rezerva na závěr (výchozí 2M) zajišťuje místo pro kroky s receipty.
8Co znamená, že přesně na hranici capu se práce přijme, ale o jeden token víc ne?
Nerovnost je <= cap, takže součet rovný capu projde, součet o token vyšší ne. Je to deterministické pravidlo, které se dá otestovat a vysvětlit, ne odhad „zhruba“.
9Proč se paralelní dávka review rezervuje jako jeden součet předem?
Aby se nespustilo několik paralelních úloh, které by dohromady cap překročily, i když by každá zvlášť prošla. Rezervace celé dávky před startem zachytí kumulativní náklad.
10Co dělá GSTACK_SESSION_KIND=unattended a čím se liší od headless?
Rodič s ním pustí skill a čte jeho artefakty místo prózy. Nejsou prompty, nepublikuje se ani nesynchronizuje a otázky se rozhodují podle pravidel. U headless (CI, eval harness) otázka BLOCKuje; unattended ji buď rozhodne doporučenou volbou, nebo zapíše jako čekající schválení. unattended přebíjí GSTACK_HEADLESS, aby rodič mohl řídit běh uvnitř CI.
11Co se stane s otázkou bez doporučené volby a proč skill nikdy sám neschválí?
Zapíše se do decisions.jsonl jako kind: "approval", status: "pending" a běh skončí na další bráně se seznamem čekajících. Souhlasy, destruktivní či nevratné volby a závěrečná brána jsou rozhodnutí člověka. Skill, který by je schvaloval sám, by obešel smysl dohledu.
12Proč je zákaz publikování v unattended režimu vynucen „u zapisovačů“?
Pokyn v promptu může model přehlédnout. Zapisovače (telemetrie, synchronizace artefaktů, spool) mají kontrolu v kódu a v tomto režimu zápis přeskočí (TELEMETRY_WRITE: skipped…, ARTIFACTS_SYNC: skipped…). Zákaz je tak nezávislý na tom, jak model pokyn pochopí.
13Jaké pravidlo říká, kdy se skill nesmí ptát?
Pokud odpověď lze pozorovat — změřit, vykreslit, zavolat, spustit test — spustí se to a výsledek se oznámí. Platí pro pozorování lokální, jen pro čtení a zdarma. Akce měnící stav, sahající do živého/cizího systému nebo stojící peníze zůstává na vašem schválení.
14Jaké otázky smí skill uživateli klást?
Produktové a preferenční: co má produkt dělat, co chcete, kolik jste ochotni utratit či riskovat. Přicházejí už se změřenými možnostmi, takže se volí mezi doloženými variantami. Pozorovatelná otázka se u /plan-tune považuje za chybu ptajícího se skillu, ne za preferenci k doladění.
15Které obecné návyky z posledního oddílu nejsou zapsané v dokumentech gstacku a proč na to stránka upozorňuje?
CLAUDE.md jako paměť, ověřitelný cíl, malé commity, plán před kódem, secrets mimo chat a repozitář, čistý kontext a nedůvěřivé čtení výstupu AI. Stránka je odděluje, aby čtenář nepovažoval obecnou praxi za závazné pravidlo repozitáře a mohl ji posoudit sám.
Slovník pojmů 16
Pojmy vysvětlené v kontextu právě tohoto příkladu.
1Skill
Slash příkaz (/review, /qa, /ship…) s postupem konkrétní role. V tomto dílu jde o to, kdy se spouští a s jakými pojistkami.
2`proactive`
Klíč konfigurace s hodnotami core, all, off, který určuje, kolik skills se spouští nebo nabízí bez příkazu.
3`gstack-config`
Nástroj pro čtení a zápis nastavení (get, set, unset). Změny platí od další invokace.
4Tier `frontier` / `smart`
Kategorie modelů v politice: frontier pro nezávislé review plánu, smart pro implementaci. Konkrétní modely pro Anthropic i OpenAI jsou uvedené v tabulce model-policy.md.
5`gstack-models resolve`
Příkaz, který offline vysvětlí zvolený model a kdo ho vybral (výchozí hodnota, pin, tier).
6Pin modelu
Ruční nastavení konkrétního modelu v rámci tieru (model_frontier_claude). unset vrátí výchozí.
7`plan_review_tier`
Nastavení, který tier dělá review plánu: frontier, smart nebo host (nativní nastavení CLI).
8Admission cap
Strop kontrolovaný před přijetím práce, ne zastavující uprostřed. Běh jím může skončit lehce nad limitem.
9`BUDGET:` řádek
Výpis stavu rozpočtu s poli used, reserved, unknown, admission_cap, tail, meter, epoch a verdiktem continue|delegate|stop.
10Meter
Zdroj měření spotřeby (capy-tokens, claude-usage-tokens, estimate-tokens). Při změně meteru se otevře nová epocha.
11Fresh-context delegation
Předání těžkého segmentu podřízenému agentovi s čistým kontextem, aby hlavní sezení nezahlcovalo.
12`unattended`
Druh sezení (GSTACK_SESSION_KIND=unattended), v němž rodič čte artefakty, nejsou prompty a nic se nepublikuje.
13`decisions.jsonl`
Soubor, kam se zapisují rozhodnutí běhu: kind: auto (doporučená volba) a kind: approval s status: pending.
14Brána (gate)
Bod, kde běh končí a čeká na lidské schválení; skill ji nikdy neschvaluje sám.
15Pozorovatelná otázka
Otázka, jejíž odpověď lze zjistit spuštěním (měření, render, volání, test). Skill ji má zodpovědět sám, ne přenášet na uživatele.
16Fail closed
Zásada, že nejasnost vede k bezpečnějšímu výsledku. Typicky: ručně zadaný opt-out se čte jako off.
Souhrn
Společné rysy všech devíti příkladů:
- Ověřitelnost místo důvěry — testy nad fixture, regresní test, který musí před opravou selhat, druhý audit po doplnění dokumentace.
- Nejmenší oprávnění — scoped tokeny, capability tiery, trust politika per repozitář, opt-in snapshot.
- Bezpečné výchozí chování — offline render, blokované vzdálené obrázky, secrets mimo repozitář, loopback místo sítě.
- Hlasité selhání — chybná konfigurace zastaví výběr, vadný diagram se ukáže červeně, chybějící fixture je přiznaná mezera.
- Člověk rozhoduje o nevratném — brány a schválení nikdy neschvaluje skill sám.