SLOPSHOPPER

waffle-view

A pane showing this repo's resolved wafflestack state — behavioral keys, run files, locks, drift, sliced to what the last `/skill` cares about — read through…

panecommandpromptprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · waffle-view
│ ┃ Waffle view ✕ › fix the failing auth test and add an audit log call │ ┃ ┏━┳━┳━┓ wafflestack · no state read yet │ ┃ ┗━┻━┻━┛ one batter, every repo ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ last refresh failed: wafflestack state ⏺ Update(src/auth.ts) │ ┃ printed no JSON ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /waffle-view │ ⎿ waffle-view: Waffle view pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Waffle view
┏━┳━┳━┓ wafflestack · no state read yet ┗━┻━┻━┛ one batter, every repo last refresh failed: wafflestack state printed no JSON
README

<h1 align="center">WaffleStack</h1> <img src="assets/wafflestack-social-animated.svg" width="100%" alt="WaffleStack — a stack of golden waffles with an animated syrup pour"> <h3 align="center">Reusable AI agent and skill definitions, distributed shadcn-style but <strong>update-safe</strong>.</h3> <a href="https://github.com/sponsors/dustinkeeton"><img src="https://img.shields.io/badge/Sponsor-GitHub-F08A1D?logo=githubsponsors&logoColor=F5C752&labelColor=241204" alt="Sponsor on GitHub"></a> <a href="https://buymeacoffee.com/dustinkeeton"><img src="https://img.shields.io/badge/Support-Buy%20Me%20a%20Coffee-F08A1D?logo=buymeacoffee&logoColor=F5C752&labelColor=241204" alt="Support on Buy Me a Coffee"></a>


One canonical source repo, rendered into harness-native files inside each consuming project — the same batter, baked fresh wherever you need it. Every supported harness gets both agents and skills: Claude Code, OpenAI Codex, and the cross-tool .agents/ directory.

Where it fits: wafflestack is the update-safe distribution layer for agent process and skills content — consumer-owned files under a lock manifest, drift detection via doctor, and explicit, diffable upgrades with versioned migrations. It carries content across repos and harnesses and keeps it current; it doesn't produce that content (that's a process pack like gstack) or run it (that's an always-on agent runtime).

Vocabulary

  • waffle — an individual installable item: an agent, a skill, or a mod (a Claude Code plugin from the toolkit's marketplace, enabled in .claude/settings.json for the claude target only).
  • stack — a named group of waffles.
  • syrup — the generic files/ payload a stack can also carry (CI workflows, scripts, config), rendered verbatim to any repo-relative path with the same {{key}} substitution, lock tracking, and drift detection.

Quick start

Guided (recommended)

Let your coding agent drive the whole setup. Kick it off either way:

Agent prompt — paste to your coding agent:

Set up wafflestack in this repo: run `npx github:dustinkeeton/wafflestack setup` and
follow the playbook it prints. Ask me which stacks to enable before you render.

Inline shell (Claude Code / Codex) — type in the prompt (the ! prefix runs the command in-session and feeds its output back to the model; --yes keeps npx non-interactive):

! npx --yes github:dustinkeeton/wafflestack setup

setup prints an agent playbook plus a generated inventory of every stack, config key, and prerequisite. The agent then detects targets, asks which stacks to enable, fills .waffle/waffle.yaml, renders, runs doctor, and reports what it did.

The labels wafflestack's workflows and skills gate on are listed once — table plus a copy-paste gh label create bootstrap — in schema/SETUP.md § Required labels.

Manual

cd your-project
npx github:dustinkeeton/wafflestack setup             # writes a starter .waffle/waffle.yaml if missing + prints the playbook
# edit .waffle/waffle.yaml: pick stacks, fill in config values
npx github:dustinkeeton/wafflestack#vX.Y.Z render     # X.Y.Z = latest release tag; renders harness files + lock

release resolution.

Commands

CommandWhat it does
setup (alias init)Write a starter .waffle/waffle.yaml if none exists (never overwrites one), then print the agent-driven install playbook + generated toolkit inventory. --gitignore also appends overlay/local-lock ignores.
listShow every waffle and syrup file per stack with its status; --interactive for a TTY multi-select, --check-prereqs to probe the prerequisites a row would add.
togglePick which rendered skills an agent may invoke on its own (disable-model-invocation, per project): TTY picker, or --disable/--enable <skill>; writes .waffle/waffle.yaml and re-renders.
render (alias bake)Regenerate every managed file from source + config, prune stale ones, write the lock.
install [ref…]Add stacks/items to .waffle/waffle.yaml, pull dependencies, then render. Bare = render.
upgradeMove an install across toolkit versions: print CHANGELOG, run migrations, re-render, doctor.
doctorDiff managed files against the lock; report edits, missing files, env gaps. Exit 1 on drift.
reportPrint redacted diagnostics (lock, config keys, doctor summary) for an upstream toolkit bug report; --json for machines.
statePrint the resolved state — every behavioral key with its value, layer and tokens, the delegate run files, lock status and drift; --json for the documented document.
eject <item>Stop managing an item — its files stay and become project-owned; drops it from include:. install <item> un-ejects it.
uninstallRemove the whole install (reports until you pass --yes; keeps hand-edited files).
reinstallRe-render the same selection from clean; --clean --yes for a full reset.
`avatars <sync\status>`Keep Gravatar in sync with the installed agent roster.
validateToolkit-developer lint: manifests, frontmatter, placeholders, and agent refs.
helpPrint usage and a one-line description of every command and flag.

Run npx github:dustinkeeton/wafflestack help for the full flag detail on any command.

Some guidance

  1. Never edit rendered files — render overwrites them. Put additions in .waffle/extensions/{agents,skills}/<name>.md and parameters in .waffle/waffle.yaml.
  2. Account-specific values (bot identities, board IDs) go in .waffle/waffle.local.yaml — gitignored, merged over the committed config, and never propagated: the lock hashes the canonical render, so every teammate's lock is byte-identical.
  3. Updates are re-renders — until they aren't. Patch/minor tags are a plain render; a breaking tag needs upgrade. See Updating.
  4. doctor is the CI drift gate — run it on PRs to fail the build on any hand-edited managed file. Add --allow-missing when some renders are gitignored, --verify-render to also catch config changes that were never re-rendered.

Deciding what to commit? Committing vs. gitignoring the rendered output walks the trade-off.

Hit a toolkit bug? Report it upstream, not in your own tracker: /waffle-report <what went wrong> (from the wafflestack stack) collects wafflestack report's redacted diagnostics — config keys only, no overlay, no absolute paths — shows you the exact payload, and files it against the toolkit's issue forms on your yes. No gh auth? It prints the body and a prefilled new-issue URL instead.

Want the state at a glance? The wafflestack stack also ships the toolkit's first Claude Code mod, waffle-view. Render enables it in your .claude/settings.json (the wafflestack marketplace, pinned to your waffle.toolkitRef release, plus enabledPlugins["waffle-view@wafflestack"], beside your own keys); Claude Code offers the install the next time you trust the repo, or run /plugin install waffle-view@wafflestack (outside a rendered repo: claude plugin marketplace add dustinkeeton/wafflestack first). Then type /waffle-view to toggle a pane showing every behavioral key's effective value and source layer, the delegate run files, lock status, and doctor drift — all read through wafflestack state --json, refreshed as you work. The pane narrows to the last /skill you typed (a Skill-tool call the model makes does not move it; a /name that is not a toolkit skill reads as the full view), and the values it shows include your gitignored waffle.local.yaml overlay.

Updating

WaffleStack ships as git tags (vX.Y.Z), versioned from a consumer's point of view:

BumpExampleMeans for youHow to take it
patch0.5.0 → 0.5.1content-only fixes… render
minor0.5.0 → 0.6.0new stacks/items, additive config… render
majorrenamed/removed item, new required key, changed layoutneeds a migration… upgrade

The … is always a pinned spec (npx github:dustinkeeton/wafflestack#vX.Y.Z) — unpinned commands refuse. Full detail — the upgrade command, migrations, pin-moving, and release resolution — lives in Upgrades and release resolution.

Learn more

License

© 2026 Dustin Keeton. Licensed under the Apache License, Version 2.0.


<a href="https://github.com/dustinkeeton/wafflestack/blob/waffle-telemetry/.waffle/telemetry/tokens.json"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fdustinkeeton%2Fwafflestack%2Fwaffle-telemetry%2F.waffle%2Ftelemetry%2Ftokens.json" alt="Claude token spend (automated runs)"></a> <img src="assets/wafflestack-flat.svg" width="24" alt=""><br> A <strong>WaffleWorks</strong> project

Source 3 files
hooks/register.tsx 308 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderNode } from 'claude-code'
3
4import type { WaffleViewDoc, WaffleViewKey, WaffleViewSlice } from '../types'
5import {
6  BRAND,
7  CAPTION_TONE,
8  HEADING_TONE,
9  LOCAL_BIN,
10  LOCAL_CLI,
11  PANE,
12  TAGLINE,
13  TITLE,
14  WAFFLE_GLYPH,
15  formatMode,
16  isOverridden,
17  isPersonsPrompt,
18  keyTone,
19  parseStateOutput,
20  promptSkill,
21  resolveArgv,
22  selectKeys,
23  selectSlice,
24  sourceTone,
25  statusTone,
26  tokensOf,
27  valueLines,
28  valueTone,
29} from './state'
30
31const doc = atom({ plugin: 'waffle-view', key: 'doc' } as const, null)
32const error = atom({ plugin: 'waffle-view', key: 'error' } as const, null)
33const isRefreshing = atom({ plugin: 'waffle-view', key: 'isRefreshing' } as const, false)
34// The last thing the person invoked (#563): `issue` after `/issue`, null after a plain prompt.
35// Tracked whether or not the pane is open, so opening it after `/issue` already slices.
36const skill = atom({ plugin: 'waffle-view', key: 'skill' } as const, null)
37
38type Dollar = Pick<EngineInterface, 'state' | 'process' | 'fs' | 'ui'>
39
40// The only read path: `wafflestack state --json --offline` through `$.process`. The last good
41// document survives a failed refresh; the failure is shown beside it.
42async function refresh($: Dollar): Promise<void> {
43  if (await read($, isRefreshing)) return
44  await update($, isRefreshing, () => true)
45  try {
46    const argv = resolveArgv({
47      hasLocalCli: await $.fs.exists(LOCAL_CLI),
48      hasLocalBin: await $.fs.exists(LOCAL_BIN),
49    })
50    const parsed = parseStateOutput(await $.process.run(argv, { timeoutMs: 120_000 }))
51    if (parsed.doc) await update($, doc, () => parsed.doc)
52    await update($, error, () => parsed.error)
53  } catch (err) {
54    await update($, error, () => (err instanceof Error ? err.message : String(err)))
55  } finally {
56    await update($, isRefreshing, () => false)
57  }
58}
59
60const isOpen = async ($: Dollar) => (await $.ui.panes()).some(pane => pane.id === PANE)
61
62export const register: Register = on => {
63  on('session.start', async ($, e, next) => {
64    await $.command.register({
65      name: PANE,
66      description: "Toggle the waffle view: this repo's resolved wafflestack state.",
67    })
68
69    return next(e)
70  })
71
72  // `/waffle-view` toggles: a second invocation closes the pane instead of re-opening it.
73  on('command.run', { command: PANE }, async $ => {
74    if (await isOpen($)) {
75      await $.ui.close({ id: PANE })
76
77      return { text: 'Waffle view pane closed.' }
78    }
79    await $.ui.open({ id: PANE, title: TITLE })
80    await refresh($)
81
82    return { text: 'Waffle view pane opened.' }
83  })
84
85  on('command.run', async ($, e, next) => {
86    if (e.command !== PANE && isPersonsPrompt(e.origin)) await update($, skill, () => e.command)
87    const ran = await next(e)
88    if (e.command !== PANE && (await isOpen($))) void refresh($)
89
90    return ran
91  }).catch(($, e, next) => next(e))
92
93  on('prompt.submit', async ($, e, next) => {
94    const invoked = promptSkill(e.text)
95    if (invoked !== PANE && isPersonsPrompt(e.origin)) await update($, skill, () => invoked)
96    const entered = await next(e)
97    if (await isOpen($)) void refresh($)
98
99    return entered
100  }).catch(($, e, next) => next(e))
101
102  on('turn.complete', async ($, e, next) => {
103    const done = await next(e)
104    if (e.agentId === undefined && (await isOpen($))) void refresh($)
105
106    return done
107  }).catch(($, e, next) => next(e))
108
109  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
110    const { Box, Text } = $.ui.resolve(e)
111    const state = await read($, doc)
112    const failure = await read($, error)
113    const busy = await read($, isRefreshing)
114    const context = { skill: await read($, skill) }
115    const slice = state ? selectSlice(state, context) : null
116    const wide = e.props.bodyColumns >= 100
117
118    const section = (title: string, rows: RenderNode[]) => (
119      <Box flexDirection="column" marginBottom={1}>
120        <Text underline {...HEADING_TONE}>{title}</Text>
121        {rows}
122      </Box>
123    )
124    const dim = (text: string) => <Text dimColor>{text}</Text>
125    const caption = (text: string) => <Text {...CAPTION_TONE}>{text}</Text>
126    const lockNote = (key: WaffleViewKey) =>
127      isOverridden(key) ? <Text color="warning">{` (lock: ${formatMode(key.canonical)})`}</Text> : null
128
129    const keyRow = (key: WaffleViewKey) => {
130      const tokens = tokensOf(key)
131      if (!wide) {
132        return (
133          <Box>
134            <Text {...keyTone(key)}>{key.key}</Text>
135            <Text {...valueTone(key.value)}>{`  ${formatMode(key.value)}`}</Text>
136            {lockNote(key)}
137            <Text {...sourceTone(key.source)}>{`  ${key.source}`}</Text>
138            {tokens && <Text wrap="truncate-end" {...CAPTION_TONE}>{`  ${tokens}`}</Text>}
139          </Box>
140        )
141      }
142
143      return (
144        <Box>
145          <Box width={30}>
146            <Text wrap="truncate-end" {...keyTone(key)}>{key.key}</Text>
147          </Box>
148          <Box width={26}>
149            <Text {...valueTone(key.value)}>{formatMode(key.value)}</Text>
150            {lockNote(key)}
151          </Box>
152          <Box width={16}>
153            <Text {...sourceTone(key.source)}>{key.source}</Text>
154          </Box>
155          <Text wrap="truncate-end" {...CAPTION_TONE}>{tokens}</Text>
156        </Box>
157      )
158    }
159
160    const keysSection = (state: WaffleViewDoc) => {
161      const keys = selectKeys(state, context)
162      const header = wide ? (
163        <Box>
164          <Box width={30}>{caption('key')}</Box>
165          <Box width={26}>{caption('value')}</Box>
166          <Box width={16}>{caption('source')}</Box>
167          {caption('tokens')}
168        </Box>
169      ) : null
170      const rows: RenderNode[] =
171        keys.length === 0
172          ? [dim(slice ? `/${slice.skill} reads no behavioral key` : 'no behavioral keys in the selected stacks')]
173          : keys.map(keyRow)
174
175      return section(`Keys (${keys.length})`, header ? [header, ...rows] : rows)
176    }
177
178    // The other config a sliced skill reads: name, layer, and the value's lines.
179    const configSection = ({ skill: name, config }: WaffleViewSlice) => {
180      if (config.length === 0) return null
181      const rows: RenderNode[] = config.flatMap(({ key, value, source }) => [
182        <Box>
183          <Text bold color={BRAND.cream}>{key}</Text>
184          <Text {...sourceTone(source)}>{`  ${source}`}</Text>
185        </Box>,
186        ...valueLines(value).map(line => <Text wrap="truncate-end">{`  ${line}`}</Text>),
187      ])
188
189      return section(`Config /${name} reads (${config.length})`, rows)
190    }
191
192    // Sliced: only the files the skill writes, the delegate facts when they are among them, the
193    // rest by path; nothing when it writes none. Full view: the delegate facts, as before.
194    const runFilesSection = ({ runFiles: { delegate } }: WaffleViewDoc) => {
195      if (slice && slice.files.length === 0) return null
196      const sliced = slice ? new Set(slice.files) : null
197      const delegateShown = delegate && (!sliced || sliced.has(delegate.checkpoints.path) || sliced.has(delegate.memory.path))
198      if (!delegateShown) {
199        if (!sliced) return section('Run files', [dim('delegate: not declared by a selected stack')])
200
201        return section('Run files', [...sliced].map(file => <Text>{file}</Text>))
202      }
203      const { checkpoints, memory } = delegate
204      const latest = checkpoints.latest
205      const rows: RenderNode[] = [
206        <Text {...(checkpoints.exists ? {} : { dimColor: true })}>
207          {checkpoints.exists
208            ? `delegate checkpoints: ${checkpoints.runs} run${checkpoints.runs === 1 ? '' : 's'} in ${checkpoints.path}`
209            : `delegate checkpoints: none (${checkpoints.path})`}
210        </Text>,
211      ]
212      if (latest) {
213        rows.push(
214          <Text {...statusTone(latest.parseError === null)}>
215            {`  latest ${latest.runId} · phase ${latest.lastPhase ?? '—'} · ${latest.mtime}${latest.parseError ? ` · unreadable: ${latest.parseError}` : ''}`}
216          </Text>,
217        )
218      }
219      rows.push(
220        <Text {...(memory.exists ? statusTone(!memory.overCap) : { dimColor: true })}>
221          {memory.exists
222            ? `delegate memory: ${memory.bytes}/${memory.maxBytes} bytes${memory.overCap ? ' — OVER CAP' : ''}`
223            : `delegate memory: none (${memory.path})`}
224        </Text>,
225      )
226      if (sliced) {
227        const known = new Set([checkpoints.path, checkpoints.latest?.file, memory.path])
228        for (const file of sliced) if (!known.has(file)) rows.push(<Text>{file}</Text>)
229      }
230
231      return section('Run files', rows)
232    }
233
234    const locksSection = ({ locks }: WaffleViewDoc) => {
235      const describe = (lock: WaffleViewDoc['locks']['committed']) =>
236        lock.present
237          ? `toolkit ${lock.toolkitVersion ?? '?'} (${lock.toolkitStatus ?? '?'}${lock.toolkitRef ? `, ${lock.toolkitRef}` : ''}) · ${lock.files} files`
238          : 'absent'
239      const sync = locks.inSync === null ? '' : locks.inSync ? ' · in sync with committed' : ' · DIVERGED from committed'
240
241      return section('Locks', [
242        <Text>{`tree: ${locks.tree}`}</Text>,
243        <Text {...(locks.committed.present ? {} : { color: 'warning' as const })}>{`committed: ${describe(locks.committed)}`}</Text>,
244        <Text {...(locks.local.present ? statusTone(locks.inSync, 'warning') : { dimColor: true })}>
245          {`local: ${locks.local.present ? describe(locks.local) + sync : 'none'}`}
246        </Text>,
247      ])
248    }
249
250    const driftSection = ({ drift }: WaffleViewDoc) => {
251      const rows: RenderNode[] = drift.ok
252        ? [<Text {...statusTone(true)}>clean — the render matches the lock</Text>]
253        : [
254            <Text {...statusTone(false)}>{`${drift.modified.length} modified · ${drift.missing.length} missing`}</Text>,
255            ...drift.modified.slice(0, 5).map(file => dim(`  M ${file}`)),
256            ...drift.missing.slice(0, 5).map(file => dim(`  ? ${file}`)),
257          ]
258      if (drift.absentDocs.length > 0) rows.push(dim(`${drift.absentDocs.length} generated .waffle/ docs absent (optional)`))
259
260      return section('Drift', rows)
261    }
262
263    const projectSection = ({ project }: WaffleViewDoc) =>
264      section('Project', [
265        <Text>{`targets: ${project.targets.join(', ') || '—'}`}</Text>,
266        <Text>{`stacks: ${project.stacks.join(', ') || '—'}`}</Text>,
267        <Text wrap="truncate-end">{`include: ${project.include.length ? project.include.join(', ') : '—'}`}</Text>,
268        <Text wrap="truncate-end">{`eject: ${project.eject.length ? project.eject.join(', ') : '—'}`}</Text>,
269        dim(`local overlay: ${project.localOverlay ? 'yes' : 'no'}`),
270        ...project.errors.map(problem => <Text color="error">{problem}</Text>),
271      ])
272
273    // The splash moment: the brand waffle, Golden, with the toolkit's name and version beside it.
274    const heading = (
275      <Box marginBottom={1}>
276        <Box flexDirection="column" marginRight={2}>
277          {WAFFLE_GLYPH.map(row => <Text {...HEADING_TONE}>{row}</Text>)}
278        </Box>
279        <Box flexDirection="column">
280          <Box>
281            <Text {...HEADING_TONE}>{state ? `wafflestack ${state.cli.version}` : 'wafflestack'}</Text>
282            {state
283              ? dim(` (${state.cli.status}${state.cli.commit ? ` ${state.cli.commit.slice(0, 7)}` : ''})`)
284              : dim(busy ? ' · reading state…' : ' · no state read yet')}
285            {slice && <Text color="suggestion">{` · /${slice.skill}`}</Text>}
286            {state && busy && dim(' · refreshing…')}
287          </Box>
288          {caption(TAGLINE)}
289        </Box>
290      </Box>
291    )
292
293    return (
294      <Box flexDirection="column">
295        {heading}
296        {failure && <Text color="error">{`last refresh failed: ${failure}`}</Text>}
297        {state && !slice && projectSection(state)}
298        {state && keysSection(state)}
299        {slice && configSection(slice)}
300        {state && runFilesSection(state)}
301        {state && !slice && locksSection(state)}
302        {state && !slice && driftSection(state)}
303        {slice && caption(`sliced to what /${slice.skill} reads — a plain prompt restores the full view`)}
304      </Box>
305    )
306  })
307}
308
hooks/state.ts 148 lines
1import type { WaffleViewContext, WaffleViewDoc, WaffleViewKey, WaffleViewLayer, WaffleViewSlice } from '../types'
2
3export const PANE = 'waffle-view'
4export const TITLE = 'Waffle view'
5export const LOCAL_CLI = 'installer/cli.mjs'
6export const LOCAL_BIN = 'node_modules/.bin/wafflestack'
7export const TOOLKIT_SPEC = 'github:dustinkeeton/wafflestack'
8const STATE_ARGS = ['state', '--json', '--offline']
9
10export type Probe = { hasLocalCli: boolean; hasLocalBin: boolean }
11export type ProcessOutput = { exitCode: number; stdout: string; stderr: string }
12export type Parsed = { doc: WaffleViewDoc; error: null } | { doc: null; error: string }
13
14// The toolkit's own checkout first (dogfooding), then an installed dependency, then npx over
15// the toolkit's default branch: `state` is read-only, so the unpinned spec `render` refuses
16// (#373) is safe here.
17export function resolveArgv({ hasLocalCli, hasLocalBin }: Probe): string[] {
18  if (hasLocalCli) return ['node', LOCAL_CLI, ...STATE_ARGS]
19  if (hasLocalBin) return [LOCAL_BIN, ...STATE_ARGS]
20  return ['npx', '--yes', TOOLKIT_SPEC, ...STATE_ARGS]
21}
22
23export function parseStateOutput({ exitCode, stdout, stderr }: ProcessOutput): Parsed {
24  const tail = stderr.trim().split('\n').filter(Boolean).slice(-3).join(' · ')
25  if (exitCode !== 0) {
26    return { doc: null, error: `wafflestack state exited ${exitCode}${tail ? `: ${tail}` : ''}` }
27  }
28  let parsed: unknown
29  try {
30    parsed = JSON.parse(stdout)
31  } catch {
32    return { doc: null, error: `wafflestack state printed no JSON${tail ? ` (${tail})` : ''}` }
33  }
34  const version = typeof parsed === 'object' && parsed !== null ? (parsed as { version?: unknown }).version : undefined
35  if (version !== 1) {
36    return { doc: null, error: `state document version ${String(version)} is not the version 1 this pane reads` }
37  }
38  return { doc: parsed as WaffleViewDoc, error: null }
39}
40
41// The context seam (#563): the behavioral keys the pane shows for what the user is doing — every
42// key, in the CLI's order, unless `context.skill` names a skill the document knows.
43export function selectKeys(doc: WaffleViewDoc, context: WaffleViewContext): WaffleViewKey[] {
44  const slice = selectSlice(doc, context)
45  return slice ? slice.keys : doc.keys
46}
47
48// Null restores the full view: no skill, or one `doc.skills` does not know (a built-in command, a
49// skill outside the toolkit). `config` is what the skill reads beyond its behavioral keys.
50export function selectSlice(doc: WaffleViewDoc, context: WaffleViewContext): WaffleViewSlice | null {
51  if (context.skill === null) return null
52  const skill = doc.skills[context.skill]
53  if (!skill) return null
54  const wanted = new Set(skill.keys)
55  const keys = doc.keys.filter(key => wanted.has(key.key))
56  const behavioral = new Set(keys.map(key => key.key))
57  const config = skill.keys
58    .filter(key => !behavioral.has(key) && key in doc.config)
59    .map(key => ({ key, value: doc.config[key]!.value, source: doc.config[key]!.source }))
60
61  return { skill: context.skill, keys, config, files: skill.files }
62}
63
64// What a prompt invoked: `/issue 12` → `issue`; a plain prompt → null.
65export function promptSkill(text: string): string | null {
66  const m = /^\s*\/([\w][\w.-]*)/.exec(text)
67  return m ? m[1]! : null
68}
69
70// Whether a prompt is the person's own: typed, bridged, the SDK host's, or a plugin's `asUser`
71// one — never a peer's message, a task notification or a scheduled trigger delivered meanwhile.
72// A session always stamps an origin; one that is absent (a test's own submit) counts as the person's.
73export function isPersonsPrompt(origin: { kind: string; asUser?: true } | undefined): boolean {
74  if (!origin) return true
75  if (origin.kind === 'plugin') return origin.asUser === true
76  return origin.kind === 'composer' || origin.kind === 'bridge' || origin.kind === 'sdk' || origin.kind === 'unclassified'
77}
78
79// A config value as pane lines: strings line by line (the first `max`, then a count), anything
80// else as one JSON line.
81export function valueLines(value: unknown, max = 8): string[] {
82  if (value === null || value === undefined) return ['—']
83  if (typeof value !== 'string') return [JSON.stringify(value)]
84  const lines = value.split('\n')
85  if (lines.length <= max) return lines
86  return [...lines.slice(0, max), `… ${lines.length - max} more line${lines.length - max === 1 ? '' : 's'}`]
87}
88
89export function formatMode(value: unknown): string {
90  if (value === null || value === undefined) return '—'
91  return typeof value === 'string' ? value : JSON.stringify(value)
92}
93
94export function tokensOf(key: WaffleViewKey): string {
95  if (!key.flag) return ''
96  const sides: string[] = []
97  if (key.flag.on) sides.push(`on ${key.flag.on}`)
98  if (key.flag.off) sides.push(`off ${key.flag.off}`)
99  return sides.join(' · ')
100}
101
102export const isOverridden = (key: WaffleViewKey): boolean => key.value !== key.canonical
103
104// The brand palette (assets/README.md, "Palette"): every colour role below resolves to one of
105// these, or to a theme status key; a pane with colour stripped keeps bold/dim and the literal words.
106export const BRAND = {
107  golden: '#F5C752',
108  syrup: '#F08A1D',
109  pocket: '#DE8127',
110  cream: '#FFF3DC',
111  caption: '#C9A87C',
112} as const
113
114export type Tone = { color?: string; dimColor?: boolean; bold?: boolean }
115
116// The 2-row variant of the CLI waffle (assets/README.md, "CLI waffle"), for the pane header.
117export const WAFFLE_GLYPH = ['┏━┳━┳━┓', '┗━┻━┻━┛'] as const
118export const TAGLINE = 'one batter, every repo'
119
120export const HEADING_TONE: Tone = { color: BRAND.golden, bold: true }
121export const CAPTION_TONE: Tone = { color: BRAND.caption, dimColor: true }
122
123// A key name: Cream, or the theme's warning when its value differs from the lock.
124export const keyTone = (key: WaffleViewKey): Tone => (isOverridden(key) ? { color: 'warning' } : { color: BRAND.cream })
125
126// A behavioral value by kind: `true` Golden, `false` muted, `prompt` Syrup, other text Cream, unset dim.
127export function valueTone(value: WaffleViewKey['value']): Tone {
128  if (value === null || value === undefined) return { dimColor: true }
129  if (value === true) return { color: BRAND.golden, bold: true }
130  if (value === false) return { color: BRAND.caption, bold: true }
131  if (value === 'prompt') return { color: BRAND.syrup, bold: true }
132  return { color: BRAND.cream, bold: true }
133}
134
135// Where a value came from: the stack default dim, the project's `waffle.yaml` Pocket, the
136// machine's local overlay Syrup.
137export function sourceTone(source: WaffleViewLayer): Tone {
138  if (source === 'local-overlay') return { color: BRAND.syrup }
139  if (source === 'waffle.yaml') return { color: BRAND.pocket }
140  return { dimColor: true }
141}
142
143// A pass/fail state in the theme's status colours; null is no verdict.
144export function statusTone(ok: boolean | null, failure: 'error' | 'warning' = 'error'): Tone {
145  if (ok === null) return {}
146  return { color: ok ? 'success' : failure }
147}
148
types/index.d.ts 98 lines
1// waffle-view's contract: the `wafflestack state --json` document (shape version 1) as the pane
2// reads it, the context the pane slices by (#563), and the values the mod keeps in `$.state`.
3
4export type WaffleViewMode = boolean | 'prompt'
5
6export type WaffleViewLayer = 'local-overlay' | 'waffle.yaml' | 'stack-default'
7
8export type WaffleViewKey = {
9  key: string
10  stacks: string[]
11  value: WaffleViewMode | string | null
12  source: WaffleViewLayer
13  canonical: WaffleViewMode | string | null
14  default: WaffleViewMode | string | null
15  modes: WaffleViewMode[]
16  prompt: boolean
17  nonInteractive: boolean | 'fail' | null
18  lockMode: WaffleViewMode | null
19  configModes: WaffleViewMode[] | null
20  flag: { on: string | null; off: string | null } | null
21  description: string
22}
23
24export type WaffleViewCheckpoint = {
25  file: string
26  runId: string
27  mtime: string
28  lastPhase: string | null
29  sections: string[]
30  parseError: string | null
31}
32
33export type WaffleViewDelegate = {
34  checkpoints: { path: string; exists: boolean; runs: number; latest: WaffleViewCheckpoint | null }
35  memory: { path: string; exists: boolean; bytes: number; maxBytes: number; overCap: boolean }
36}
37
38export type WaffleViewLock = {
39  path: string
40  present: boolean
41  toolkitVersion: string | null
42  toolkitStatus: string | null
43  toolkitRef: string | null
44  files: number
45}
46
47/** One declared config key, resolved (`config` in the document, #563). */
48export type WaffleViewConfigValue = { value: unknown; source: WaffleViewLayer; stacks: string[] }
49
50/** What one skill cares about (`skills[<name>]` in the document, #563). */
51export type WaffleViewSkillContext = { keys: string[]; files: string[] }
52
53export type WaffleViewDoc = {
54  version: 1
55  cli: { version: string; status: string; commit: string | null }
56  project: {
57    targets: string[]
58    stacks: string[]
59    include: string[]
60    eject: string[]
61    localOverlay: boolean
62    errors: string[]
63  }
64  keys: WaffleViewKey[]
65  runFiles: { delegate: WaffleViewDelegate | null }
66  locks: {
67    committed: WaffleViewLock
68    local: WaffleViewLock
69    tree: 'committed' | 'local'
70    inSync: boolean | null
71    divergence: unknown
72  }
73  drift: { ok: boolean; modified: string[]; missing: string[]; absentDocs: string[]; notes: string[] }
74  config: Record<string, WaffleViewConfigValue>
75  skills: Record<string, WaffleViewSkillContext>
76}
77
78/**
79 * What the user is doing right now, as far as the pane can tell: the name the last prompt invoked
80 * (`/issue` → `issue`), or null after a plain prompt. A name `doc.skills` does not know (a built-in
81 * command, a skill outside the toolkit) reads as the full view.
82 */
83export type WaffleViewContext = { skill: string | null }
84
85/** A sliced view: the skill, the behavioral keys and other config it reads, the run files it writes. */
86export type WaffleViewSlice = {
87  skill: string
88  keys: WaffleViewKey[]
89  config: { key: string; value: unknown; source: WaffleViewLayer }[]
90  files: string[]
91}
92
93declare module 'claude-code' {
94  interface PluginState {
95    'waffle-view': { doc: WaffleViewDoc | null; error: string | null; isRefreshing: boolean; skill: string | null }
96  }
97}
98