From 805536c43567ce9dfd7330fda99474ac00ab2a3d Mon Sep 17 00:00:00 2001 From: garrytan Date: Sat, 3 Oct 2026 19:49:05 +0000 Subject: [PATCH 1/6] fix: mark Remaining Work provenance so restore verifies guessed steps first (#3004) /context-save now starts every Remaining Work item with `Open.` and ends it with how this session knows it: `(path run)` with the observed outcome, `(path read)` or `(path assumed)` for concrete paths, and `(target state checked)`, `(code read)` or `(path assumed)` for writing steps. /context-restore keeps saved order and original text but splits the list into Next steps and Verify first (assumed, code-read, failed runs and unmarked concrete or writing items), prints a banner for pre-marker checkpoints, and option A walks saved order so an unverified first item is verified before any later step runs. Adds a prompt-byte contract test for the marker wire format and a periodic behavior E2E (context-restore-provenance-order) that seeds an assumed item ahead of a run item plus a code-read write. Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- context-restore/SKILL.md | 29 +++++++- context-restore/SKILL.md.tmpl | 29 +++++++- context-save/SKILL.md | 24 ++++++- context-save/SKILL.md.tmpl | 24 ++++++- .../context-remaining-work-provenance.test.ts | 63 +++++++++++++++++ test/helpers/touchfiles-data.ts | 5 ++ test/skill-e2e-context-skills.test.ts | 69 +++++++++++++++++++ 7 files changed, 235 insertions(+), 8 deletions(-) create mode 100644 test/context-remaining-work-provenance.test.ts diff --git a/context-restore/SKILL.md b/context-restore/SKILL.md index f552fe9e1da..d0345843bb8 100644 --- a/context-restore/SKILL.md +++ b/context-restore/SKILL.md @@ -506,6 +506,22 @@ checkpoint(s) from another project; only this project's are listed." If it print `LEGACY_BUCKET`, relay that line. If the chosen file is `ROOT_DIFFERS`, add "Saved from another checkout of this repository at `{project_root}`." as info. +**Sort Remaining Work by provenance.** Keep every item's original text and saved +order, and drop nothing. Put an item under **Verify first** when it: +- ends in `(path assumed)` or `(code read)`; +- ends in `(path run)` but its text reports a failure; +- has no marker and is a writing step (migration, sync, insert, import, a dialog that + writes) or names a concrete path (a runnable command, CLI flag or switch, config key + or value, or file or directory path). + +Every other item goes under **Next steps**: `(path run)` with a successful outcome, +`(path read)`, `(target state checked)`, and unmarked items that neither write nor +name a concrete path. Verifying means read-only inspection: read the file or the +target, or run a command that changes nothing. Checkpoints saved before provenance +markers existed have none, so their concrete-path items land under Verify first. When +the file has no provenance markers at all, print this line above the groups: +`This checkpoint predates provenance markers; items naming commands, paths or writes are listed under Verify first.` + Read the chosen file and present a summary: ``` @@ -522,7 +538,13 @@ Status: {status} {summary from saved file} ### Remaining Work -{remaining work items} +{legacy banner line, if it applies} + +Next steps +{Next steps items, in saved order, original text} + +Verify first (inspect read-only before executing anything) +{Verify first items, in saved order, original text} ### Notes {notes} @@ -540,7 +562,10 @@ After presenting, ask via AskUserQuestion: - B) Show the full saved file - C) Just needed the context, thanks -If A, summarize the first remaining work item and suggest starting there. +If A, take the first Remaining Work item in saved order. If it is under Next steps, +suggest starting there. If it is under Verify first, suggest verifying it (read-only) +before doing it or any later item, so a later runnable step never jumps ahead of an +unverified earlier one. --- diff --git a/context-restore/SKILL.md.tmpl b/context-restore/SKILL.md.tmpl index 4ba1571c981..55db95b2195 100644 --- a/context-restore/SKILL.md.tmpl +++ b/context-restore/SKILL.md.tmpl @@ -180,6 +180,22 @@ checkpoint(s) from another project; only this project's are listed." If it print `LEGACY_BUCKET`, relay that line. If the chosen file is `ROOT_DIFFERS`, add "Saved from another checkout of this repository at `{project_root}`." as info. +**Sort Remaining Work by provenance.** Keep every item's original text and saved +order, and drop nothing. Put an item under **Verify first** when it: +- ends in `(path assumed)` or `(code read)`; +- ends in `(path run)` but its text reports a failure; +- has no marker and is a writing step (migration, sync, insert, import, a dialog that + writes) or names a concrete path (a runnable command, CLI flag or switch, config key + or value, or file or directory path). + +Every other item goes under **Next steps**: `(path run)` with a successful outcome, +`(path read)`, `(target state checked)`, and unmarked items that neither write nor +name a concrete path. Verifying means read-only inspection: read the file or the +target, or run a command that changes nothing. Checkpoints saved before provenance +markers existed have none, so their concrete-path items land under Verify first. When +the file has no provenance markers at all, print this line above the groups: +`This checkpoint predates provenance markers; items naming commands, paths or writes are listed under Verify first.` + Read the chosen file and present a summary: ``` @@ -196,7 +212,13 @@ Status: {status} {summary from saved file} ### Remaining Work -{remaining work items} +{legacy banner line, if it applies} + +Next steps +{Next steps items, in saved order, original text} + +Verify first (inspect read-only before executing anything) +{Verify first items, in saved order, original text} ### Notes {notes} @@ -214,7 +236,10 @@ After presenting, ask via AskUserQuestion: - B) Show the full saved file - C) Just needed the context, thanks -If A, summarize the first remaining work item and suggest starting there. +If A, take the first Remaining Work item in saved order. If it is under Next steps, +suggest starting there. If it is under Verify first, suggest verifying it (read-only) +before doing it or any later item, so a later runnable step never jumps ahead of an +unverified earlier one. --- diff --git a/context-save/SKILL.md b/context-save/SKILL.md index 803e7db3a7e..bdc3997b201 100644 --- a/context-save/SKILL.md +++ b/context-save/SKILL.md @@ -404,10 +404,30 @@ Using the gathered state plus your conversation history, produce a summary cover 1. **What's being worked on** — the high-level goal or feature 2. **Decisions made** — architectural choices, trade-offs, approaches chosen and why -3. **Remaining work** — concrete next steps, in priority order +3. **Remaining work** — concrete next steps, in priority order, each marked with + how this session knows it (see the provenance table below) 4. **Notes** — anything a future session needs to know (gotchas, blocked items, open questions, things that were tried and didn't work) +**Remaining Work provenance.** Every item starts with the status `Open.` and never +with a completion token such as `[done]` or `[executed]`. Then pick its trailing +marker by the first rule that applies: + +| # | The item is... | Marker | Use when this session... | +|---|----------------|--------|--------------------------| +| 1 | a writing step (migration, sync, insert, import, a dialog that writes), with or without a concrete path | `(target state checked)` | inspected the target's schema or state (for example the unique key) | +| | | `(code read)` | read the writer but not the target | +| | | `(path assumed)` | inferred the write without reading either | +| 2 | otherwise, names a concrete path: a runnable command, CLI flag or switch, config key or value, or file or directory path | `(path run)` | executed it and observed the outcome; state the outcome in the item (`exit 0`, `failed: `) | +| | | `(path read)` | read the code or file but did not execute it | +| | | `(path assumed)` | inferred it without running or reading it, however confident | +| 3 | anything else | none | (`Open.` alone) | + +Writing steps have their own markers because whether a write is safe to repeat +depends on the target's state, not on the code that writes. Examples: +`Open. Run the suite with CONFIG=staging. (path run) exit 0` and +`Open. Switch B reads config Y. (path assumed)`. + If the user provided a title, use it. Otherwise, infer a concise title (3-6 words) from the work being done. @@ -496,7 +516,7 @@ files_modified: ### Remaining Work -{Numbered list of concrete next steps, in priority order} +{Numbered list of concrete next steps, in priority order. Each item starts with `Open.` and ends with its provenance marker from Step 2, or no marker under rule 3.} ### Notes diff --git a/context-save/SKILL.md.tmpl b/context-save/SKILL.md.tmpl index d9bfef97748..26d38cb6a15 100644 --- a/context-save/SKILL.md.tmpl +++ b/context-save/SKILL.md.tmpl @@ -79,10 +79,30 @@ Using the gathered state plus your conversation history, produce a summary cover 1. **What's being worked on** — the high-level goal or feature 2. **Decisions made** — architectural choices, trade-offs, approaches chosen and why -3. **Remaining work** — concrete next steps, in priority order +3. **Remaining work** — concrete next steps, in priority order, each marked with + how this session knows it (see the provenance table below) 4. **Notes** — anything a future session needs to know (gotchas, blocked items, open questions, things that were tried and didn't work) +**Remaining Work provenance.** Every item starts with the status `Open.` and never +with a completion token such as `[done]` or `[executed]`. Then pick its trailing +marker by the first rule that applies: + +| # | The item is... | Marker | Use when this session... | +|---|----------------|--------|--------------------------| +| 1 | a writing step (migration, sync, insert, import, a dialog that writes), with or without a concrete path | `(target state checked)` | inspected the target's schema or state (for example the unique key) | +| | | `(code read)` | read the writer but not the target | +| | | `(path assumed)` | inferred the write without reading either | +| 2 | otherwise, names a concrete path: a runnable command, CLI flag or switch, config key or value, or file or directory path | `(path run)` | executed it and observed the outcome; state the outcome in the item (`exit 0`, `failed: `) | +| | | `(path read)` | read the code or file but did not execute it | +| | | `(path assumed)` | inferred it without running or reading it, however confident | +| 3 | anything else | none | (`Open.` alone) | + +Writing steps have their own markers because whether a write is safe to repeat +depends on the target's state, not on the code that writes. Examples: +`Open. Run the suite with CONFIG=staging. (path run) exit 0` and +`Open. Switch B reads config Y. (path assumed)`. + If the user provided a title, use it. Otherwise, infer a concise title (3-6 words) from the work being done. @@ -170,7 +190,7 @@ files_modified: ### Remaining Work -{Numbered list of concrete next steps, in priority order} +{Numbered list of concrete next steps, in priority order. Each item starts with `Open.` and ends with its provenance marker from Step 2, or no marker under rule 3.} ### Notes diff --git a/test/context-remaining-work-provenance.test.ts b/test/context-remaining-work-provenance.test.ts new file mode 100644 index 00000000000..0fc423fe2c9 --- /dev/null +++ b/test/context-remaining-work-provenance.test.ts @@ -0,0 +1,63 @@ +/** + * Remaining Work provenance (#3004): prompt-byte contract for the shipped + * context-save and context-restore SKILL.md files. + * + * The markers are a wire format between two skills: /context-save writes them + * into a checkpoint and a later /context-restore sorts on them. Only that + * contract is pinned (marker tokens, group headings, banner, option-A order), + * not the surrounding prose. Behavior is covered by the periodic E2E case + * context-restore-provenance-order. + * + * Value: protects=save writes the five provenance markers and restore sorts them into Next steps and Verify first; fails_when=a marker, a group or the saved-order option A is dropped; why_new=no test reads Remaining Work; seam=none + */ +import { describe, test, expect } from 'bun:test'; +import * as fs from 'fs'; +import * as path from 'path'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const MARKERS = ['(path run)', '(path read)', '(path assumed)', '(code read)', '(target state checked)']; + +function read(rel: string): string { + return fs.readFileSync(path.join(ROOT, rel), 'utf-8'); +} + +function between(text: string, start: string, end: string): string { + const from = text.indexOf(start); + expect(from, `missing ${start}`).toBeGreaterThanOrEqual(0); + const to = text.indexOf(end, from + start.length); + expect(to, `missing ${end} after ${start}`).toBeGreaterThan(from); + return text.slice(from, to); +} + +describe('Remaining Work provenance contract', () => { + test('context-save marks every item Open. and defines all five markers, writing steps first', () => { + const save = read('context-save/SKILL.md'); + const table = between(save, '**Remaining Work provenance.**', 'If the user provided a title'); + for (const marker of MARKERS) expect(table).toContain(`\`${marker}\``); + expect(table).toContain('`Open.`'); + expect(table).toContain('`[done]`'); + expect(table.indexOf('a writing step')).toBeLessThan(table.indexOf('names a concrete path')); + const format = between(save, '### Remaining Work', '### Notes'); + expect(format).toContain('`Open.`'); + }); + + test('context-restore sorts into Next steps and Verify first and option A walks saved order', () => { + const restore = read('context-restore/SKILL.md'); + expect(restore).not.toContain('{remaining work items}'); + const rules = between(restore, '**Sort Remaining Work by provenance.**', 'Read the chosen file'); + const verifyFirst = between(rules, 'Put an item under **Verify first**', 'Every other item'); + for (const marker of ['(path assumed)', '(code read)']) expect(verifyFirst).toContain(`\`${marker}\``); + expect(verifyFirst).toContain('reports a failure'); + expect(verifyFirst).toContain('has no marker'); + const nextSteps = between(rules, 'Every other item goes under **Next steps**', 'Verifying means'); + for (const marker of ['(path run)', '(path read)', '(target state checked)']) expect(nextSteps).toContain(`\`${marker}\``); + expect(rules).toContain( + '`This checkpoint predates provenance markers; items naming commands, paths or writes are listed under Verify first.`', + ); + const summary = between(restore, '### Remaining Work', '### Notes'); + expect(summary.indexOf('Next steps')).toBeLessThan(summary.indexOf('Verify first')); + const optionA = between(restore, 'If A,', '## If no saved contexts exist'); + expect(optionA).toContain('first Remaining Work item in saved order'); + expect(optionA).toContain('under Verify first, suggest verifying it'); + }); +}); diff --git a/test/helpers/touchfiles-data.ts b/test/helpers/touchfiles-data.ts index d1c3d3ac72c..3d11db80863 100644 --- a/test/helpers/touchfiles-data.ts +++ b/test/helpers/touchfiles-data.ts @@ -655,6 +655,7 @@ export const E2E_TOUCHFILES: Record = { 'context-save-routing': [ 'context-save/**', 'scripts/resolvers/preamble.ts', 'test/skill-e2e-context-skills.test.ts', 'bin/gstack-skill-start', 'test/helpers/shipped-skill-routing.ts'], 'context-save-then-restore-roundtrip': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'context-save/**', 'context-restore/**', 'bin/gstack-slug', 'bin/gstack-remote-identity.sh', 'test/skill-e2e-context-skills.test.ts', 'bin/gstack-skill-start', 'test/helpers/shipped-skill-routing.ts'], 'context-restore-fragment-match': [ 'context-restore/**', 'test/skill-e2e-context-skills.test.ts', 'bin/gstack-skill-start', 'test/helpers/shipped-skill-routing.ts'], + 'context-restore-provenance-order': ['context-save/**', 'context-restore/**', 'test/skill-e2e-context-skills.test.ts', 'bin/gstack-skill-start', 'test/helpers/shipped-skill-routing.ts'], 'context-restore-empty-state': [ 'context-restore/**', 'test/skill-e2e-context-skills.test.ts', 'bin/gstack-skill-start', 'test/helpers/shipped-skill-routing.ts'], 'context-restore-list-delegates': [ 'context-restore/**', 'test/skill-e2e-context-skills.test.ts', 'bin/gstack-skill-start', 'test/helpers/shipped-skill-routing.ts'], 'context-restore-legacy-compat': [ 'context-restore/**', 'test/skill-e2e-context-skills.test.ts', 'bin/gstack-skill-start', 'test/helpers/shipped-skill-routing.ts'], @@ -1287,6 +1288,7 @@ export const E2E_TIERS: Record = { 'context-save-routing': 'periodic', // Proves /context-save routes via Skill tool 'context-save-then-restore-roundtrip': 'periodic', // Full cycle in one session 'context-restore-fragment-match': 'periodic', // /context-restore + 'context-restore-provenance-order': 'periodic', // #3004 Next steps / Verify first, 3-trial panel 'context-restore-empty-state': 'periodic', // Graceful zero-saves message 'context-restore-list-delegates': 'periodic', // /context-restore list redirect 'context-restore-legacy-compat': 'periodic', // Pre-rename files still load @@ -1664,6 +1666,7 @@ export const E2E_KINDS: Record = { 'context-save-routing': 'rule', 'context-save-then-restore-roundtrip': 'rule', 'context-restore-fragment-match': 'rule', + 'context-restore-provenance-order': 'behavior', 'context-restore-empty-state': 'rule', 'context-restore-list-delegates': 'rule', 'context-restore-legacy-compat': 'rule', @@ -1787,6 +1790,8 @@ export const E2E_KINDS: Record = { export const BEHAVIOR_WHY: Record = { 'shared-libs-opportunity-judgment': "Whether a candidate extraction is worth recommending is a judgment call; the read-only invariant stays a contract.", + 'context-restore-provenance-order': + "How the live model lays out the two Remaining Work groups can drift run to run; never executing a seeded step and never leapfrogging the unverified first item stay contracts.", 'review-design-lite': "How many of the seven design-lite checklist items the live review flags varies run to run; the fake-engine rows it must carry stay strict.", 'review-army-red-team': diff --git a/test/skill-e2e-context-skills.test.ts b/test/skill-e2e-context-skills.test.ts index 71fabe0dabc..31f214505f3 100644 --- a/test/skill-e2e-context-skills.test.ts +++ b/test/skill-e2e-context-skills.test.ts @@ -14,6 +14,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; import { JUDGE_MS, CAPTURE_MS } from './helpers/eval-budgets'; import { runSkillTest } from './helpers/session-runner'; +import { expectContract } from './helpers/eval-store'; import { ROOT, runId, evalsEnabled, describeIfSelected, testConcurrentIfSelected, @@ -136,6 +137,7 @@ describeIfSelected('Context Skills E2E (live-fire)', [ 'context-save-routing', 'context-save-then-restore-roundtrip', 'context-restore-fragment-match', + 'context-restore-provenance-order', 'context-restore-empty-state', 'context-restore-list-delegates', 'context-restore-legacy-compat', @@ -277,6 +279,73 @@ Do NOT use AskUserQuestion.`, try { fs.rmSync(workDir, { recursive: true, force: true }); } catch {} }, CAPTURE_MS); + // ── 3b. Provenance (#3004): guessed and code-read steps are Verify first ── + // The checkpoint ranks an assumed step first, then a step that was run, then + // a write whose target was never inspected. Restore must show the run step + // under Next steps, the other two under Verify first, and option A must + // verify the first item instead of leapfrogging to the runnable one. + testConcurrentIfSelected('context-restore-provenance-order', async () => { + const { workDir, gstackHome, slug } = setupWorkdir('provenance'); + seedSave(gstackHome, slug, '20260404-120000-billing-migration.md', + { status: 'in-progress', branch: 'main', timestamp: '2026-04-04T12:00:00Z' }, + [ + '## Working on: billing migration', + '', + '### Summary', + 'Moving invoices to the new billing schema.', + '', + '### Remaining Work', + '1. Open. Run the migration check with SWITCH_B=1 against staging, PROV_ASSUMED_7Q. (path assumed)', + '2. Open. Run bun test test/billing.test.ts, PROV_RUN_4K. (path run) exit 0', + '3. Open. Apply scripts/backfill.sql (INSERT IGNORE into invoices), PROV_WRITE_9Z. (code read)', + '', + '### Notes', + 'None.', + '', + ].join('\n')); + + const result = await runSkillTest({ + prompt: `Run /context-restore. Invoke via the Skill tool and present its summary. Do NOT use AskUserQuestion: assume the user picks A (continue working). Do not execute or edit anything. End your reply with exactly one line \`FIRST_ACTION: \`.`, + workingDirectory: workDir, + env: { GSTACK_HOME: gstackHome }, + maxTurns: 10, + allowedTools: ['Skill', 'Bash', 'Read', 'Grep', 'Glob'], + timeout: JUDGE_MS, + testName: 'context-restore-provenance-order', + runId, + }); + + logCost('context-restore-provenance-order', result); + + const out = result.output || ''; + const base = Math.max(0, out.indexOf('Remaining Work')); + const next = out.indexOf('Next steps', base); + const verify = next >= 0 ? out.indexOf('Verify first', next) : -1; + const pos = (token: string) => out.indexOf(token, base); + const grouped = next >= 0 && verify > next + && pos('PROV_RUN_4K') > next && pos('PROV_RUN_4K') < verify + && pos('PROV_ASSUMED_7Q') > verify && pos('PROV_WRITE_9Z') > verify; + const firstAction = out.match(/FIRST_ACTION:\s*(verify|do)\s+(PROV_\w+)/i); + const ranSeeded = (result.toolCalls || []).some((tc) => tc.tool === 'Bash' + && /SWITCH_B=1|backfill\.sql|billing\.test/.test(JSON.stringify(tc.input || {}))); + const exitOk = ['success', 'error_max_turns'].includes(result.exitReason); + const name = 'context-restore provenance order'; + + expectContract(!ranSeeded, 'context-restore-provenance-order: restore executed a seeded Remaining Work command', { collector: evalCollector, name }); + expectContract(!(firstAction && firstAction[2] !== 'PROV_ASSUMED_7Q' && /do/i.test(firstAction[1])), + 'context-restore-provenance-order: option A jumped past the unverified first item to execute a later one', { collector: evalCollector, name }); + + const startsByVerifying = !!firstAction && /verify/i.test(firstAction[1]) && firstAction[2] === 'PROV_ASSUMED_7Q'; + recordE2E(evalCollector, name, 'Context Skills E2E', result, { + passed: exitOk && grouped && startsByVerifying, + }); + + expect(exitOk).toBe(true); + expect(grouped).toBe(true); + expect(startsByVerifying).toBe(true); + try { fs.rmSync(workDir, { recursive: true, force: true }); } catch {} + }, CAPTURE_MS); + // ── 4. /context-restore with zero saves → graceful empty-state ─────── testConcurrentIfSelected('context-restore-empty-state', async () => { const { workDir, gstackHome, slug } = setupWorkdir('empty'); From 2ad0e34d1c5a2be3c7f3431679f5d0680dd64da8 Mon Sep 17 00:00:00 2001 From: garrytan Date: Sat, 3 Oct 2026 20:00:21 +0000 Subject: [PATCH 2/6] fix(design): never overwrite a paid design image (#1529) Every image the API returns now goes through one persistence path (design/src/persist.ts): mkdir, exclusive `wx` claim that bumps x.png -> x-2.png ... x-999.png, write, fsync, close. A failure after the bytes arrived removes the claimed file and keeps a 0600 recovery copy in the temp dir; empty image data is a failure, never a 0-byte PNG. The API call is the only thing inside each retry loop, so a local save failure never buys a second image (variants, iterate fallback, generate --retry). generate, iterate, evolve and variants (both branches) print the same run fields (requested, saved, selected, failures, recovered) on every exit, with exit 0 / 2 (nothing saved) / 3 (stopped after saving). Each generate --retry attempt is its own saved image listed in `attempts`. compare accepts --images-file and JSON-array --images. The gallery lists bumped names, orders history by mtime then board-images.json, and marks approvals by approved_path. New bin/gstack-design-claim publishes staged images without clobbering; bin/gstack-design-approved resolves an approval record (legacy letter-only records still resolve; a missing approved_path is an error, never a substitute). Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> --- bin/gstack-design-approved | 24 ++ bin/gstack-design-claim | 55 +++++ design/src/approval.ts | 56 +++++ design/src/auth.ts | 19 +- design/src/cli.ts | 65 ++---- design/src/commands.ts | 41 +++- design/src/evolve.ts | 107 +++++---- design/src/gallery.ts | 43 +++- design/src/generate.ts | 128 ++++++----- design/src/image-args.ts | 53 +++++ design/src/iterate.ts | 103 ++++----- design/src/persist.ts | 196 ++++++++++++++++ design/src/variants.ts | 341 ++++++++++++++++------------ design/test/approval.test.ts | 61 +++++ design/test/cli-persistence.test.ts | 223 ++++++++++++++++++ design/test/gallery.test.ts | 36 ++- design/test/image-args.test.ts | 52 +++++ design/test/models.test.ts | 16 +- design/test/persist.test.ts | 165 ++++++++++++++ test/gstack-design-claim.test.ts | 118 ++++++++++ 20 files changed, 1530 insertions(+), 372 deletions(-) create mode 100755 bin/gstack-design-approved create mode 100755 bin/gstack-design-claim create mode 100644 design/src/approval.ts create mode 100644 design/src/image-args.ts create mode 100644 design/src/persist.ts create mode 100644 design/test/approval.test.ts create mode 100644 design/test/cli-persistence.test.ts create mode 100644 design/test/image-args.test.ts create mode 100644 design/test/persist.test.ts create mode 100644 test/gstack-design-claim.test.ts diff --git a/bin/gstack-design-approved b/bin/gstack-design-approved new file mode 100755 index 00000000000..7c3f360a218 --- /dev/null +++ b/bin/gstack-design-approved @@ -0,0 +1,24 @@ +#!/usr/bin/env bun +// gstack-design-approved — print the absolute path of the image an +// approved.json names. +// +// Usage: gstack-design-approved +// +// Prefers approved_path (relative to approved.json's directory). Legacy +// records with only approved_variant resolve to variant-.png. When the +// named image is missing, exits 1 with "approved image is missing; +// reselect from the board" and never substitutes another image. + +import { resolveApprovedImage } from '../design/src/approval'; + +const file = process.argv[2]; +if (!file) { + console.error('Usage: gstack-design-approved '); + process.exit(1); +} +const resolved = resolveApprovedImage(file); +if (!resolved.ok) { + console.error(resolved.error); + process.exit(1); +} +console.log(resolved.path); diff --git a/bin/gstack-design-claim b/bin/gstack-design-claim new file mode 100755 index 00000000000..88a8c9f1f25 --- /dev/null +++ b/bin/gstack-design-claim @@ -0,0 +1,55 @@ +#!/bin/sh +# gstack-design-claim — publish a staged design image without overwriting. +# +# Usage: gstack-design-claim +# +# Creates with an exclusive, non-overwriting create (set -C +# noclobber, which opens with O_EXCL). When the name is taken it tries +# -2, -3 ... -999, the same rule as +# $D's claimOutputPath (x-2.png bumps to x-2-2.png). Prints the final path. +# On any failure it exits non-zero with problem/cause/fix and leaves the staged +# image in place, so the paid bytes survive. On success the staged copy is +# removed. + +set -u + +fail() { + printf 'gstack-design-claim: %s\ncause: %s\nfix: %s\n' "$1" "$2" "$3" >&2 + exit 1 +} + +[ "$#" -eq 2 ] || fail "expected 2 arguments, got $#" "usage: gstack-design-claim " "pass the staged image path, then the destination path" +src=$1 +dest=$2 + +[ -f "$src" ] && [ -s "$src" ] || fail "staged image $src is missing or empty" "the generating command did not save an image there" "use the outputPath the \$D command printed" + +dir=$(dirname "$dest") +base=$(basename "$dest") +case "$base" in + ?*.*) stem=${base%.*}; ext=".${base##*.}" ;; + *) stem=$base; ext="" ;; +esac + +err=$(mkdir -p "$dir" 2>&1) || fail "cannot create $dir; staged image kept at $src" "$err" "make $dir writable or choose another destination" + +n=1 +candidate=$dest +while :; do + if err=$( (set -C; : > "$candidate") 2>&1 ); then + if err=$(cat "$src" 2>&1 > "$candidate"); then + rm -f "$src" + printf '%s\n' "$candidate" + exit 0 + fi + rm -f "$candidate" + fail "cannot write $candidate; staged image kept at $src" "$err" "free disk space or make $dir writable, then rerun" + fi + if [ -e "$candidate" ] || [ -L "$candidate" ]; then + n=$((n + 1)) + [ "$n" -le 999 ] || fail "$dest and every name through $stem-999$ext already exist; staged image kept at $src" "999 images already use this name" "choose a new destination name or move older images out of $dir" + candidate="$dir/$stem-$n$ext" + continue + fi + fail "cannot create $candidate; staged image kept at $src" "$err" "make $dir writable or choose another destination" +done diff --git a/design/src/approval.ts b/design/src/approval.ts new file mode 100644 index 00000000000..400015439df --- /dev/null +++ b/design/src/approval.ts @@ -0,0 +1,56 @@ +/** + * Resolve the image an approval record names. `approved_path` is stored + * relative to the directory holding approved.json, so a copied or relocated + * designs directory still resolves. Records without `approved_path` (written + * before never-overwrite) fall back to `variant-.png`. A + * present `approved_path` whose file is missing is an error: another image is + * never substituted. + */ + +import fs from "fs"; +import path from "path"; + +export type ApprovedImage = { ok: true; path: string; legacy: boolean } | { ok: false; error: string }; + +export interface ApprovalRecord { + approved_variant?: unknown; + approved_path?: unknown; +} + +function missing(imagePath: string): ApprovedImage { + return { ok: false, error: `approved image ${imagePath} is missing; reselect from the board` }; +} + +function readable(imagePath: string): boolean { + try { + fs.accessSync(imagePath, fs.constants.R_OK); + return fs.statSync(imagePath).isFile(); + } catch { + return false; + } +} + +/** The image path a record names, without checking that it exists. */ +export function approvedImagePath(record: ApprovalRecord, recordDir: string): { path: string; legacy: boolean } | null { + if (typeof record.approved_path === "string" && record.approved_path !== "") { + return { path: path.resolve(recordDir, record.approved_path), legacy: false }; + } + if (typeof record.approved_variant === "string" && record.approved_variant !== "") { + return { path: path.join(recordDir, `variant-${record.approved_variant}.png`), legacy: true }; + } + return null; +} + +export function resolveApprovedImage(approvedJsonPath: string): ApprovedImage { + let record: ApprovalRecord; + try { + record = JSON.parse(fs.readFileSync(approvedJsonPath, "utf-8")); + } catch (err: any) { + return { ok: false, error: `cannot read ${approvedJsonPath}: ${err.code || err.message}` }; + } + const named = approvedImagePath(record ?? {}, path.dirname(path.resolve(approvedJsonPath))); + if (!named) { + return { ok: false, error: `${approvedJsonPath} names no approved image; reselect from the board` }; + } + return readable(named.path) ? { ok: true, ...named } : missing(named.path); +} diff --git a/design/src/auth.ts b/design/src/auth.ts index 1202500a919..fc25cbcf4ea 100644 --- a/design/src/auth.ts +++ b/design/src/auth.ts @@ -119,19 +119,20 @@ export function saveApiKey(key: string): void { } /** - * Get API key or exit with setup instructions. + * Get API key or throw with setup instructions. */ export function requireApiKey(): string { const resolution = resolveApiKeyInfo(); if (!resolution) { - console.error("No OpenAI API key found."); - console.error(""); - console.error("Run: $D setup"); - console.error(" or save to ~/.gstack/openai.json: { \"api_key\": \"sk-...\" }"); - console.error(" or set OPENAI_API_KEY environment variable"); - console.error(""); - console.error("Get a key at: https://platform.openai.com/api-keys"); - process.exit(1); + throw new Error([ + "No OpenAI API key found.", + "", + "Run: $D setup", + " or save to ~/.gstack/openai.json: { \"api_key\": \"sk-...\" }", + " or set OPENAI_API_KEY environment variable", + "", + "Get a key at: https://platform.openai.com/api-keys", + ].join("\n")); } console.error(`Using OpenAI key from ${describeApiKeySource(resolution)}.`); if (resolution.warning) console.error(resolution.warning); diff --git a/design/src/cli.ts b/design/src/cli.ts index b266c6f385e..2278b9a6547 100644 --- a/design/src/cli.ts +++ b/design/src/cli.ts @@ -12,7 +12,7 @@ * 4. Print result JSON to stdout */ -import { COMMANDS } from "./commands"; +import { COMMANDS, OUTPUT_CONTRACT } from "./commands"; import { generate } from "./generate"; import { checkCommand } from "./check"; import { compare } from "./compare"; @@ -26,6 +26,7 @@ import { generateDesignToCodePrompt } from "./design-to-code"; import { serve } from "./serve"; import { gallery } from "./gallery"; import { normalizeIntFlag } from "./flag-utils"; +import { resolveImagePaths } from "./image-args"; import { daemonStatus as daemonStatusClient, ensureDaemon, @@ -33,6 +34,9 @@ import { shutdownDaemon, } from "./daemon-client"; import { spawn as nodeSpawn } from "child_process"; +import fs from "fs"; +import os from "os"; +import path from "path"; function parseArgs(argv: string[]): { command: string; @@ -75,6 +79,7 @@ function printUsage(): void { console.log(` ${name.padEnd(12)} ${info.description}`); console.log(` ${"".padEnd(12)} ${info.usage}`); } + console.log(`\n${OUTPUT_CONTRACT}`); console.log("\nAuth: ~/.gstack/openai.json, then OPENAI_API_KEY env var"); console.log("If OPENAI_API_KEY matches a current-directory .env file, the source is reported before billing."); console.log("Setup: $D setup"); @@ -107,19 +112,18 @@ async function runSetup(): Promise { // Smoke test console.log("\nRunning smoke test (generating a simple image)..."); - try { - await generate({ - brief: "A simple blue square centered on a white background. Minimal, geometric, clean.", - output: "/tmp/gstack-design-smoke-test.png", - size: "1024x1024", - quality: "low", - }); - console.log("\nSmoke test PASSED. Design generation is working."); - } catch (err: any) { - console.error(`\nSmoke test FAILED: ${err.message}`); + const smoke = await generate({ + brief: "A simple blue square centered on a white background. Minimal, geometric, clean.", + output: path.join(fs.mkdtempSync(path.join(os.tmpdir(), "gstack-design-smoke-")), "smoke-test.png"), + size: "1024x1024", + quality: "low", + }); + if (smoke.exitCode !== 0) { + console.error(`\nSmoke test FAILED: ${smoke.failures.map(f => f.reason).join("; ")}`); console.error("Check your API key and organization verification status."); process.exit(1); } + console.log("\nSmoke test PASSED. Design generation is working."); } async function main(): Promise { @@ -133,7 +137,7 @@ async function main(): Promise { switch (command) { case "generate": - await generate({ + process.exitCode = (await generate({ brief: flags.brief as string, briefFile: flags["brief-file"] as string, output: (flags.output as string) || "/tmp/gstack-mockup.png", @@ -141,7 +145,7 @@ async function main(): Promise { retry: normalizeIntFlag(flags.retry, { name: "retry", def: 0, min: 0 }), size: flags.size as string, quality: flags.quality as string, - }); + })).exitCode; break; case "check": @@ -149,9 +153,7 @@ async function main(): Promise { break; case "compare": { - // Parse --images as glob or multiple files - const imagesArg = flags.images as string; - const images = await resolveImagePaths(imagesArg); + const images = await resolveImagePaths(flags.images as string, flags["images-file"] as string | undefined); const outputPath = (flags.output as string) || "/tmp/gstack-design-board.html"; compare({ images, output: outputPath }); // If --serve flag is set, publish the board. @@ -195,7 +197,7 @@ async function main(): Promise { break; case "variants": - await variants({ + process.exitCode = await variants({ brief: flags.brief as string, briefFile: flags["brief-file"] as string, // #2032: pass the RAW flag through — variants() normalizes at its @@ -209,7 +211,7 @@ async function main(): Promise { break; case "iterate": - await iterate({ + process.exitCode = await iterate({ session: flags.session as string, feedback: flags.feedback as string, output: (flags.output as string) || "/tmp/gstack-iterate.png", @@ -261,7 +263,7 @@ async function main(): Promise { } case "evolve": - await evolve({ + process.exitCode = await evolve({ screenshot: flags.screenshot as string, brief: flags.brief as string, output: (flags.output as string) || "/tmp/gstack-evolved.png", @@ -381,31 +383,6 @@ function openBrowser(url: string): void { } } -/** - * Resolve image paths from a glob pattern or comma-separated list. - */ -async function resolveImagePaths(input: string): Promise { - if (!input) { - console.error("--images is required. Provide glob pattern or comma-separated paths."); - process.exit(1); - } - - // Check if it's a glob pattern - if (input.includes("*")) { - const glob = new Bun.Glob(input); - const paths: string[] = []; - for await (const match of glob.scan({ absolute: true })) { - if (match.endsWith(".png") || match.endsWith(".jpg") || match.endsWith(".jpeg")) { - paths.push(match); - } - } - return paths.sort(); - } - - // Comma-separated or single path - return input.split(",").map(p => p.trim()); -} - // Self-execution shortcut: when invoked with --daemon-mode, this same // binary runs as the persistent design daemon instead of the CLI. Keeps // the production install to a single executable; daemon-client.ts spawns diff --git a/design/src/commands.ts b/design/src/commands.ts index 17d5811a763..76ff9ded794 100644 --- a/design/src/commands.ts +++ b/design/src/commands.ts @@ -16,17 +16,17 @@ export const COMMANDS = new Map([ ["generate", { description: "Generate a UI mockup from a design brief", - usage: "generate --brief \"...\" --output /path.png", + usage: "generate --brief \"...\" --output /path.png [--check --retry N] (never overwrites: bumps to /path-2.png; each --retry attempt is its own saved image; prints outputPath, attempts + run fields)", flags: ["--brief", "--brief-file", "--output", "--check", "--retry", "--size", "--quality"], }], ["variants", { description: "Generate N design variants from a brief", - usage: "variants --brief \"...\" --count 3 --output-dir /path/", + usage: "variants --brief \"...\" --count 3 --output-dir /path/ [--viewports desktop,tablet,mobile] (never overwrites: variant-A.png bumps to variant-A-2.png; prints paths, errors + run fields)", flags: ["--brief", "--brief-file", "--count", "--output-dir", "--size", "--quality", "--viewports"], }], ["iterate", { description: "Iterate on an existing mockup with feedback", - usage: "iterate --session /path/session.json --feedback \"...\" --output /path.png", + usage: "iterate --session /path/session.json --feedback \"...\" --output /path.png (never overwrites; prints outputPath + run fields)", flags: ["--session", "--feedback", "--output"], }], ["check", { @@ -36,8 +36,8 @@ export const COMMANDS = new Map x-2.png, x-2.png -> x-2-2.png), stderr prints +"note: exists; saved to (existing file kept)", and the JSON +reports the actual path. Read paths from the JSON, never from a fixed file name. + +Run fields printed by generate, iterate, evolve and variants (on every exit): + requested images requested saved every saved path, in order + selected outputPath or paths failures [{file, reason}] not saved + recovered [{path, reason}] private recovery copies in the temp dir + + command extra fields readers + generate outputPath sessionFile responseId checkResult design-review, design-shotgun, + attempts[{path, check}] (one per --retry try) plan-design-review + iterate outputPath sessionFile responseId iteration plan-design-review, design-consultation + evolve outputPath sourceScreenshot brief attempts design-shotgun + variants outputDir count succeeded failed paths errors office-hours, plan-design-review, + viewports (--viewports only) design-consultation + compare board HTML; --serve prints {id, url, sourceDir} all board flows (--images-file) + +Exit codes: 0 a selected result exists; 2 nothing was saved; 3 stopped after +saving at least one image but before its selected result (interrupted retry); +1 invalid flags rejected before any API call (no JSON).`; diff --git a/design/src/evolve.ts b/design/src/evolve.ts index a656054b03a..69b48684916 100644 --- a/design/src/evolve.ts +++ b/design/src/evolve.ts @@ -6,10 +6,10 @@ */ import fs from "fs"; -import path from "path"; import { requireApiKey } from "./auth"; import { receiptedFetch } from "./receipted-fetch"; import { imageRequestBody, modelRejectionHint, visionRequestBody } from "./models"; +import { emitResult, exitCodeFor, newAccounting, persistImage, recordOutcome, type ExitCode } from "./persist"; export interface EvolveOptions { screenshot: string; // Path to current site screenshot @@ -22,37 +22,68 @@ export interface EvolveOptions { * Sends the screenshot as context to the image model with image generation, * asking it to produce a new version incorporating the brief's changes. */ -export async function evolve(options: EvolveOptions): Promise { - const apiKey = requireApiKey(); - const screenshotData = fs.readFileSync(options.screenshot).toString("base64"); - - console.error(`Evolving ${options.screenshot} with: "${options.brief}"`); - const startTime = Date.now(); - - // Use the Responses API with both a text prompt referencing the screenshot - // and the image_generation tool to produce the evolved version. - // Since we can't send reference images directly to image_generation, - // we describe the current state in detail first via vision, then generate. - - // Step 1: Analyze current screenshot - const analysis = await analyzeScreenshot(apiKey, screenshotData); - console.error(` Analyzed current design: ${analysis.slice(0, 100)}...`); - - // Step 2: Generate evolved version using analysis + brief - const evolvedPrompt = [ - "Generate a pixel-perfect UI mockup that is an improved version of an existing design.", - "", - "CURRENT DESIGN (what exists now):", - analysis, - "", - "REQUESTED CHANGES:", - options.brief, - "", - "Generate a new mockup that keeps the existing layout structure but applies the requested changes.", - "The result should look like a real production UI. All text must be readable.", - "1536x1024 pixels.", - ].join("\n"); +export async function evolve(options: EvolveOptions): Promise { + const acct = newAccounting(1); + let outputPath: string | null = null; + try { + const apiKey = requireApiKey(); + const screenshotData = fs.readFileSync(options.screenshot).toString("base64"); + + console.error(`Evolving ${options.screenshot} with: "${options.brief}"`); + const startTime = Date.now(); + + // Use the Responses API with both a text prompt referencing the screenshot + // and the image_generation tool to produce the evolved version. + // Since we can't send reference images directly to image_generation, + // we describe the current state in detail first via vision, then generate. + + // Step 1: Analyze current screenshot + const analysis = await analyzeScreenshot(apiKey, screenshotData); + console.error(` Analyzed current design: ${analysis.slice(0, 100)}...`); + + // Step 2: Generate evolved version using analysis + brief + const evolvedPrompt = [ + "Generate a pixel-perfect UI mockup that is an improved version of an existing design.", + "", + "CURRENT DESIGN (what exists now):", + analysis, + "", + "REQUESTED CHANGES:", + options.brief, + "", + "Generate a new mockup that keeps the existing layout structure but applies the requested changes.", + "The result should look like a real production UI. All text must be readable.", + "1536x1024 pixels.", + ].join("\n"); + + const imageData = await requestEvolvedImage(apiKey, evolvedPrompt); + const outcome = persistImage(imageData, options.output); + outputPath = recordOutcome(acct, outcome); + if (outcome.ok) { + const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); + console.error(`Generated (${elapsed}s, ${(outcome.bytes / 1024).toFixed(0)}KB) → ${outcome.path}`); + } + } catch (err: any) { + const reason = err?.message || String(err); + console.error(reason); + acct.failures.push({ file: options.output, reason }); + } + + return emitResult({ + outputPath, + sourceScreenshot: options.screenshot, + brief: options.brief, + attempts: acct.saved.map(p => ({ path: p })), + requested: acct.requested, + saved: acct.saved, + selected: outputPath, + failures: acct.failures, + recovered: acct.recovered, + }, exitCodeFor(outputPath !== null, acct.saved.length)); +} + +async function requestEvolvedImage(apiKey: string, evolvedPrompt: string): Promise { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 240_000); @@ -85,19 +116,7 @@ export async function evolve(options: EvolveOptions): Promise { if (!imageItem?.result) { throw new Error("No image data in response"); } - - fs.mkdirSync(path.dirname(options.output), { recursive: true }); - const imageBuffer = Buffer.from(imageItem.result, "base64"); - fs.writeFileSync(options.output, imageBuffer); - - const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); - console.error(`Generated (${elapsed}s, ${(imageBuffer.length / 1024).toFixed(0)}KB) → ${options.output}`); - - console.log(JSON.stringify({ - outputPath: options.output, - sourceScreenshot: options.screenshot, - brief: options.brief, - }, null, 2)); + return imageItem.result; } finally { clearTimeout(timeout); } diff --git a/design/src/gallery.ts b/design/src/gallery.ts index 95675559d56..5ab08a48661 100644 --- a/design/src/gallery.ts +++ b/design/src/gallery.ts @@ -6,6 +6,7 @@ import fs from "fs"; import path from "path"; +import { approvedImagePath } from "./approval"; export interface GalleryOptions { designsDir: string; // ~/.gstack/projects/$SLUG/designs/ @@ -20,6 +21,32 @@ interface SessionData { variants: string[]; // paths to variant PNGs } +const VARIANT_IMAGE = [/^variant-[A-Z](-\d+)?\.png$/i, /^variant-\d+(-\d+)?\.png$/i]; + +/** + * Variant images in a session directory as chronological history, not rounds: + * names not on the current board sort by mtime then name, followed by the + * board's images in board-images.json order. Never-overwrite means one + * letter can appear in several rounds (variant-A.png, variant-A-2.png). + */ +export function listVariantImages(sessionDir: string): string[] { + const found = fs.readdirSync(sessionDir) + .filter(f => VARIANT_IMAGE.some(re => re.test(f))) + .map(f => path.join(sessionDir, f)); + + let board: string[] = []; + try { + const parsed = JSON.parse(fs.readFileSync(path.join(sessionDir, "board-images.json"), "utf-8")); + if (Array.isArray(parsed)) board = parsed.filter((p): p is string => typeof p === "string").map(p => path.resolve(sessionDir, p)); + } catch {} + + const mtime = new Map(found.map(f => [f, fs.statSync(f).mtimeMs])); + const history = found + .filter(f => !board.includes(f)) + .sort((a, b) => (mtime.get(a)! - mtime.get(b)!) || a.localeCompare(b)); + return [...history, ...board.filter(f => found.includes(f))]; +} + export function generateGalleryHtml(designsDir: string): string { const sessions: SessionData[] = []; @@ -44,16 +71,9 @@ export function generateGalleryHtml(designsDir: string): string { } } - // Find variant PNGs - const variants: string[] = []; + let variants: string[] = []; try { - const files = fs.readdirSync(sessionDir); - for (const f of files) { - if (f.match(/variant-[A-Z]\.png$/i) || f.match(/variant-\d+\.png$/i)) { - variants.push(path.join(sessionDir, f)); - } - } - variants.sort(); + variants = listVariantImages(sessionDir); } catch { // Can't read directory, skip } @@ -81,12 +101,13 @@ export function generateGalleryHtml(designsDir: string): string { sessions.sort((a, b) => b.date.localeCompare(a.date)); const sessionCards = sessions.map(session => { + const approvedTarget = session.approved ? approvedImagePath(session.approved, session.dir) : null; const variantImgs = session.variants.map((vPath, i) => { try { const imgData = fs.readFileSync(vPath).toString("base64"); const ext = path.extname(vPath).slice(1) || "png"; const label = path.basename(vPath, `.${ext}`).replace("variant-", ""); - const isApproved = session.approved?.approved_variant === label; + const isApproved = approvedTarget?.path === vPath; return `