Skip to content

feat(generate): add civitai generate and civitai workflows - #210

Merged
ZacxDev merged 15 commits into
mainfrom
feat/generate
Aug 6, 2026
Merged

ZacxDev merged 15 commits into
mainfrom
feat/generate

Conversation

@ZacxDev

@ZacxDev ZacxDev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Adds civitai generate — submit a generation, watch it, download the outputs — plus
civitai workflows list|get|cancel. Built in five gated phases; every gate was
re-verified independently rather than accepted from the phase that produced it.

Surface

civitai generate "a cat wearing sunglasses"                   # everything server-defaulted
civitai generate "a cat" --checkpoint 1759168 --lora 250712:0.8 --quantity 4
civitai generate "a cat" --dry-run                            # price it, spend nothing
civitai generate --input graph.json                           # raw graph passthrough
civitai generate "a cat" --print-input > g.json               # graduate flags -> file
civitai workflows list | get <id> | cancel <id>

Five content flags, not twelve. Everything omitted stays reachable via --input, which is
also why the CLI needs no per-engine code.

🔴 The spend story, stated plainly

There is no server-side spend ceiling reachable from a personal API key. The quote is
not binding, realized cost can exceed it with no refund, and the per-API-key
buzzLimit does not bind this path (the orchestrator meters a separate System key, so
a user who sets it is falsely reassured). --max-cost is an estimate check, not a cap;
--timeout stops waiting, not paying. All of that is in --help and the README in
those words, because the failure mode is someone running an unattended loop believing
otherwise.

Defaults are conservative: --dry-run costs nothing, a TTY run confirms, and a non-TTY
run refuses without --yes
so a pipeline can never silently spend.

Why it looks the way it does

The server is permissive, not validating — every one of these was measured live, and
each returns HTTP 200:

Input Server behaviour
steps: 0 accepted; degenerate, half-price, wrong job
unknown key silently dropped; your parameter vanishes
invalid sampler silently ignored
nonexistent model id 200, and you are billed for a substituted model
quantity: 10000 clamped to 10, no error

So the CLI resolves --checkpoint/--lora against /api/v1/model-versions/{id} before
submitting, turning that fourth row into a hard local 404. It is a live lookup, not a
vendored table, so it carries no drift cost.

Three things that look like bugs and are load-bearing (all in AGENTS.md items 11–16):

  • Two different tRPC envelopes. whatIf takes the graph flat; generate takes it
    nested under .input. A mismatch returns 200 with a constant ~8 cost while every
    "did it 200?" test stays green.
  • externalId is minted unconditionally. The server retries submits 3× with no
    idempotency key — its own comment says the caller must supply one — so omitting it risks
    a triple charge.
  • DownloadPresigned carries no credential. isTrustedDownloadHost trusts any
    *.civitai.com host and blobs come from orchestration.civitai.com, so folding this
    back into DownloadFile would send a full-scope personal API key to the orchestrator.

Verification

  • 1786 tests, 1783 pass, 0 fail, 3 skip (all three skips pre-existing/env-gated), gofmt
    and vet clean — run on the merged tree against current origin/main, not just the
    branch.
  • Guards were mutation-tested: each was broken deliberately and shown to fail with its
    own message
    , then reverted. Two guards initially survived and the tests were
    strengthened until they didn't.
  • One real generation at the phase-2 gate: estimated 8 Buzz, charged exactly 8,
    1024×1024 JPEG downloaded with no credential attached, re-attach via workflows get
    confirmed. That single data point does not disprove the overage risk above.

claudedocs/civitai-generate-design.md carries the full trace and an appendix retracting
every design claim that did not survive implementation.

Requires

A personal API key with the AI Services scope. An OAuth civitai login token cannot
generate — the civitai-cli OAuth client lacks the AI scope bits, which needs a
server-side migration to change. civitai whoami already reports the capability.

Known gaps

  • --input is txt2img-only on purpose. The server's prompt audit is gated on
    'prompt' in data, and the validated graph is rebuilt from declared nodes only, so a
    graph carrying its prompt elsewhere could slip the audit. The CLI should not be that
    vector; other workflows are refused with that reason.
  • Silent model substitution within an ecosystem remains undetectable — the tRPC reply
    carries no substitution record (only the App Blocks path does). Worth a server-side ask.
  • No img2img yet.

🤖 Generated with Claude Code

ZacxDev and others added 12 commits August 5, 2026 12:58
…erate` subcommand

Traces the orchestration path in civitai/civitai and proposes a three-layer
surface (bare prompt / five flags / --input graph passthrough).

Core feasibility verified live against civitai.com with a personal API key
(read-only whatIfFromGraph probes; harness validated with positive and
negative controls; Buzz balance unchanged, so nothing was spent):

  - a personal API key DOES authenticate tRPC orchestrator.* calls
  - `ecosystem` is omittable; the graph applies defaults server-side

Records the hazards that adversarial review turned up, each measured rather
than inferred:

  - whatIf and generate take DIFFERENT tRPC envelopes; the mismatch returns
    200 with a bogus default cost, defeating a single-builder dry-run
  - the server retries submits 3x with no idempotency key, so externalId
    must be minted unconditionally by the caller
  - resources[] requires model.type, so --lora needs a version lookup
  - the server is permissive: zero values, unknown keys, bad samplers and
    nonexistent model ids are all accepted silently and billed
  - no server-side spend ceiling is reachable from a personal API key

Includes an appendix retracting the v1 claims that did not survive review.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…yet)

Adds internal/genapi — the transport layer behind a future `civitai generate`.
No cobra command, no polling, no blob download, no --input: this is the wire
plumbing plus the guards that make it safe to build on.

Mirrors internal/appapi's shape (TokenSource seam, authedDo/doOnceWith with
transparent 401 refresh, response-body cap) rather than inventing a second
auth/transport pattern, and adds no dependency: the externalId is a v4 UUID
built from crypto/rand.

Four things carry real money risk and are pinned by tests:

- ONE payload struct, TWO envelope shapes. whatIfFromGraph takes the graph FLAT
  under `json`; generateFromGraph nests it under `json.input`. The mismatch is
  silent — measured against civitai.com, a nested payload sent to whatIf is
  never parsed and prices the default job (total 8) byte-identically to `{}`,
  where the same graph sent flat priced 60. A cost pre-flight in the wrong
  regime would quote a constant while waving through an arbitrarily expensive
  job. Both shapes are asserted by decoding the ACTUAL outgoing bytes into
  map[string]any and checking key POSITION, against a handler that reproduces
  the measured flat-only pricing.

- Unconditional externalId on every submit. The platform retries a submit 3x on
  5xx and on no-response, reusing the same body, and adds no idempotency key of
  its own; the orchestrator dedupes on (userId, externalId). Without one, a
  single user action can be charged three times. It is never sent on a whatIf —
  a matching key there would return the pre-existing workflow and burn it.

- Unset fields are ABSENT from the wire. `steps: 0` is accepted by the server
  and silently prices a degenerate, cheaper, wrong job, so every optional field
  is a pointer with omitempty. Guarded by key-presence checks on map[string]any
  (never strings.Contains — "cfg" substring-matches "cfgScale"), including a
  whole-struct form that fails for any future field added without omitempty,
  plus an explicit-zero test that pins why a pointer and not a value type.

- Model-version resolution via the existing public REST route. resources[]
  entries require model:{type}, which is not derivable from a version id, and a
  WRONG type is silently accepted. The lookup doubles as the substitution
  mitigation: a nonexistent checkpoint id currently returns 200 with the
  ecosystem default billed instead, and this turns it into a hard local 404.
  It is a live round-trip, not a vendored table, so it carries no drift cost.

Errors are classified with civitai.Tag/TagStatus so exit codes are pinned by
errors.Is, never message text. errkind.go maps BOTH 401 and 403 to
ErrUnauthorized, which is wrong for insufficient-Buzz / generation-disabled /
muted-account; this layer classifies faithfully by status and leaves a TODO
pointing at design §7 for the surface phase that owns the exit-code contract.

Tests are hermetic (httptest only — no call ever reaches civitai.com, and the
generate mutation is never sent anywhere real). Each guard was mutation-tested:
swapping either envelope, dropping the externalId, and making Steps a value
type each turned the relevant test red with its own message.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…submit

Phase 1 of the generation surface: the full command shape, --dry-run, the
cost/balance display and confirmation, and submit-then-print-workflowId.
Polling, blob download, --input and img2img are later phases.

Spend safety, which is most of the work here:

  * Every --checkpoint / --lora id is resolved against the public
    model-version API BEFORE submitting. The generator accepts a nonexistent
    checkpoint with HTTP 200, silently substitutes the ecosystem default and
    bills for it; resolving first turns that into a hard local 404. It is also
    required — a resources[] entry needs model:{type}, which is not derivable
    from a version id. The resolved model NAME is echoed in the confirmation so
    the user approves a name, not an integer.
  * --dry-run (and --dry-run --json, raw passthrough) price the job without
    spending. A cost-less or `ready:false` estimate is refused rather than
    submitted.
  * Confirmation mirrors confirmSubmit: --yes bypasses, an interactive TTY
    prompts with cost + balance, and a NON-TTY without --yes is refused rather
    than charged silently.
  * --max-cost is documented everywhere as an ESTIMATE CHECK, NOT A CAP: the
    server returns no binding quote and enforces no ceiling, so the realized
    charge can exceed it with no refund.
  * Exactly five content flags. --steps/--cfg-scale/--sampler are deliberately
    absent (a zero is accepted and prices a cheaper, broken job), and --model is
    absent because `civitai download --model` means a MODEL id, not a version id.

Exit codes: pkg/civitai's statusKind maps both 401 and 403 to ErrUnauthorized
(exit 3), so failures that are not credential problems would send a script round
the `civitai login` loop forever. statusKind is left untouched — changing it
would move every other command's exit code — and the discrimination happens in
classifyGenerateError, which reads the SERVER's message via a new
genapi.APIError rather than the formatted error string (the transport's own 403
advisory enumerates every 403 cause, so matching Error() classifies all of them
identically). Out of Buzz, muted/onboarding, generation disabled and a blocked
prompt each get an errors.Is-assertable sentinel and land on exit 1.

Measured against the platform source, the design doc's §7 table is wrong on two
rows: insufficient Buzz and "generation disabled" are re-thrown as tRPC
BAD_REQUEST and reach the CLI as 400s, not 403s. The real 403 victims are a
muted account and an incomplete onboarding.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two corrections found while implementing phases 0 and 1, both verified against
the server source rather than inferred:

  - insufficient Buzz and "generation disabled" reach the CLI as 400, not 403;
    the orchestrator's 403 is re-thrown as tRPC BAD_REQUEST. The real 403
    misclassification victims are a muted account and incomplete onboarding.
  - the authedDo POST-replay hazard is closed NOW by the unconditional
    externalId, not deferred to the OAuth migration.

Also records the constraint that statusKind must not be changed to fix this:
it is shared by every command, so a new 403 mapping would silently alter exit
codes CLI-wide.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ows get`

Phase 2 of `civitai generate`: the command now waits for the job it paid for,
reports what the workflow actually produced, and writes the results to disk —
plus the read command that makes every early exit recoverable.

Polling
- New `genapi.Client.GetWorkflow` (tRPC `orchestrator.getWorkflow`). Deliberately
  NOT `statusUpdate`: that is an `orchestratorGuardedProcedure`, so a muted user
  could not poll a workflow they had ALREADY PAID FOR, and its projection drops
  the step metadata where the per-output `hidden` flag lives.
- Exponential backoff with a 5s floor that is clamped UP, not merely defaulted,
  and explicit 429 handling that raises the floor for every subsequent poll.
  `getWorkflow` proxies straight through to the orchestrator with no cache and
  no rate limit, so the CLI's own restraint is all that stops a 429 storm.
- All four terminal statuses handled; an UNRECOGNISED status keeps waiting
  rather than fabricating an outcome.

Output handling
- `genapi.Deliverable` ports the site's own predicate verbatim
  (`available && !blockedReason && !hidden`). Excluded outputs are reported WITH
  their reason, and a count that differs from --quantity is called out; a
  workflow whose every output was filtered exits non-zero.
- `hidden` and `seed` are read from the STEP metadata (incl. the legacy `images`
  key), because `getWorkflow` returns the RAW orchestrator workflow, not the
  site's normalized shape where those are blob fields.

Blob download
- Reuses pkg/civitai's downloader — SSRF dial guard, https-per-redirect-hop,
  hop cap, `.part` + atomic rename, degenerate-name rejection.
- 🔴 New `Client.DownloadPresigned` seam fetches with NO credential.
  `isTrustedDownloadHost` matches any *.civitai.com host, so a naive reuse of
  `DownloadFile` would have sent a full-scope 25-permission API key to the
  orchestrator for a URL that is already presigned. The predicate itself is
  untouched — `civitai download` depends on it.

Interrupt safety
- `signal.NotifyContext` over the whole run.
- `{externalId, submittedAt, payloadHash}` written BEFORE the POST; the key is
  minted in the command layer so it can be recorded first. New `--external-id`
  makes the printed re-attach command real (a duplicate key returns 200 with the
  pre-existing workflow — there is no 409).
- --timeout and Ctrl-C print both ids plus the exact re-attach command, and
  return an ERROR: the job keeps running and the charge stands.

New flags: --no-wait, --timeout, --out-dir, --no-download, --force,
--external-id. New command group: `civitai workflows get <id> [--json]`.

Also fixes a pflag `UnquoteUsage` bug found while smoke-testing --help (a
back-quoted command in a bool flag's usage rendered as its VALUE NAME), pinned
by a guard over every flag on both commands.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Phase 3 of `civitai generate`.

--input <file>|- sends a generation graph verbatim, so a caller can reach
parameters the five content flags do not model. genapi.Graph gains a `Raw`
carrier with a MarshalJSON that emits it byte-for-byte: round-tripping the
document through the typed struct would DELETE every key the struct does not
model, which is worse than the server's own silent-drop behaviour because it
happens before the request is built. whatIf still strips prompt/negativePrompt,
by deleting the two keys from the decoded object rather than re-marshalling.

Three guards, in refusal order:

- txt2img ONLY. The server's prompt audit is gated on a top-level `prompt`
  string node and rebuilds what it inspects from DECLARED nodes only, so a graph
  carrying its prompt elsewhere (comfy, a nested step input) is exactly the
  shape that could reach the generator unaudited. That is an OPEN upstream
  question; the CLI must not be the vector while it is open.
- Envelope keys are REFUSED, not stripped: civitaiTip, creatorTip, buzzType,
  tags, externalId, sourceMetadata, sourceMetadataMap, remixOfId and a top-level
  `input`. Tips are real Buzz that --dry-run structurally CANNOT see (whatIf
  prices a strictly smaller body and is never sent tips), so a strip-and-warn
  would override an explicit instruction in the user's file on a stream an
  unattended run discards. Refusing is unmissable and costs one edit.
- Unknown top-level keys WARN on stderr and never block. The wording is a
  statement about the CLI's own knowledge, not a verdict on the key: the CLI
  does not vendor the server's node registry (anti-mirror rule). It matters
  because the server drops undeclared keys silently at HTTP 200.

--input is mutually exclusive with a prompt argument and the five content flags
(the house pattern from validateDownloadFlags — reject rather than invent a
merge rule for "does --lora append to or replace the file's resources?").
Execution flags all still apply.

--print-input assembles the graph, prints it and exits before the estimator and
long before the submit. Its output round-trips through --input by construction,
which is what replaces the cut --set expression language.

workflows list wraps orchestrator.queryGeneratedImages with cursor paging and
--json; it reports outputs as deliverable/total using the same predicate as
`get`, so a workflow whose results were all filtered out cannot read as normal.
workflows cancel wraps the cancelWorkflow MUTATION and says at every surface
that it BILLS THE ACCRUED COST and refunds nothing. Cancel deliberately does not
route through unwrapTRPC: the procedure returns undefined, so a SUCCESSFUL reply
carries no result.data.json and unwrapTRPC would reject it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…eneration

Endpoint shapes, all verified against the server source while implementing:

  - orchestrator.getWorkflow returns the RAW orchestrator workflow, not the
    normalized shape this doc described; hidden lives at
    step.metadata.output[<blobId>] with a legacy step.metadata.images fallback,
    seed comes from step.metadata.params, and outputs sit in three different
    containers keyed by step type
  - queryGeneratedImages returns the NORMALIZED shape, so a workflow is two
    different types depending on the endpoint
  - cancelWorkflow returns undefined; HTTP 200 is the only success signal
  - there are 9 envelope siblings to whitelist against, not 5

Also records the phase-2 gate: one real generation, estimated 8 Buzz and
charged exactly 8, image downloaded with no credential attached.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…N caveats

AGENTS.md gains six "intentional decisions" items covering `civitai generate`
(11-16): tRPC-not-REST, the deliberate absence of any local graph validation,
the unset-flags-must-be-absent rule, the two asymmetric tRPC envelopes, the
unconditional externalId, and why DownloadPresigned must not be folded back
into DownloadFile. Also adds internal/genapi to the Layout list and corrects
the closing paragraph, which said "both vendored mirrors" while items 1-3 and
10 track three.

README.md: adds `civitai generate` to the credential table (an OAuth login
cannot generate), documents the two generation `--json` caveats (presigned
output URLs expire; `--json` still exits 0 on `ready: false`), and splits the
generate exit-code table by whether the Buzz was already spent.

Corrects two places where the docs disagreed with the code:
  - the global exit-code table said out-of-Buzz and generation-disabled arrive
    as HTTP 403; both arrive as 400 (the upstream 403 is re-thrown server-side
    as a tRPC BAD_REQUEST). Only a muted account / incomplete onboarding is a
    genuine 403.
  - genapi.SubmitResult still carried an UNVERIFIED warning; the shape was
    verified against a live submit at the phase-2 gate.

No behaviour change: docs and comments only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…t never happened

Two audit findings on PR #210, both sitting on this command's own money story.

1. The realized charge was printed only on the --no-wait branch. The default
   (waiting) path announced the workflow and never showed what was billed, so a
   user who approved an ESTIMATE was never shown the actual figure -- on a
   command whose documented behaviour is that realized cost can exceed the
   estimate with no refund. printSubmitted now prints it, and prints NOTHING
   when the server reported no cost rather than a fabricated 0.

2. "You MAY have been charged" fired when nothing had left the machine.
   StatusOf(err)==0 conflates "the request went out and the reply was lost"
   with "the request never left this process"; a cancelled context and an
   expired --timeout produce the second. The warning sent the user to re-attach
   with an externalId no workflow exists behind, which submits a NEW job and
   charges them for real. Adds the ctx.Err() guard the poll loop already had.

Both guards are mutation-verified by BRANCH INVERSION, not deletion: inverting
the ctx check makes the false warning appear AND the genuine one disappear, so
both directions are pinned; inverting the cost check kills all three renderer
tests. Each assertion has a positive control.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@ZacxDev

ZacxDev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Correction to this PR's description, after an adversarial audit

The body claims: "Guards were mutation-tested: each was broken deliberately and shown to fail with its own message." That is overstated, and I'm correcting it here rather than editing the body, since anyone who already read it saw the stronger claim.

Every deletion-shaped mutant does die. But an independent audit ran 50 semantic mutants — operand swaps, branch inversions, off-by-ones, stale re-binds — and 8 survived. Deletion is the weak half of mutation testing; the surviving ones delete nothing:

Mutation Where Consequence
case "y","yes"→ok; default→cancel rewritten as case "n","no"→cancel; default→ok generate.go:979 The spend prompt's default-deny is unpinned. Tests only feed "y" and "n", so a refactor to a deny-list keeps the suite green while [y/N] silently becomes [Y/n]. The current code is correct (bare Enter, maybe, yy, Ye all cancel) — it just isn't asserted.
drop filepath.Base in pendingPath generate_state.go:82 The documented traversal guard on user-supplied --external-id has no test. Verified working manually.
cost > balance → cost >= balance generate.go:709 The cost == balance boundary on the money check is untested. Fails safe.
replay trigger status == 401 → status != 200 genapi/client.go:175 Nothing pins that the mutation replay happens only on 401. Not a live double-charge — the unconditional externalId bounds it — but that's half of the argument in AGENTS.md item 15, and only the other half is asserted.

Plus four lower-impact survivors (clamp-warning boundary, a redundant overwrite stat, a <400 vs <300 status check, and the unread crash-recovery record).

Two findings fixed in 2cb3193, both on the money story

  1. The realized charge was only ever printed on --no-wait. The default waiting path announced the workflow and never showed what was billed — on a command whose documented behaviour is that realized cost can exceed the estimate with no refund. Now printed, and printed as nothing (not 0) when the server reported no cost.
  2. "You MAY have been charged" fired when nothing had left the machine. StatusOf(err)==0 conflated "the request went out and the reply was lost" with "the request never left this process". A cancelled context produced the second, and the warning sent the user to re-attach with an externalId no workflow exists behind — which submits a new job and charges for real.

Both are mutation-verified by branch inversion, not deletion: inverting the ctx guard makes the false warning appear and the genuine one disappear, so both directions are pinned. Each assertion carries a positive control.

Not fixed here

The four table rows above are real gaps in test coverage, not defects — the audit verified the code behaves correctly in each case. The unread PayloadHash (its comment claims a re-attach comparison that nothing implements) and the missing confirmation on workflows cancel are worth follow-ups.

What the audit confirmed independently

The envelope asymmetry, reproduced live and blind: flat = 12, nested = 8, empty {} = 8 — i.e. a nested payload is byte-identically the default-job price. Buzz balance identical before and after; zero spend; no mutation procedure was ever called. Also confirmed: no double-charge path, no unapproved-charge path, no credential leak, the priced graph is byte-identically the submitted graph, and the 401 replay re-sends the same externalId.

Audit verdict: safe to merge, no deploy-blocking findings.

…tion

Reverts the ctx.Err() early-return added in 2cb3193, which a delta re-audit
correctly called a net money-safety regression.

ctx.Err() cannot distinguish "cancelled before the POST" (microseconds, no
charge possible) from "cancelled mid-flight" (up to the submit timeout, charge
entirely possible) -- Ctrl-C during a slow orchestrator hop cancels the same
context, and a slow hop is exactly why a user reaches for Ctrl-C. So the guard
traded a harmless false warning in a microsecond window for SILENCE in a
two-minute window where the charge is real. Silence there strands the user:
this is the only surface that hands back the externalId, and nothing reads the
crash-recovery record.

The uncertainty now lives in the MESSAGE rather than the control flow: the
warning always fires, and a cancelled context is worded "interrupted before
any answer arrived" instead of claiming the server was silent.

Three comment claims from 2cb3193 were also false and are removed: --timeout
does not bound the submit (it is applied in waitAndCollect), re-attaching is
safer than the bare re-run the warning discourages because the orchestrator
dedupes on (userId, externalId), and the cited generate_wait.go precedent does
the OPPOSITE -- a cancelled poll routes to printReattach and says the job has
already been charged.

Also closes the seam the previous round missed: the charge assertions covered
printSubmitted directly, so a mutant making the CALL SITE pass a nil cost
survived all 913 package tests. Adds waiting-path tests driving runGenerate,
plus a cancel-AFTER-send test with submitCalls==1 as its positive control.
Re-introducing either regression now fails.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@ZacxDev

ZacxDev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Correcting my own previous fix — 2cb3193 was a regression, reverted in 75cb114

My last comment said fix #2 was "mutation-verified by branch inversion". It was — and it was still wrong. A delta re-audit of 79b76c5..2cb3193 caught it, and I've verified both of its findings independently.

What I broke

2cb3193 added an early return on ctx.Err() != nil before the "you MAY have been charged" warning, on the theory that a cancelled context means the request never left the process.

That is true only for the microseconds before the POST. Ctrl-C during the round trip cancels the same context, and that window is up to the submit timeout (~120 s) — a slow orchestrator hop being exactly why a user reaches for Ctrl-C. So the guard traded a harmless false warning in a microsecond window for silence in a two-minute window where the charge is real.

Silence there is the worst outcome available: this warning is the only surface that hands the user their externalId, and nothing reads the crash-recovery record back (readPendingGeneration has no production consumer). The user is left with an error, no workflow id, no idempotency key, and no hint that money may have moved.

Red/green, cancel fired inside the submit seam with submitCalls == 1 as the control:

build stderr
79b76c5 (before my "fix") ⚠ …MAY still have been accepted and charged… --external-id 91da0a02-…
2cb3193 (my "fix") empty

Three claims in my own comment were also false

  • "--timeout produces the never-sent case" — --timeout doesn't bound the submit at all; it's applied in waitAndCollect. The submit's bound is a client-level http.Client{Timeout}, which leaves the caller's ctx live.
  • "re-attach with an externalId no workflow exists behind… submits a NEW job and charges them for real" — overstated. The orchestrator dedupes on (userId, externalId), so re-attaching is strictly safer than the bare re-run the warning talks the user out of.
  • "Same guard the poll loop already applies at generate_wait.go:190" — the line number is right and the analogy is inverted. There, a cancelled ctx routes to printReattach and says the job "has already been charged". I cited a precedent that does the opposite of what I did, and per this repo's "a comment is a claim too" rule that comment would have led the next maintainer to defend the regression.

The fix in 75cb114

The uncertainty belongs in the message, not the control flow. We cannot observe whether the request bytes were written, so the warning always fires; a cancelled context is worded "the submit was interrupted before any answer arrived" rather than claiming server silence. The false comments are gone.

And the seam I'd missed

The re-audit also found that my charge assertions all called printSubmitted directly — so a mutant making the call site pass a nil cost survived all 913 package tests. My headline claim ("the default path shows the charge") was asserted about the renderer, never about the path. Now covered by waiting-path tests that drive runGenerate, with a nil-cost contrast.

Both regressions are now pinned: re-introducing the ctx.Err() return fails two tests, and the call-site mutant fails one.

Suite: 1795 tests, 1792 pass, 0 fail, 3 skip (the three known env-gated), gofmt and vet clean.

Still open (unchanged, follow-ups)

The four coverage gaps from the previous comment stand — the spend prompt's default-deny, the --external-id traversal guard, the cost == balance boundary, and the 401-only replay trigger. All are missing tests, not defects. Plus PayloadHash, whose comment still claims a re-attach comparison nothing implements.

ZacxDev added a commit that referenced this pull request Aug 6, 2026
PR #210 (`feat/generate`) adds items 11–16 to this same list while this PR adds
item 11, and `git merge-tree --write-tree` exits 1 on AGENTS.md — a real
textual conflict. Both PRs also independently corrected the intro's stale
"items 5–8 cover `civitai app metrics`" to "5–9" while adding a different
clause, so the correct merged sentence is neither side's and a naive
take-one-side resolution silently loses the other's range.

Nothing about that is discoverable from the file, so whoever resolves the next
collision re-derives the rule under time pressure. Writing it down: append-only,
numbered by arrival, the PR merging SECOND renumbers its OWN items, never an
existing one — because items cross-reference each other by number (item 10
points at item 11, item 9 points at item 6) and so do code comments.

Applied the new rule to the file as it stands: all four `item N` / `items N–M`
references resolve correctly (items 4 and 8 as non-mirrors, items 5–9 as
metrics, item 6 as `notOwned`, item 11 as the ready-ack). The Layout section
carries no item references in this branch.

No code change; the mutation battery is unaffected.

Refs #206
…ot spelled

Round-3 delta audit findings. No functional change; all three were guards that
would stay green while the hazard existed.

- The --external-id assertions matched the FLAG NAME, so blanking the
  interpolated value survived all 917 package tests -- in the one case the
  warning exists to protect. Now assert the minted id VALUE, with a
  non-empty precondition so the assertion cannot be vacuous.
- The waiting-path test asserted the charge was PRESENT while its comment
  claimed it was printed BEFORE the wait. Deferring printSubmitted until after
  waitAndCollect survived. Ordering is now pinned by sampling stderr at the
  first poll.
- Three comment inaccuracies: printReattach lives in generate.go, not
  generate_wait.go; the mid-flight cancel fixture does NOT discriminate
  mid-flight from pre-entry cancellation (measured) and now says so; and a
  test still labelled itself the positive control for a negative test that was
  deleted last round.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@ZacxDev

ZacxDev commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Audit loop converged — round 4 clean, no findings

Four rounds, stopping on a clean round rather than on my say-so.

round scope outcome
1 full PR, blind no 🔴; 2 🟡 fixed; 8 of 50 semantic mutants survived
2 79b76c5..2cb3193 🔴 my fix #2 was a money-safety regression — reverted
3 2cb3193..75cb114 functionally clean; 🟡 guards were spelled, not structural
4 75cb114..5517be6 no findings

Round 4 independently re-ran every kill: blanking the interpolated externalId now fails 2 tests (previously survived all 917), deferring printSubmitted past the wait fails the ordering assertion and only that one — proving the new assertion discriminates rather than duplicating. It also confirmed the round-3 kills were preserved through the rewrite, that the precondition guards can't pass vacuously (lastExternalID is assigned only inside the submit closure), and -race clean.

The round-2 finding is the one worth remembering. I added a ctx.Err() early return to stop a false "you MAY have been charged" warning. It was mutation-verified by branch inversion and it was still wrong: ctx.Err() cannot distinguish cancelled before the POST (microseconds, no charge possible) from cancelled mid-flight (up to ~120s, charge entirely possible). It traded a harmless false warning for silence in the window where the charge is real — and that warning is the only surface handing back the externalId. Mutation testing proved the guard did what I intended; it could not tell me the intent was wrong. Only the delta re-audit did.

Outstanding, all test-coverage gaps rather than defects (each verified to behave correctly): the spend prompt's default-deny, the --external-id traversal guard, the cost == balance boundary, and the 401-only replay trigger. Plus PayloadHash, whose comment claims a re-attach comparison nothing implements — either implement it or reword.

State: mergeable: MERGEABLE, mergeStateStatus: CLEAN, 0 commits behind main, 1795 tests / 1792 pass / 0 fail / 3 pre-existing skips, gofmt + vet clean, -race clean. Ready for human review.

ZacxDev added a commit that referenced this pull request Aug 6, 2026
…READY (#206)

* fix(scaffold): the static and page-vite templates never said BLOCK_READY (#206)

A `page` app is not shown by the Civitai host until it posts `BLOCK_READY` —
that handler in `PageBlockHost.tsx` is the only transition into `ready`. All
three templates declare `page`, but only `page-money` ever sent it, and only
because `@civitai/blocks-react`'s `IframeTransport` acks internally. `static`
(the `civitai app init` DEFAULT) and `page-vite` are deliberately SDK-free, so
they had to say hello themselves and did not. `BLOCK_READY` appeared nowhere in
this repo.

Measured against the REAL `PageBlockHost` (851f759c20) in Chromium,
apps scaffolded from the unfixed CLI and served over HTTP into a sandboxed
iframe with the manifest's own `allow-scripts allow-forms`:

  static     never ready -> visible failure card at ~37s
  page-vite  never ready -> visible failure card at ~37s
  page-money ready in 431-472ms

Same at both trust tiers. The ~37s is `MAX_AUTO_RETRIES = 2` with
`AUTO_RETRY_BACKOFF_MS = [2000, 5000]`. This was an original omission, not a
regression: `git log --follow` shows both template files declared `page` from
their first commit.

The fix vendors one canonical emitter in `internal/blockproto` and has
`scaffold.Render` copy it VERBATIM (no `text/template` pass) into the path
`Template.ReadyAckPath()` names — so there is exactly one authority and both
templates ship byte-identical bytes. Two hand-maintained copies would drift,
and drift here is invisible locally: the app renders fine and dies only inside
the real host.

Ack on BLOCK_INIT, not on load — and on INIT only. Not because on-load is
broken: an on-load poster was MEASURED WORKING in the same harness (ready in
178-265ms). On-INIT is chosen for robustness. The host registers its
BLOCK_READY subscriber inside an effect and silently DROPS a message whose type
has no subscriber yet, with no retry, while it re-posts BLOCK_INIT every ~400ms
until acked — so answering INIT removes the race. It also hands over
`event.origin`, so nothing posts to `'*'`; it is late enough not to reveal an
empty interactive frame (the host fades its launch overlay and enables
pointerEvents on ready); and it is what the SDK's own transport does. Repeats
are a no-op, because the host's inbound channel is rate-limited across all
types.

Also fixes the envelope both templates were teaching. Every block->host message
is `{ type, payload }` — the host dispatches `data.payload` — so the demo posts
with top-level fields modelled the wrong shape for every message an author adds
next. And `RESIZE_IFRAME` is removed outright: `hostHandlerParity.ts` marks it
N/A for `PageBlockHost` (a page block fills the surface and does not size to
content), so it was inert advice. `static/app.js`'s "the minimal useful thing an
app can do is tell the host how tall it is" was simply false for a page app.

After the fix, re-scaffolded from this CLI and re-measured in the same harness
(2 runs, stable): static ready in 453/459ms, page-vite in 477/434ms, page-money
still 489/435ms, and the inert negative control still times out at ~38s.

Refs #206

* test(scaffold): two guards for the ready-ack, because neither one is enough

Guard A (`ready_ack_contract_test.go`, runs in `make ci`) enumerates
`AllTemplates()` and decides subject-hood from EVIDENCE in the rendered output,
never a list in the test: a template is subject to the page-host readiness
contract if its rendered `block.manifest.json` declares `page`, and it is
expected to ship the vendored emitter unless its rendered `package.json`
depends on `@civitai/*` (whose transport acks for it). It then asserts, as
INDEPENDENT sub-tests with distinct messages:

  - byte-equality of the rendered emitter with `blockproto.ReadyAckSource()`;
  - that the emitter is actually REACHED from the entry point — index.html's
    <script src>, or an import in the module index.html loads — checked after
    stripping comments, so the HTML comment above the script tag cannot
    satisfy it.

Plus a count positive control (>= 2 SDK-free page templates examined, with the
page/SDK split printed) so a guard that stopped observing cannot report a
serene pass, and a shape predicate with a negative corpus: a comment mentioning
BLOCK_READY, the string in a README, `{type:'BLOCK_READY', height:0}`, an
untriggered post, and a correct ack broadcast to `'*'` — each asserted to be
rejected BY THE EXPECTED RULE, not merely rejected.

Guard A cannot prove the ack FIRES. No Go static check can prove JavaScript
executes. Guard B (`ready_ack_runtime_test.go`) therefore loads each shipped
emitter in node under a `window` stub, plays the host's side of the handshake
at it, and reads what came out: exactly one message, only after a real
BLOCK_INIT, `{type:'BLOCK_READY',payload:{height:0}}`, addressed at the host
origin and not `'*'`, with a second BLOCK_INIT producing no second ack. It is
env-gated (CIVITAI_CHECK_SCAFFOLD_RUNTIME=1, mirroring the network guard in
pins_guard_test.go) so `make ci` stays Go-only and offline, and it is wired
into the daily `bump-scaffold-pins` workflow as its own job — an env-gated test
with no scheduled runner is a meaningless green.

Guard B validates its own harness before reading its verdict: two known-bad
fixtures (an inert emitter, and a naive ack with the wrong envelope, a `'*'`
target, no gate and no dedupe) go through the SAME assertions and must be
faulted, and the naive one doubles as the count positive control — it posts on
every message, so the driver's counter is watched moving off zero before any
zero it reports elsewhere is believed.

Mutation results (each failure confirmed to come from THIS guard's own
assertion, with the rest of `go test ./...` clean):

  delete the <script> tag from static/index.html   -> A wiring FAILS, A
                                                      byte-equality PASSES
  render an emitter one byte off canonical         -> A byte-equality FAILS,
                                                      A wiring PASSES
  drop "page" from static's manifest               -> static skipped AND the
                                                      count control FAILS
  emitter posts {type,height} with no payload      -> A shape + B FAIL
  emitter acks on load instead of BLOCK_INIT       -> A shape + B FAIL
  invert `event.source !== window.parent`          -> A passes ENTIRELY, whole
                                                      Go module green, B FAILS

That last one is the point of Guard B: the emitter keeps every structural
feature Guard A can see and is completely inert. (The brief predicted the
ack-on-load mutation would play that role; measured, Guard A's shape rules
catch that one too — the inverted source check is the real blind spot.)

Refs #206

* docs: the host handshake is a contract authors must not delete

The templates now ship `civitai-host.js`, and nothing told anyone what it is or
why it looks like it does nothing locally. Four surfaces:

- `static` / `page-vite` READMEs get a "The host handshake — don't delete it"
  section: what BLOCK_READY is for, that the envelope is `{type,payload}`, that
  the ack answers BLOCK_INIT rather than announcing, and the no-local-host
  caveat only page-money's README carried ("`npm run dev` alone shows a blank
  screen — there's no host to send BLOCK_INIT"). Without that caveat the
  emitter's silence during local preview reads as a bug and the file reads as
  deletable.
- `civitai app init`'s next-steps output says the same thing for the two
  templates that ship the emitter. The NeedsHarness branch already covered it;
  the static/page-vite branches said "open index.html" / "npm run dev" with no
  hint that what you see locally is not what the host does.
- README.md gains a "The host handshake (BLOCK_READY)" section under Templates,
  including that RESIZE_IFRAME is not part of a page app's protocol.
- AGENTS.md item 11 records the decision: what it mirrors, why ack-on-INIT
  (with the honest note that on-load was MEASURED working — it is a robustness
  choice, not a bug fix), why `{type,payload}` even though the host ignores this
  particular payload, why `event.origin` and not `'*'`, that RESIZE_IFRAME is
  deliberately ABSENT from page templates, and what each of the two guards does
  and does not prove. Item 10's "third vendored mirror" is amended — this makes
  four (schema/, the slot registry, the dev-embed dotenv mirror, and this).

Refs #206

* docs(readme): page-vite ships no dev harness and wires no SDK

Two pre-existing claims, unrelated to #206 and wrong on inspection of the
templates:

- "The `page-money` / `page-vite` templates ship a dev **harness**" — only
  page-money does. `templates/page-vite/` has no `Harness.tsx.tmpl`, and its
  package.json declares neither `dev:harness` nor `dev:live`. An author
  following that sentence runs a script that does not exist.
- "the code your app actually imports lives in two published npm packages (the
  `page-money` / `page-vite` templates wire them for you)" — page-vite's
  package.json depends on react, react-dom and vite only. Being SDK-free is the
  point of that template, not an oversight.

Also states the reason `npm run dev` shows nothing of the protocol (no host to
send BLOCK_INIT) rather than describing it as a blank screen, which is no longer
true now that the templates render their own UI.

* fix(scaffold): the wiring guard matched a basename, and Guard B gated nothing

Audit round on #206. No 🔴 findings — the shipped emitter is correct and the
browser matrix held — but two of the guards were weaker than the PR claimed.

**The wiring check matched a BASENAME, not a path.** Two mutants shipped a
broken app past the ENTIRE suite, both measured green, both reproducing #206:

  static/index.html   src="./vendor/civitai-host.js"          -> ships a 404
  page-vite/main.jsx  import '../nonexistent/civitai-host.js' -> build fails

So the claim that the guard proved the entry point REACHES the emitter was not
true. Every reference is now RESOLVED — a <script src> against the document
root, an import against the importing module's directory — and compared with
where the emitter actually is; a bare specifier or a URL is not a project path
at all. On failure it prints every reference with what it resolved to and
whether that file exists, so a near-miss names itself. Backed by a 10-case
corpus on synthetic trees (wrong subdir, unresolvable relative, bare specifier,
HTML comment, commented-out import, orphan module, no script tags, CDN URL that
merely ends in the name) — the accept cases are the two real template shapes.

**Guard B never ran on a PR.** ci.yml never set CIVITAI_CHECK_SCAFFOLD_RUNTIME,
so it skipped on every pull request and ran only on a daily schedule, on the
default branch, with no dependent job. The failure the PR advertised it caught —
inverting `event.source !== window.parent` — would have merged green and been
reported up to 24h later. It is now a `ready-ack-runtime` job in ci.yml; the
daily copy stays, relabelled as the drift runner it actually is. Measured, this
is not theoretical: FOUR mutations are invisible to the whole offline suite and
caught only here (inverted source check, inverted type check, latch-before-post,
listener attached inside a setTimeout).

**Nothing in CI built page-vite.** Only page-money was ever scaffolded and
built (template-page-money, scaffold-currency). Since this PR its entry module
has a hard resolution dependency on ./civitai-host.js, so the second mutant
above would have shipped a template that cannot `npm run build` at all. New
`template-page-vite` job builds it and asserts the ack SURVIVES BUNDLING —
Guard A pins the source tree, Vite output is what the platform serves. Control
pair measured locally: with the import the bundle carries BLOCK_INIT/BLOCK_READY,
with it commented out it carries neither, while the positive control (the app's
display name) matches either way, proving the grep reads the bundle.

**`acked` latched before a post that can throw.** `postMessage` rejects a
targetOrigin it cannot parse as a URL, and `event.origin` is the string "null"
when the sender is at an opaque origin — so one throw would silence the emitter
forever while the host kept retrying. Measured in Chromium 1228 rather than
taken from the spec: `postMessage(msg, 'null')` throws
`SyntaxError: Invalid target origin 'null'`. The latch now sets after the post.
Not reachable through today's PageBlockHost, and the comment says so rather than
claiming a live bug. Pinned by a new `--throw-first-post` mode in the driver,
which also models a browser's per-listener exception isolation (previously a
throwing emitter would have killed the driver instead of being observed).

Also: `app init`'s three handshake lines had no test, unlike every sibling
caveat — added, with a control asserting page-money does NOT get them, and
proven to fail when the block is deleted. And the provenance path was wrong in
two comments: usePostMessage.ts is under src/components/AppBlocks/, never
src/hooks/.

Full battery re-run, 16 mutations, ZERO survivors — including the classes the
first battery missed (inverted condition, swapped operands, wrong bind,
commented-out-but-greppable). The battery now also has a positive control that
each mutation APPLIED: one regex silently no-op'd on the `}` inside
`{{ .Name }}` and read as a surviving mutant until that check existed.

Refs #206

* docs: the emitter pins a window, not an identity — and the mirror moved

Four corrections from the audit round, plus mirror currency.

**The emitter checks the sender WINDOW, not the sender ORIGIN.** It answers
`window.parent` and replies to whatever origin that window sent from — which
establishes "our embedder", not "Civitai". The comment said "only the framing
host" and the README said "the host's real origin"; both overstated it. That is
sound for THIS message (the ack carries `{height:0}` and discloses nothing a
page that chose to frame us doesn't already know) and insufficient for anything
else — and both scaffold READMEs explicitly invite authors to add more messages.
All four surfaces now say what it actually establishes, and carry an explicit
warning that an origin allowlist is required before handling any message that
carries data.

Decision recorded in AGENTS.md rather than left implicit: we deliberately do NOT
vendor an allowlist into the emitter. The real set (production, preview
subdomains, dev-*.civit.ai tunnels) is platform state that moves without notice,
so it would become a FIFTH mirror needing lockstep, and getting it wrong
silently breaks the dev tunnel — while @civitai/blocks-react already maintains
exactly that list from VITE_BLOCK_ALLOWED_PARENT_ORIGINS. Keep the emitter
minimal; make adopting the SDK the documented prerequisite for handling data.

**The upgrade path could wedge the host into a fake-ready state.** "If you later
adopt @civitai/blocks-react, delete it" was the one line reversing the
"don't delete it" instruction repeated in four other places, and it was a
parenthetical. If an author adds the SDK and KEEPS the emitter, whichever
handshake answers the first BLOCK_INIT calls notifyReady() -> stop(), clearing
the retry interval AND the readiness timeout; the SDK's waitForInit then rejects
at its own 10s and the host sits "ready" showing an app that never started, with
no retry and no card. Worse than #206, and silent. Now a callout with the
mechanism, in both template READMEs, the main README, and the emitter header.

**useBlockResize was described as "for the non-page block surfaces"**, but
page-money — a page template — calls it (src/App.tsx.tmpl:140). The accurate
statement is that RESIZE_IFRAME is ignored on a page surface and the hook is
surface-agnostic, so calling it there is a harmless no-op that lets SDK
component code move between surfaces.

**Mirror currency: the reference moved from 851f759c20 to 35a9598dc9.** Two
intervening commits touch this contract. BLOCK_HELLO now EXISTS host-side
(iframeInitController.notifyHello, hostHandlerParity.ts, host browser tests) —
the earlier "zero host references" note was true when measured and is now stale.
Re-verified independently rather than taken on report: notifyHello() leaves the
retry interval and readiness timeout armed by start() untouched, and its own
comment forbids it becoming a precondition for sending init, so a block that
never announces is served by the unchanged retry loop — exactly what this
emitter relies on. Recorded that the emitter deliberately does not send it
(scaffolded apps forgo the fast path, cost: one retry tick of latency) and that
the init-fragment path ships gated off and refuses surface === 'dev-tunnel'.
Emitting BLOCK_HELLO remains out of scope.

Also corrects the provenance path (usePostMessage.ts lives under
src/components/AppBlocks/, never src/hooks/) and documents the three guards,
including why the wiring check must resolve paths and must never go back to a
basename or strings.Contains match.

Refs #206

* fix(scaffold): "blocks the merge" was false, and the SDK control was vacuous

Round 3 on #206, from a delta re-audit of 4bc88ad..738ecb6 (which cleared the
previous round's ten findings by mutation).

**The gating claim was false.** `ready_ack_runtime_test.go` and AGENTS.md said
the per-PR ready-ack job BLOCKS the merge. Measured:

  $ gh api repos/civitai/cli/branches/main/protection --jq .required_status_checks.contexts
  ["pins-vs-published","scaffold-currency"]
  $ gh api repos/civitai/cli/rulesets
  []

`ready-ack-runtime` is not a required context. Neither is `template-page-vite`,
and neither is `build-test`. A red run reports and stops nothing — so #211's red
job proved the check DETECTS the regression, not that it would have BLOCKED it.

Corrected in the wording, not in branch protection: making these contexts
required is the honest alternative but it is a repo-policy change affecting
every open PR, so it is the maintainer's call and is recorded as the outstanding
step instead of taken unilaterally. The measurement is inline at each site so
the next reader can re-check rather than trust it.

**Every ::error:: in the bundle assertion was unreachable.** `set -euo pipefail`
plus `n=$(grep -rlF … | wc -l)`: grep exits 1 on no match, pipefail propagates,
`set -e` kills the step AT THE ASSIGNMENT. Reproduced — it exited 1 having
printed only the positive-control line, so the log could not distinguish "the
harness isn't reading the bundle" from "the ack didn't survive the build", which
is the exact ambiguity the positive control exists to remove. It failed CLOSED,
so this was diagnosis, not safety. Each grep now carries `|| true`, the loop
accumulates rc instead of dying, and the needles are scoped to the JS files
actually counted — previously a match in dist/index.html or a public/
passthrough would have satisfied them. Watched in both directions with a decoy
planted in dist/index.html: annotations print, the step still fails rc=1, and
the decoy does not satisfy the assertions.

**The SDK-template control test was vacuous.** Replacing the guard at
app_init.go:238 with `if true` survived the ENTIRE suite: page-money's
ReadyAckPath() is "", so the line printed with an empty filename ("   performs
the host handshake — keep it. …") and the "civitai-host.js is absent" assertion
was satisfied BY THE BUG it should have caught. An assertion spelled on a value
the failure mode erases can only ever pass. Now asserted on the phrase
"performs the host handshake", shared as a constant with the positive test, and
watched going red on that exact mutation.

Checked the conjunct question rather than assuming: NEITHER half should go.
They are coextensive across today's three templates but guard different
failures — `ReadyAckPath() != ""` stops the empty-filename line, `!NeedsHarness()`
stops "there's no host to send BLOCK_INIT" being printed at a template whose
dev:harness mounts one. Recorded at the site.

**Dead branch removed, three live ones pinned.** The `://` half of the URL guard
was unconditionally dead — verified by resolving candidate specifiers with each
half toggled, it changes the outcome for no input — so it is gone rather than
left as a branch no mutation can reach, and the CDN corpus case now says it is
rejected by the fallthrough. The `//` half is NOT dead: without it
`//evil.example.com/../civitai-host.js` has its leading slash stripped,
filepath.Join cleans the `..`, and it resolves to EXACTLY the emitter's path and
is accepted. Pinned, along with the `?`/`#` suffix stripping and the
errNoScriptTags early return, via a new optional `wantErr` on the corpus so a
rejection must come from the branch the case exists to exercise.

Also sweeps two leftover "the real host origin" overclaims from a456c95 that the
round-2 sweep missed (contract_test.go:92, runtime_test.go:151).

Battery: 20 mutations, ZERO survivors, each attributed to the specific test that
killed it, with the apply-verification and null-mutant controls in place.

Refs #206

* docs(agents): record how the "intentional decisions" list is numbered

PR #210 (`feat/generate`) adds items 11–16 to this same list while this PR adds
item 11, and `git merge-tree --write-tree` exits 1 on AGENTS.md — a real
textual conflict. Both PRs also independently corrected the intro's stale
"items 5–8 cover `civitai app metrics`" to "5–9" while adding a different
clause, so the correct merged sentence is neither side's and a naive
take-one-side resolution silently loses the other's range.

Nothing about that is discoverable from the file, so whoever resolves the next
collision re-derives the rule under time pressure. Writing it down: append-only,
numbered by arrival, the PR merging SECOND renumbers its OWN items, never an
existing one — because items cross-reference each other by number (item 10
points at item 11, item 9 points at item 6) and so do code comments.

Applied the new rule to the file as it stands: all four `item N` / `items N–M`
references resolve correctly (items 4 and 8 as non-mirrors, items 5–9 as
metrics, item 6 as `notOwned`, item 11 as the ready-ack). The Layout section
carries no item references in this branch.

No code change; the mutation battery is unaffected.

Refs #206

* docs: two comments claimed more than had been measured

Both are claims this PR itself introduced, in text a future maintainer would
read as evidence.

`resolveProjectRef` said the removed `strings.Contains(spec, "://")` half
"decided nothing for any input". Measured, five inputs disagree — among them
`/x://../civitai-host.js` and `./civitai-host.js?u=https://evil.com`, which it
rejected and which now resolve to the emitter. None is a URL and the new
answer is what a browser gives, so the removal fixes a latent false rejection;
but the comment justified deleting a guard on a stronger claim than the
measurement supports. It now states the scope it was actually measured at.

The numbering note said the Layout section cross-references items by number.
It does not — the coupling today is other items, `ci.yml` and a Go test
comment. Left as-is it points a maintainer doing a renumber at a section with
nothing to fix, while understating where the real references live.

Comment-only: 17 changed lines in the Go file, none outside a comment.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
@ZacxDev
ZacxDev merged commit e340de9 into main Aug 6, 2026
13 checks passed
@ZacxDev
ZacxDev deleted the feat/generate branch August 6, 2026 02:00
ZacxDev added a commit that referenced this pull request Aug 6, 2026
#210 (`civitai generate`) landed first and took AGENTS.md items 12–17, so per
this file's own convention — the PR merging SECOND renumbers ITS OWN new items —
the ready-ack item becomes 18.

Both sides had also edited the "which items are which" sentence above the list,
which is exactly the collision AGENTS.md warns about ("the correct merged
sentence is usually neither one's"). It is rewritten to name both ranges rather
than taking either side. Re-grepped every `item N` cross-reference afterwards:
all resolve, and item 18's references to items 3, 10 and 11 are unchanged.

Merged tree verified rather than assumed: 1896 RUN / 1892 PASS / 0 FAIL /
4 SKIP across 17 packages, gofmt clean over 242 files, and the live
scaffold-and-validate matrix re-run on a binary built from the merge.
ZacxDev added a commit that referenced this pull request Aug 7, 2026
* docs(handoff): capture the civitai generate session state

Records what shipped (#210/#215/#218/#221), the three platform issues and
their outcomes, and the live diagnosis state for the two open follow-ups so
the next session does not re-run probes that already have answers.

Also captures the traps that cost real time here: make ci runs neither gofmt
nor golangci-lint, zsh does not word-split unquoted parameters, a test hang
prints FAIL with no --- FAIL line, and the img2img promotion detector that
must never be re-added because three edit-capable ecosystems price
identically with and without images.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(handoff): retract a wrong diagnosis before anyone acts on it

Investigation 1 described a hazard that does not exist on main. The finding
was real but against PR #222 -- a competing implementation of the same
feature that DID resolve version ids to names in the render path. #222 was
closed as a duplicate and #221 merged instead; I carried the finding across
without re-reading the merged code.

Verified at ba3136c: reportModelSubstitutions takes (io.Writer, []ModelSubstitution,
substitutionPhase), does zero I/O, and prints raw ids. resolveVersion is called
only in buildGenerateGraph pre-estimate.

A handoff carrying a wrong diagnosis is worse than one carrying none -- it is
the first thing the next session acts on. Retracted in place, with where the
false premise came from, so it cannot be re-derived.

Also records both follow-ups as resolved by #237.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(handoff): #3667 is a CONFIRMED audit gap, and the "no bypass" note was wrong

The #3667 section said "Ruled out - IMPORTANT, do not re-derive: there is no
known bypass". That is false, and it is the shape of note that gets a security
gate lifted, so it is retracted in place with the reasoning that failed: some
graphs composing a shared promptGraph says nothing about graphs that opt out of
the shared node names, and two do.

Hunyuan3D declares no `prompt` node at all (hunyuan3d-graph.ts:71), so the audit
at orchestration-new.service.ts:1460 never runs, and the handler then maps
`hunyuanPrompt` back to `prompt` for the generator (handler:58). PolyGen`s
`texturePrompt` is covered by no audit block and is the only text in an
img2model3d request. Verified at a7e0bcd668 across all 79 declared node
keys; escalated on civitai/civitai#3667.

Consequently: DECIDED to keep `--input` pinned to txt2img (next-steps item 3),
since the gate`s stated lift condition is now answered in the negative.

Also records the independent re-verification of PR #237 (2377 PASS / 0 FAIL,
10/10 call-site-weighted mutants killed, with a positive control proving the
harness can report a survivor), and warns that the base clone is currently on
another session`s branch with uncommitted work.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant