.md file to compare - side-by-side diff against image
image
description: "Triggers on prompt mention of 'image'."
What it does for you
Creates a polished image and publishes it ready to use.
What it produces
A recent result, so you can see the kind of work it returns.
loading…
How to get it
These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.
For developers how this skill is built, graded, and how it runs
at a glance- the short version
what's inside - the parts that make up a skill 3/4 present
A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.
state/skills/image/SKILL.md
present
state/lib/image.ts
present
state/bin/image/
not present
state/skills/image/AGENTS.md
present
how it's graded - what counts as a good run 4 criteria · 3 deterministic · 1 judge
Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.
how it runs - the shared frame every skill uses 5/5 present
Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.
state/log/evals.ndjson what it has learned - fixes written back in over time sample
When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.
- Loading feedback rows…
how the work flows- who makes it, who checks it
what this step does
image: generate-iterate → linkedin-post → CDN (turns=1)
what this step does
SKILL.md- the skill, written out in plain English
image
Produce one image asset with actor-≠-auditor verification: Nano Banana 2 draws, Gemini 3.1 Pro vision model inspects with a structured JSON schema, the loop runs until verdict=pass or max_auto_turns is exhausted, every frame gets uploaded to the DO Spaces CDN, and the final frame URL is returned.
This is the first fully-worked skill in snappy-os. It's graduated - the prose steps point at a real script in state/bin/image/.
Inputs
| Key | Required | Default | Purpose |
|---|---|---|---|
illustration | yes | - | The visual prompt (subject, style, grounding refs) |
text | yes | - | The overlay text. Empty string is allowed for text-free images. |
slug | yes | - | Filename slug. Becomes {date}-{slug}.jpg on CDN. |
format | no | linkedin-post | One of the generate-iterate.sh templates |
max_auto_turns | no | 1 | Max fix iterations after the first draft |
Steps
1. Scope (default - no side effects)
Read last image run from state/log/chain.ndjson. Report the plan:
image: generate-iterate → linkedin-post → CDN (turns=1)
If inputs are missing, list them and stop. Do not touch the CDN.
2. Apply (requires all three inputs)
Run the script:
bash state/bin/image/generate-iterate.sh \
--illustration "<prompt>" \
--text "<overlay>" \
--slug "<slug>" \
--out-dir "/tmp/snappy-image-<slug>" \
--format "<format>" \
--max-auto-turns <n>
The script writes /tmp/snappy-image-<slug>/<slug>/state.json with a frames[] array. Each frame is {n, kind, url} - kind is draft, edit, or final.
3. Read state.json, return the final frame URL
const state = JSON.parse(readFileSync(statePath, "utf8"));
const last = state.frames[state.frames.length - 1];
return { ok: true, link: last.url, note: `${state.frames.length} frame(s)` };
4. Log from the caller (not the script)
generate-iterate.sh writes its own state.json under /tmp/snappy-image-<slug>/ but does NOT write to state/log/chain.ndjson or state/log/evals.ndjson. The snappy-os caller (the agent loop invoking this skill) is responsible for appending the chain row from the frame metadata the script returns:
{"ts":"...","run_id":"...","skill":"image","action":"delivered","link":"https://..."}
Eval
Actor: Nano Banana 2 (gemini-3.1-flash-image-preview) draws frames. Auditor: Gemini 3.1 Pro vision model (gemini-3.1-pro-preview) inspects each frame with responseJsonSchema returning:
{"verdict": "pass" | "fix", "primary_issue": "...", "fix_instruction": "..."}
Scoring (the caller - not the script - appends to state/log/evals.ndjson via score(). The script returns the verdict; the snappy-os runtime emits the eval row):
| Outcome | Score | Meaning |
|---|---|---|
| First frame verdict=pass | 1.0 | Clean one-shot |
| Fix applied, second frame pass | 0.5 | Iteration worked |
| Still fail after max_auto_turns | 0.0 | Ship nothing, escalate |
| Script error / no state.json | 0.0 | Infrastructure failure |
import { score } from "../lib/eval.ts";
score("image", run_id, {
score: verdict === "pass" ? 1.0 : fixed ? 0.5 : 0.0,
primary_issue: primary_issue ?? null,
frames: frames.length,
});
Why this is a real eval, not a metric: the inspector is a different model from the generator, with a structured schema it cannot rubber-stamp. The shell exit code is not the signal - the verdict field is.
Gotchas (P-fix any new ones here)
- The 6-layer composite template is encoded in the helper scripts under
state/bin/image/ itself (compose-ref.sh, composite-labels.py, classroom-mosaic.sh). There is no dedicated templates/ subdirectory - never freehand, always invoke the helpers.
- Light-on-cream logos fail contrast invisibly. Run the contrast check before
compositing (compose-ref.sh --contrast-check).
- Empty string for
textis valid (text-free background for composite).
The gate does not treat empty text as missing.
- Round-tripped drafts in the kernel sometimes have
,where em dashes
used to be. Image prompts are §4a-exempt - do not strip em dashes from illustration / prompt frontmatter.
Graduation
This skill is graduated. The script in state/bin/image/generate-iterate.sh is the deterministic path. Prose here exists only to explain intent and to document the eval. If the agent needs to regenerate the logic from scratch, it reads this page + the script.
Rubric
criteria:
- name: script_execution_success
kind: deterministic
check: "The `state/bin/image/generate-iterate.sh` script exits successfully (exit code 0)."
- name: cdn_url_returned
kind: deterministic
check: "The skill returns a well-formed URL for the final image frame, as indicated in the `link` field of the skill's output."
- name: state_json_integrity
kind: deterministic
check: "The `/tmp/snappy-image-<slug>/<slug>/state.json` file exists and contains a valid JSON object with a `frames` array, where the last frame has `kind: 'final'`."
- name: vision_model_verdict
kind: judge
check: "The `verdict` field in the vision model's inspection output for the final frame is 'pass'."AGENTS.md- what the AI loads when this skill comes up
image - loader
Per-turn rules for the image skill. Full reference: state/skills/image/SKILL.md. Do not skip these.
Critical Rules
- Always use the helper scripts in
state/bin/image/(generate-iterate.sh,compose-ref.sh,composite-labels.py,classroom-mosaic.sh) - never freehand. There is NOstate/bin/image/templates/directory; the 6-layer composite is encoded inline in those scripts. Staletemplates/path tripped every fresh agent (FIXED 2026-04-29). - Image-prompt frontmatter is §4a-exempt. Do NOT strip em-dashes from
illustration/layer_*/metaphor_rationale/image_prompt- those go to the image model, not a reader. (memoryfeedback_image_prompts_not_4a) - Actor ≠ auditor. Nano Banana 2 (
gemini-3.1-flash-image-preview) draws; Gemini 3.1 Pro (gemini-3.1-pro-preview) inspects withresponseJsonSchemareturning{verdict, primary_issue, fix_instruction}. Never collapse them. (CONSTITUTION invariant #3.) - Light-on-cream logos fail contrast invisibly. Run
compose-ref.sh --contrast-checkBEFORE compositing. - Pipeline is sealed. 6-layer template + cream-paper ref + locked layers + learned suffix is the validated path that produced "masterful" consistency. Don't change the pipeline. (memory
feedback_image_system_validated) - Educational formats (
cycle-*,process-*,comparison-*,hierarchy-*,annotated-*) enforce HARD R6: NO text labels inside the drawing area; titles only in the lower-third title slot. If--illustrationincludes stage labels likeSTAGE 1,SKILL RUNS, or letter tags, the inspector fails v1 every time. Describe each zone's VISUAL SHAPE only; let the title carry the words. (FIXED 2026-04-29 from snappy-os-system-poster.) - Never fan out parallel agent-browser writes to upload - silent drops. Serialize uploads; parallelize generation only. (memory
feedback_no_parallel_browser_writes) --max-auto-turns Nis a misnomer.generate-iterate.shruns ONE auto-edit pass regardless of N (lines 332-348). v2 frames are uninspected. Force a v2 verdict via--resume <run-dir>+ rerun, or extend the script's loop (>10 LOC, structural).- The CALLER appends the eval row, not the script.
generate-iterate.shwrites onlystate.jsonunder/tmp/snappy-image-<slug>/; it does NOT touchstate/log/chain.ndjsonorstate/log/evals.ndjson. The snappy-os runtime is responsible for the row.
Commands
| ui dashboard | state/skills/image/resources/ui.openui |
| step | command |
|---|---|
| invoke | bash state/bin/image/generate-iterate.sh --illustration "<prompt>" --text "<overlay>" --slug "<slug>" --out-dir "/tmp/snappy-image-<slug>" --format "<format>" --max-auto-turns <n> |
| state file | /tmp/snappy-image-<slug>/<slug>/state.json - frames[] of {n, kind, url} where kind ∈ {draft, auto-edit, manual-edit} (NOT final) |
| verdict | only frames[0] carries a verdict; subsequent edits are unverified by the script |
| score | frame[0].verdict=="pass" → 1.0 ; frame[0].verdict=="fix" AND frame[1] exists → 0.5 ; no frame[1] after fix → 0.0 ; script error / no state.json → 0.0 |
| eval log | state/log/evals.ndjson - {ts, run_id, skill:"image", score, primary_issue, frames, mode:"auto", actor_session_id:"nano-banana-2-<run_id>", auditor_session_id:"gemini-3-1-pro-<run_id>-aud"} |
| chain log | caller appends {ts, run_id, skill:"image", action:"delivered", link} to state/log/chain.ndjson |
| contrast | bash state/bin/image/compose-ref.sh --contrast-check |
| reference | state/skills/image/SKILL.md |
| writeback | state/log/loader-feedback.log |
OpenUI Resource
- Skill-owned OpenUI Lang resource:
state/skills/image/resources/ui.openui. Read it before rendering or editing this skill's generated component surface. - Skill-owned Lang shape (defineComponent, zod schema, view):
state/skills/image/ui.tsx. This is the canonical source forImageGalleryPreviewand its sub-shapeImageGalleryPreviewImage- their props (images, captions, the 2-col grid contract), descriptions, and view chrome. Snappy-chat re-exports them fromweb/src/genui/image-gallery-preview.tsx; do NOT inline a parallel definition there. Surfaced + enforced bystate/lint/skill-shape-locality.ts. - Treat this resource as a first-class artifact of the skill, not a generic chat response. Improve it when the skill's user-facing output needs to become richer.
- System resources compose OpenUI primitives and inherit SnappyChat tokens. Use
ui_contract: brandedin SKILL.md only for deliberate platform or client visuals.
Known Pitfalls
- Empty string for
textis valid (text-free background for composite). The gate does not treat empty text as missing. - The shell exit code is irrelevant - the
verdictfield in the inspector's structured JSON is the signal. - Run-this from drain is a paid call (Nano Banana 2 + Gemini Pro vision). When briefs queue
imagefor "RUN THIS" withoutillustration/text/sluginputs, emit[SKIPPED]rather than fabricating an eval row. - The 6-layer composite template lives inside the helper scripts - there is no
templates/directory.
Self-Test
An agent reading this should correctly:
- [ ] Use the helper scripts in
state/bin/image/(NOT a non-existenttemplates/)? - [ ] Skip §4a (em-dash) checks on image-prompt frontmatter?
- [ ] Run
compose-ref.sh --contrast-checkbefore compositing logos? - [ ] Trust the
verdictfield, not the shell exit code? - [ ] Read frame
kindas one ofdraft|auto-edit|manual-edit(NOTfinal) and treat onlyframe[0].verdictas the score signal? - [ ] For educational formats, describe each zone's visual shape - never embed stage/letter labels in the drawing area?
- [ ] Recognize
--max-auto-turnsas effectively1until the script's retry loop is added?
<!-- kernel-ok: historical attribution for the PID-loader pattern. -->
Self-correcting loader (PID feedback)
This is the rule that makes loaders learn. Ported from snappy-kernel, where it demonstrably worked: the snappy-dom-cartographer skill mapped Skool admin UI once, every later ship-agent inherited the full map for free.
Before you finish, do two things:
1. Fix gaps (P - proportional). MANDATORY. If this loader didn't cover your case - if you had to read another file, run an undocumented command, work around a wrong selector, or discover a quirk - you MUST attempt an Edit to this AGENTS.md before you log.
- Default action: edit this file. Surgical. Add the missing line, table
row, or code example where it belongs. No restructuring.
- Only
LOGGEDis allowed when: the fix needs >10 lines, spans multiple
files, or requires a structural rewrite. In that case the state/regen/drain.sh queue picks it up asynchronously.
- "I didn't have time" / "it's minor" / "the next agent will figure it out"
are NOT valid reasons. Minor gaps compound - that's the whole point of this loop.
- Concrete example of a valid P-fix: discover
agent-browser screenshot
takes path positionally not as --output <path>. One line in a table. Edit it in. Do not just log it.
- The goal: the next agent never has to leave the loader.
2. Log the result.
echo "[$(date -u +%FT%TZ)] image: <what was missing or fixed> [FIXED|LOGGED] action_kind=<kind>" >> state/log/loader-feedback.log
<slug>MUST be the literal folder name of this loader
(state/skills/<slug>/AGENTS.md). The class token between [ts] and : is the producer slug, the writeback class, AND the grade class - they must be equal so state/lib/controller-tune.ts can pair the brief.
FIXED= you patched this loader inline (P-fix).LOGGED= too large for inline; the PostToolUse enqueue + Stop-hook drain
will rewrite the loader from scratch on next session-end.
action_kindis the SECOND pairing predicate (added 2026-04-27, task #327).
Pick the value that describes what you actually did - same slug, different action_kind means the writeback satisfies a different brief layer:
shape-ok- only frontmatter-shape verification passed (rare from
a human; usually emitted by the lint, not a loader echo)
skill-ran- the skill ran end-to-end and an eval row landed
in state/log/evals.ndjson
loader-rewritten- you EDITED this AGENTS.md inline (the FIXED case),
OR the regen drain rewrote it
pattern-elevated- you promoted a recurring failure to a Critical Rule
(rule fix or new-skill scaffold) If you LOGGED (couldn't fix inline), omit action_kind - the inferrer will pick it up from your body keywords.
Do not skip this. Every agent run must leave the system better than it found it. The loader is the setpoint; you are the sensor; the gap is the error signal; closing the gap is the correction.
api.ts- the code it can call
#!/usr/bin/env npx tsx
/**
* state/lib/image.ts -- Image generation and CDN upload client.
*
* Same shape as xano.ts, github.ts, pipeline.ts: typed functions, one import.
* Wraps the shell scripts in state/bin/image/ under a clean interface.
*
* import { generate, upload } from "../lib/image.ts";
* const result = await generate({ illustration: "...", text: "Title", slug: "my-img", format: "skool-course" });
* console.log(result.cdnUrl);
*
* CLI:
* npx tsx state/lib/image.ts generate --illustration "..." --text "Title" --slug test --format linkedin-post
* npx tsx state/lib/image.ts upload --file /tmp/img.png --context course-imagery --slug my-slug
*/
import { execSync } from "child_process";
import { readFileSync, existsSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
const BIN = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "image");
// ── Types ──
export type ImageFormat =
| "linkedin-post"
| "linkedin-carousel"
| "skool-course"
| "blog-hero"
| "video-slide"
| "thumbnail"
| "instagram-feed"
| "instagram-story";
export interface GenerateOptions {
/** Visual concept for the illustration area (use this OR topic+council) */
illustration?: string;
/** Topic for art council to debate (use with council) */
topic?: string;
/** Title text rendered in the lower third */
text: string;
/** Short slug for filenames and CDN path */
slug: string;
/** Target platform format (default: linkedin-post) */
format?: ImageFormat;
/** Output directory (default: /tmp/snappy-image) */
outDir?: string;
/** Max self-inspection edit rounds (default: 1) */
maxAutoTurns?: number;
/** Optional reference image path for style transfer */
ref?: string;
/** Art council panel to use (e.g. "art", "textbook", "whimsy") */
council?: string;
/** Fan out all council proposals in parallel (default: false) */
matrix?: boolean;
}
export interface GenerateResult {
/** Local path to final image */
path: string;
/** CDN URL of final image */
cdnUrl: string;
/** Inspector verdict: "pass" or "fix" */
verdict: string;
/** Eval score: 1.0 if pass, 0.5 if fix-applied, 0.0 if error */
score: number;
/** Number of versions generated (1 = no edits needed) */
versions: number;
/** All CDN URLs for each version */
allUrls: string[];
/** Matrix results (only when council + matrix mode) */
matrix?: { expert: string; url: string }[];
}
export interface UploadOptions {
/** Local file path */
file: string;
/** CDN context/folder (default: images/generated) */
context?: string;
/** Slug for the CDN key */
slug?: string;
}
// ── Functions ──
/**
* Generate an image with self-inspecting loop.
* Calls generate-iterate.sh under the hood.
*/
export async function generate(opts: GenerateOptions): Promise<GenerateResult> {
if (!opts.illustration && !opts.topic) {
throw new Error("generate requires either illustration or topic");
}
const outDir = opts.outDir ?? "/tmp/snappy-image";
const format = opts.format ?? "linkedin-post";
const maxTurns = opts.maxAutoTurns ?? 1;
const args: string[] = [];
// Council mode: pass topic + council panel, let experts debate the concept
if (opts.topic && opts.council) {
args.push(`--topic ${q(opts.topic)}`);
args.push(`--council ${q(opts.council)}`);
if (opts.matrix) args.push("--matrix");
} else if (opts.illustration) {
args.push(`--illustration ${q(opts.illustration)}`);
}
args.push(
`--text ${q(opts.text)}`,
`--slug ${q(opts.slug)}`,
`--out-dir ${q(outDir)}`,
`--format ${format}`,
`--max-auto-turns ${maxTurns}`,
);
if (opts.ref) args.push(`--ref ${q(opts.ref)}`);
const stdout = run(`bash ${BIN}/generate-iterate.sh ${args.join(" ")}`, 600_000);
// Parse CDN URLs from stdout (lines like "v1: https://...")
const urls = [...stdout.matchAll(/v\d+:\s+(https:\/\/\S+)/g)].map((m) => m[1]);
// Parse matrix results if present (lines like " Steinberg: https://...")
const matrixMatches = [...stdout.matchAll(/^\s+(\w+):\s+(https:\/\/\S+)/gm)];
const matrix =
matrixMatches.length > 0 ? matrixMatches.map((m) => ({ expert: m[1], url: m[2] })) : undefined;
// Read state.json for structured result
const stateFile = `${outDir}/${opts.slug}/state.json`;
let verdict = "unknown";
let versions = urls.length;
let finalPath = `${outDir}/${opts.slug}/v${versions}.png`;
if (existsSync(stateFile)) {
const state = JSON.parse(readFileSync(stateFile, "utf-8"));
const frames = state.frames ?? [];
const last = frames[frames.length - 1];
if (last) {
verdict = last.verdict ?? "unknown";
}
versions = frames.length;
finalPath = `${outDir}/${opts.slug}/v${versions}.png`;
}
const score = verdict === "pass" ? 1.0 : versions > 1 ? 0.5 : 0.0;
return {
path: finalPath,
cdnUrl: urls[urls.length - 1] ?? "",
verdict,
score,
versions,
allUrls: urls,
matrix,
};
}
/**
* Upload a local file to the DO Spaces CDN.
* Returns the public HTTPS URL.
*/
export async function upload(opts: UploadOptions): Promise<string> {
const args = [`--file ${q(opts.file)}`];
if (opts.context) args.push(`--context ${q(opts.context)}`);
if (opts.slug) args.push(`--slug ${q(opts.slug)}`);
const stdout = run(`bash ${BIN}/cdn-upload.sh ${args.join(" ")}`);
// Last line of stdout is the https URL
const lines = stdout.trim().split("\n");
const url = lines.find((l) => l.startsWith("https://")) ?? lines[lines.length - 1];
return url.trim();
}
// ── Helpers ──
function q(s: string): string {
return `"${s.replace(/"/g, '\\"')}"`;
}
function run(cmd: string, timeout = 300_000): string {
return execSync(cmd, {
encoding: "utf-8",
timeout,
stdio: ["pipe", "pipe", "pipe"],
});
}
// ── CLI ──
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("image.ts")) {
const [, , command, ...rest] = process.argv;
function cliArg(name: string): string | undefined {
const idx = rest.indexOf(`--${name}`);
return idx >= 0 ? rest[idx + 1] : undefined;
}
(async () => {
switch (command) {
case "generate": {
const illustration = cliArg("illustration");
const topic = cliArg("topic");
const text = cliArg("text");
const slug = cliArg("slug");
if ((!illustration && !topic) || !text || !slug) {
console.error(
"usage: image.ts generate --topic '...' --council art --text '...' --slug <slug> [--format <fmt>] [--matrix]",
);
console.error(
" or: image.ts generate --illustration '...' --text '...' --slug <slug> [--format <fmt>]",
);
process.exit(2);
}
const result = await generate({
illustration: illustration || undefined,
topic: topic || undefined,
council: cliArg("council") || undefined,
matrix: rest.includes("--matrix"),
text,
slug,
format: (cliArg("format") as ImageFormat) ?? "linkedin-post",
outDir: cliArg("out-dir"),
maxAutoTurns: cliArg("max-auto-turns") ? Number(cliArg("max-auto-turns")) : undefined,
ref: cliArg("ref"),
});
console.log(JSON.stringify(result, null, 2));
break;
}
case "upload": {
const file = cliArg("file");
if (!file) {
console.error("usage: image.ts upload --file <path> [--context <ctx>] [--slug <slug>]");
process.exit(2);
}
const url = await upload({ file, context: cliArg("context"), slug: cliArg("slug") });
console.log(url);
break;
}
default:
console.log("usage: image.ts <generate|upload> [options]");
console.log("");
console.log(" generate --illustration '...' --text '...' --slug <slug> [--format <fmt>]");
console.log(" upload --file <path> [--context <ctx>] [--slug <slug>]");
}
})();
}
scripts- helper scripts it can run
prose-only skill - 7 inline code blocks live in SKILL.md above (no state/bin/ sidecar yet).
how we check it- the checks, plus the last 10 runs
| timestamp | verb | score | primary_issue | artifact |
|---|---|---|---|---|
| 2026-04-29 17:10Z | - | 0.50 | - | - |
| 2026-04-28 04:30Z | - | 0.50 | - | - |
| 2026-04-25 04:11Z | - | 1.00 | - | - |
| 2026-04-25 02:05Z | - | 1.00 | - | - |
| 2026-04-24 17:06Z | - | 1.00 | - | - |
| 2026-04-24 05:33Z | - | 1.00 | - | - |
| 2026-04-21 15:58Z | - | 1.00 | - | - |
| 2026-04-21 15:56Z | - | 1.00 | - | - |
| 2026-04-21 03:53Z | - | 1.00 | - | - |
| 2026-04-16 00:05Z | - | 0.50 | - | - |