From 3c6f53406be2ba441a2ca9fb611738859528c591 Mon Sep 17 00:00:00 2001 From: Abdul Wahab <32850166+abdulwahabone@users.noreply.github.com> Date: Mon, 17 Aug 2026 02:26:02 +0500 Subject: [PATCH] Fix: stop the direction page hanging forever after a re-roll (#469) (#530) * Fix: stop the direction page hanging forever after a re-roll (#469) The re-roll leg of the decision-page protocol was documented only in serve-question.mjs's own header, so agents never ran --update and the open tab polled a round that could never arrive. Compounding failure modes: the page poll swallowed every error, the daemon's --timeout was an absolute guillotine that killed the server under a still-open tab, a choice posted to a dead server confirmed nothing, and refresh or Reload on an unresolved round resurrected heartbeats that held the daemon alive indefinitely. - new-work.md documents the re-roll leg: rerun concept-seed with --from/--reroll, deliver with --update on the same key, never --start a second server. - The page poll terminates and says why: eight consecutive fetch failures means the server is gone; the delivery deadline (the server's own --idle-grace, inlined into the page) passing means the hand never arrived. Both stop heartbeating. - The daemon's --timeout bounds only the wait for a page to open; once the page heartbeats, the server lives while the page does and exits after --idle-grace (default 600s) without a beat, including under --timeout 0. - Build this and Re-roll against a dead server fail loudly instead of silently swallowing the click. - The server tracks the window between a collected re-roll answer and the --update that replaces the round, and serves the page in waiting mode there, so a native refresh re-enters the same bounded wait instead of resurrecting dead cards; the in-page Reload button only revives a delivered hand. - --update is exempt from the headless gate and its liveness probe trusts a fresh heartbeat over a failed kill probe (sandbox EPERM is not death). Squash of the six review-round commits on this branch, rebased onto main after the decision-page revamp. AI assistance: prepared with an AI agent operating under maintainer instruction (abdulwahabone). Co-authored-by: Cursor * Fix review findings: persist the replacement deadline, refuse unloadable hands A browser-native refresh of the waiting page re-entered the bounded wait with a fresh delivery deadline and an immediate heartbeat, so refreshing before each deadline expired could hold the daemon alive and keep --wait on WAITING indefinitely. The server now records when the re-roll or followup answer was collected, each served waiting page inherits only what remains of that one allowance, and a page served after the deadline renders stalled immediately and never starts its heartbeat. And a next hand the round could not load used to reload-loop the tab: GET /'s catch kept the file on disk, so /next-status stayed ready:true forever. --update now refuses a payload without a non-empty options array at the sender, and GET / discards an unloadable next file so the bounded wait resumes. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review finding: a stalled page recovers a late hand without a click The stall silenced heartbeats so the idle grace could reclaim the daemon, but that silence read as a closed tab: after a late --update, --wait saw the stale beat and reported PAGE CLOSED while the user sat on the Reload screen, so the agent abandoned the browser path the recovery UI exists for. The stall screen now keeps a beat-free /next-status watch that reloads into a delivered hand on its own (GET never beats, so an abandoned flow is still reclaimed), and --wait no longer concludes closure from a stale beat while an undelivered next hand sits on disk. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review finding: a delivered hand must not mask a closed page The mid-delivery suppression keyed on the next file existing, but a closed tab never claims that file, so an unconsumed delivery held --wait on WAITING indefinitely instead of reporting the closed flow. The suppression is now age-bound: a stalled page's watch reclaims a delivered hand within seconds, so a file still unclaimed after a 10s grace means no page is coming back and the stale beat reads as the closed page it is. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review finding: stamp the delivery clock at --update, not the copy --wait's mid-delivery grace reads the next file's mtime, but copyFileSync's timestamp behavior is the platform's business: a copy that preserves the source payload's older mtime would start the grace already spent and report PAGE CLOSED under a live stalled tab. --update now touches the delivered file itself, so delivery time is delivery time everywhere. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review findings: disable canon during the wait, validate --timeout The waiting and stall screens disabled only the re-roll buttons; the footer canon action stayed clickable, and a canon pick posted after --wait had consumed the re-roll could never be collected: it overwrote the answer, marked the table closed, and exited the daemon under the agent. Both disable sites now take the canon exit down with the re-roll buttons; a delivered hand reloads the page and serves it live again. And --timeout reached the lifetime timer unvalidated: NaN or a negative value disarmed the no-page exit and the daemon leaked. It now takes the default unless the value is a finite non-negative number, keeping 0 as the explicit wait-forever. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review finding: a second click must not renew the delivery deadline dealAgain left the re-roll and canon controls live through the answer POST and the 700ms fly-out, so a second click posted another re-roll and the server restamped awaitingNextSince, renewing the deadline this PR made non-renewable on refresh and on the stall screen. The controls now go quiet at the click itself, in dealAgain and in answer(), and the server stamps the allowance only on the transition into the wait, so a duplicate answer racing the disable keeps the first stamp. Regression coverage on both sides: the unit deadline test posts a duplicate re-roll mid-allowance and asserts the budget shrank instead of resetting, and the e2e stall test asserts both controls are disabled immediately after the click, before the fly-out. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review finding: a late delivery must survive its claim window --update could land a replacement hand after the stalled page went silent but moments before the daemon's idle deadline: the daemon exited before the page's 1.5s watch could claim the hand, orphaning a delivery --update had confirmed, and the next --wait reported a server failure. The idle exit now defers while an unclaimed next hand is younger than the claim grace --wait already reads (extracted as one shared constant), so the page's watch deals it and heartbeats resume; a file unclaimed past the grace still ends the daemon, bounded as before. Regression test: deliver at idle-deadline-minus-a-beat, assert the daemon survives past the deadline and serves the late hand. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review finding: the claim itself must hold the daemon The idle-exit hold read only the next file's freshness, but GET / deletes that file when it serves the claimed round, before the reloading page can post its first heartbeat: a lifetime tick in that gap saw no pending hand and a stale beat, and exited under the hand just claimed. GET / now stamps the claim when it consumes a pending hand, and the idle exit honors the same bounded grace from that stamp, so the reloading page gets its seconds to beat while an abandoned claim still ends the daemon at the grace. The claim-window regression test now also fetches after the claim, past another lifetime tick, and asserts the daemon survived the gap; verified it fails on the previous commit. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor * Fix review finding: --wait must ride out the claim gap too The claim deletes the next file --wait's mid-delivery grace watches, and the reloading page has not beat yet, so --wait in that gap read the stale beat as PAGE CLOSED while the daemon was alive serving the dealt round, and the agent abandoned a browser session that had just recovered. GET / now persists the claim stamp into the per-key state file, and --wait's suppression honors it under the same bounded grace: a fresh claim stays WAITING, a claim nobody followed with a beat still reads as the closed page it is. Regression test drives --wait through the gap (claim with a stale beat: WAITING, not exit 4) and past it (backdated claim stamp: exit 4); verified it fails on the previous commit. AI-assisted (Cursor agent) under maintainer instruction. Co-authored-by: Cursor --------- Co-authored-by: Cursor Co-authored-by: Paul Bakaus --- skill/reference/new-work.md | 2 +- skill/scripts/serve-question.mjs | 274 +++++++++++++++++++--- tests/new-work-e2e.test.mjs | 179 ++++++++++++++ tests/serve-question.test.mjs | 388 ++++++++++++++++++++++++++++++- 4 files changed, 804 insertions(+), 39 deletions(-) diff --git a/skill/reference/new-work.md b/skill/reference/new-work.md index e247d2f56..7fbdd96a5 100644 --- a/skill/reference/new-work.md +++ b/skill/reference/new-work.md @@ -46,7 +46,7 @@ The script deals three of your structures; the dice pick which three reach the u 4. Run `node {{scripts_path}}/concept-seed.mjs --scope direction --mode ` and follow what it prints. No substitute, no skip: on a new or replacement world, writing artifact code before this script has run and its assignment is acknowledged is a contract violation, whatever the harness, the model, or the time pressure; the roll is what keeps every run from converging on the category default. The script assigns the direction to build and deals catalog challengers. Fuse each challenger before judging it: the challenger supplies the form and its system grammar, the product supplies every fact, clarity wins conflicts. Weigh fused challengers against the assigned direction on exactly two axes, audience identification and product clarity. Losing to strong grounded material is a valid outcome; beating a thin or tool-monoculture list is the point. Close with a verdict per challenger, decided before any borrowing: wins (beats the assigned direction on both axes; becomes the build candidate), competitive (holds one axis; stays a full alternate), or declined (loses both). A declined challenger is not spent: name the one discipline of its system the assigned direction lacks, and raise the assigned direction to match before presenting it. A donation transfers ambition and system discipline (a palette's total commitment, a grid's density courage, a form's structural honesty), never the challenger's clothes; a lifted motif is a costume note, not a raise, and one world owns the page. Write each raise into the presented direction as its own line, named for its donor; a raise nobody can read did not happen. 5. Present one direction, fully committed and already raised by the hand it beat, raises visible as named lines: world, first viewport, visitor path, signature interaction, cross-surface reach, honest risk. Route each challenger by verdict: winning and competitive challengers are full alternates with their QUALITY BAR cards and one-line case; declined challengers render demoted, compact and quiet, each carrying its verdict and what the direction kept from it, never full-size, never silently dropped, still adoptable on request. The verdict informs the user's choice, never pre-empts it; the demoted row is the hand's proof of judgment. A hand holds at most three full-card challengers: when the roll deals more, the three strongest join and the rest wait in the re-roll pool, noted in one line; dropping a challenger from the hand itself takes a named product-truth failure, disclosed. Add one card for your own top-ranked grounded candidate when it is not the assigned direction, kicker IMPECCABLE’S PICK, same anatomy as every card, with an honest risk line naming its familiarity when true: the strongest grounded direction is often where most runs in this category land, and the user deciding that trade is the point of showing it. Familiar and effective is a legitimate destination, not a failure of nerve; the pick card and the standing exit serve it at two depths. One pick card, never two, never a ranked list: a lineup of your candidates hands selection back to a taste function and invites the safest card. The pick never takes the lead position; when the dice assign your top candidate there is no pick card, and the assigned card notes it topped your list. Add re-roll with an optional one-line steer, in three registers: plain (a fresh hand, same spread), safer (your remaining conventional grounded candidates plus the canon against named competitors), bolder (foreign forms only, at full commitment). The register is the user's steering on the familiar-to-bold axis, never yours to pre-select; when the answer carries one, re-run the seed with `--register ` and the next `--reroll` round, and follow what it prints. A user saying "bolder" or "safer" while a direction round is open means these registers, never the bolder or harden commands. The two channels share this structure and differ only in richness: cards and boards on the decision page, names and one-liners through the structured tool, whose option list carries the assigned direction, the pick, the winning and competitive challengers, and the standing exit last; declined challengers fold into the assigned option's description as their kept lines, so the raise survives the text channel. -The standing exit: every direction round offers one quiet, permanent alternative, the category standard, played straight. It is the user's door, never yours: never recommend it, never weigh it against the roll, never let it soften the dealt directions; the counterweights bind the unchosen default, not the chosen one. When the user takes it (the canon action, a safer-steer, or plain words asking for the familiar or competitor-like path), convention becomes the commitment: ask once for two or three products this should sit alongside, make their craft level the bar, and execute the canon at full fidelity, without irony or smuggled quirk. Record a standing preference as a brand commitment in PRODUCT.md. Re-roll eliminates every direction already shown, grounded and challenger alike; after two consecutive re-rolls, ask what quality is missing. Re-roll on your own only on named factual grounds, when the assigned direction cannot carry the product's truth or task; taste is never grounds. The user may re-roll freely, and a user- or brief-pinned direction beats the roll, always. Present the decision visually: write an options payload with the assigned direction leading, its raised lines included; the pick card when one exists; the dealt challengers as alternates with their QUALITY BAR cards, verdicts, and kept lines; re-roll with its safer and bolder registers; steer; canon enabled; and `buildPath` carrying the recorded default with `toggle: true` whenever image generation exists (details in the build-path paragraph below). A degraded roll with no challengers still uses the page, as a single text-only card with re-roll. Give every card the same anatomy: thesis, palette, materials, first viewport, honest risk, and the challengers' case lines (`--schema` prints the exact shape); the page renders identity from these fields, demotes declined challengers to their row on its own, and a challenger's catalog image rides as labeled inspiration, never the promise of the build. Author `canonCard` too: the category standard as one honest card, same anatomy; the page keeps it subordinate, and the counterweights still bind you. Run `node {{scripts_path}}/serve-question.mjs --start --payload ` (`--schema` first for the payload shape). It daemonizes, prints the page URL and a key, and exits; open that URL for the user, in-app browser first, then the system opener, then showing the URL. Collect the choice with `--wait --key `, repeating while it exits 3; the ANSWER prints as JSON. Exit 4 means the page closed unanswered: re-present once through the structured question tool, and with no answer there either, proceed unattended with the assigned direction and state the assumptions. A harness that can leave a shell blocked in the background may run the script without `--start` and let it auto-open and block. Never predict the fallback: run the script, and only exit code 2 from starting it routes the decision to the structured tool; that exit is the fallback, never an error to retry. +The standing exit: every direction round offers one quiet, permanent alternative, the category standard, played straight. It is the user's door, never yours: never recommend it, never weigh it against the roll, never let it soften the dealt directions; the counterweights bind the unchosen default, not the chosen one. When the user takes it (the canon action, a safer-steer, or plain words asking for the familiar or competitor-like path), convention becomes the commitment: ask once for two or three products this should sit alongside, make their craft level the bar, and execute the canon at full fidelity, without irony or smuggled quirk. Record a standing preference as a brand commitment in PRODUCT.md. Re-roll eliminates every direction already shown, grounded and challenger alike; after two consecutive re-rolls, ask what quality is missing. Re-roll on your own only on named factual grounds, when the assigned direction cannot carry the product's truth or task; taste is never grounds. The user may re-roll freely, and a user- or brief-pinned direction beats the roll, always. Present the decision visually: write an options payload with the assigned direction leading, its raised lines included; the pick card when one exists; the dealt challengers as alternates with their QUALITY BAR cards, verdicts, and kept lines; re-roll with its safer and bolder registers; steer; canon enabled; and `buildPath` carrying the recorded default with `toggle: true` whenever image generation exists (details in the build-path paragraph below). A degraded roll with no challengers still uses the page, as a single text-only card with re-roll. Give every card the same anatomy: thesis, palette, materials, first viewport, honest risk, and the challengers' case lines (`--schema` prints the exact shape); the page renders identity from these fields, demotes declined challengers to their row on its own, and a challenger's catalog image rides as labeled inspiration, never the promise of the build. Author `canonCard` too: the category standard as one honest card, same anatomy; the page keeps it subordinate, and the counterweights still bind you. Run `node {{scripts_path}}/serve-question.mjs --start --payload ` (`--schema` first for the payload shape). It daemonizes, prints the page URL and a key, and exits; open that URL for the user, in-app browser first, then the system opener, then showing the URL. Collect the choice with `--wait --key `, repeating while it exits 3; the ANSWER prints as JSON. An ANSWER of `{"optionId":"reroll"}` keeps the server alive and the page open on a loading hand: rerun concept-seed with the same `--scope` and `--mode` plus `--from --reroll ` (1 on the first re-roll, counting up), build the next payload, deliver it with `--update --key --payload `, then return to `--wait` on that key. Never `--start` a second server or fall back to chat here: either strands the open tab on a hand that never arrives. Exit 4 means the page closed unanswered: re-present once through the structured question tool, and with no answer there either, proceed unattended with the assigned direction and state the assumptions. A harness that can leave a shell blocked in the background may run the script without `--start` and let it auto-open and block. Never predict the fallback: run the script, and only exit code 2 from starting it routes the decision to the structured tool; that exit is the fallback, never an error to retry. When image generation exists, every card also declares a `comp` path under `.impeccable/mocks/decision/`, the canon card included. Where the harness sandboxes its shell, start the page through the least-sandboxed command path it offers: a sandboxed shell cannot bind the board's port, and the first-attempt failure costs a retry every session. Serve the page first, then produce the comps; the page shimmer-waits per slot and the user may answer before they land. Each card's image is that direction's north-star comp at full fidelity under [visualize.md](visualize.md)'s comp discipline: the requested surface's first viewport, structure-led prompt, real product name and real content, no invented commercial claims, in that card's own palette, type character, and material world, committed all the way. Generation takes the same time at any fidelity, so an unfinished draft pays comp cost for draft quality; fairness between cards is equal fidelity in each card's own grammar, one surface, one aspect, never shared unfinishedness. The frame's aspect is the surface's own: portrait at device viewport for a native app or mobile-first surface, landscape for desktop web; the decision page adapts to either, and a phone screen comped landscape is a broken frame, not a neutral default. Produce in reading order, the assigned card, then the pick, then the full-card hand, then canon, each file written with its prompt sidecar the moment it is done, so a re-roll's spend front-loads onto the cards read first; declined challengers get no comp, their catalog thumb is their face. With parallel subagents, fan out one agent per card: each spawn is the shipped asset producer with a single-comp packet, that card's fields, PRODUCT.md, the shared frame, and the card's declared path, up to four in flight. Regenerate inline any slot still empty when its agent returns; drop without ceremony any slot still empty when the user answers. No other supervision is owed. Without parallel subagents, generate in the main thread after serving, same order, and let the harness's own generation display carry the progress; the wait for the answer follows the last file. The chosen card's comp is not spent by the choice: comp-led, it enters the comp round as compositional option one; code-led, it returns at the finish review as the critique reference, what the image dared that the build did not. Unchosen comps stay in `.impeccable/mocks/decision/` as the round's spent hand; they carry no approval and imply none. With no image generation, cards carry their identity in palette chips and facts, and that page is complete, not a lesser version; the page then also demotes every challenger's catalog art to a labeled thumbnail on its own, because salience must encode the verdict, never the accident of which cards have images. diff --git a/skill/scripts/serve-question.mjs b/skill/scripts/serve-question.mjs index 4e80b0027..7c4ff0812 100644 --- a/skill/scripts/serve-question.mjs +++ b/skill/scripts/serve-question.mjs @@ -95,9 +95,16 @@ * --stop --key K kill a daemonized question. * --update --key K --payload F deliver the next hand after a re-roll: the * live page swaps to loading cards when the user re-rolls, and - * reloads into this new payload the moment it lands. + * reloads into this new payload the moment it lands. Always the + * same key the round started with; a second --start serves a new + * URL and strands the open tab on a hand that never arrives. * - * node serve-question.mjs --payload question.json [--timeout 900] [--no-open] [--port 0] + * --timeout bounds the wait for a page to arrive, never the user's decision: + * once the page heartbeats, the server lives while the page does, and exits + * only after --idle-grace seconds (default 600) pass with no beat, wide + * enough to survive a closed laptop lid mid-decision. + * + * node serve-question.mjs --payload question.json [--timeout 900] [--idle-grace 600] [--no-open] [--port 0] */ import http from 'node:http'; import fs from 'node:fs'; @@ -120,11 +127,13 @@ if (process.env.IMPECCABLE_QUESTION_DISABLED) { } // Headless self-detection, applied only where a browser is actually wanted. // --no-open means the caller opens the URL itself, and --wait / --stop / -// --schema never open anything: --wait polls a daemon whose browser question -// was already settled at --start, --stop kills one, --schema prints text. A -// spurious exit 2 from those breaks the documented loop, which polls --wait -// while it exits 3 and reads --schema before building a payload. -const wantsBrowser = !hasFlag('no-open') && !hasFlag('wait') && !hasFlag('stop') && !hasFlag('schema'); +// --schema / --update never open anything: --wait polls a daemon whose +// browser question was already settled at --start, --stop kills one, +// --schema prints text, and --update hands the next round to a page that is +// already open. A spurious exit 2 from those breaks the documented loop, +// which polls --wait while it exits 3, reads --schema before building a +// payload, and delivers re-rolled hands with --update. +const wantsBrowser = !hasFlag('no-open') && !hasFlag('wait') && !hasFlag('stop') && !hasFlag('schema') && !hasFlag('update'); if (wantsBrowser && !process.env.IMPECCABLE_QUESTION_FORCE) { const headless = process.env.CI || @@ -176,7 +185,20 @@ function printAnswer(raw) { } const payloadPath = arg('payload'); -const timeoutSec = Number(arg('timeout', '900')); +// --timeout bounds only the wait for a page to open; 0 is the explicit +// wait-forever. A negative or unparseable value takes the default, so a +// typo cannot disarm the no-page exit and leak the daemon. +const timeoutArg = Number(arg('timeout', '900')); +const timeoutSec = Number.isFinite(timeoutArg) && timeoutArg >= 0 ? timeoutArg : 900; +// How long the server (and the page's own delivery deadline) outlive the +// last heartbeat; a zero, negative, or unparseable value takes the default. +const idleGraceArg = Number(arg('idle-grace', '600')); +const idleGraceMs = (Number.isFinite(idleGraceArg) && idleGraceArg > 0 ? idleGraceArg : 600) * 1000; +// How long a delivered next hand may sit unclaimed before it means no page +// is coming back: --wait reads it to keep a stalled page from counting as +// closed mid-delivery, and the daemon reads it to survive until the page's +// watch claims a hand delivered moments before the idle deadline. +const NEXT_CLAIM_GRACE_MS = 10000; const portArg = Number(arg('port', '0')); const QUESTION_DIR = path.join(process.cwd(), '.impeccable', 'questions'); const stateFile = (key) => path.join(QUESTION_DIR, `${key}.state.json`); @@ -243,7 +265,19 @@ if (hasFlag('wait')) { } try { const state = JSON.parse(fs.readFileSync(stateFile(key), 'utf8')); - if (state.lastBeat && Date.now() - state.lastBeat > 15000) { sawClose = true; break; } + // A silent page is not a closed one while a freshly delivered next + // hand sits unclaimed: a stalled page stops beating by design and its + // watch reloads, beating again, within seconds of the file landing. + // The suppression is age-bound because a closed tab never claims the + // hand: a file still there after the grace means no page is coming. + const midDelivery = (() => { + try { if (Date.now() - fs.statSync(path.join(QUESTION_DIR, `${key}.next.json`)).mtimeMs < NEXT_CLAIM_GRACE_MS) return true; } + catch { /* nothing delivered */ } + // The claim deletes that file before the reloaded page can beat: the + // claim stamp the server persisted covers the same bounded gap. + return Boolean(state.claimedAt) && Date.now() - state.claimedAt < NEXT_CLAIM_GRACE_MS; + })(); + if (!midDelivery && state.lastBeat && Date.now() - state.lastBeat > 15000) { sawClose = true; break; } } catch { /* state mid-write */ } await new Promise((r) => setTimeout(r, 1000)); } @@ -280,10 +314,33 @@ if (hasFlag('stop')) { if (hasFlag('update')) { const key = arg('key'); if (!key || !payloadPath) { console.error('serve-question: --update needs --key and --payload'); process.exit(1); } - JSON.parse(fs.readFileSync(payloadPath, 'utf8')); - try { process.kill(JSON.parse(fs.readFileSync(stateFile(key), 'utf8')).pid, 0); } - catch { console.error('serve-question: no live question server for that key'); process.exit(2); } - fs.copyFileSync(payloadPath, path.join(QUESTION_DIR, `${key}.next.json`)); + // A hand the server cannot load must fail here, at the sender: delivered + // anyway, the page would see ready:true for a round that never renders. + const nextRound = JSON.parse(fs.readFileSync(payloadPath, 'utf8')); + if (!nextRound || !Array.isArray(nextRound.options) || nextRound.options.length === 0) { + console.error('serve-question: --update payload needs an options array; nothing was delivered. Fix the payload and rerun --update on the same key.'); + process.exit(1); + } + // Liveness mirrors --wait: a fresh page heartbeat is the primary proof, the + // kill probe is secondary, and EPERM means a sandbox blocked the signal, + // never a dead server. This is the documented re-roll delivery step, so a + // false "no live server" here strands the page mid-shuffle. + const live = (() => { + try { + const state = JSON.parse(fs.readFileSync(stateFile(key), 'utf8')); + if (state.lastBeat && Date.now() - state.lastBeat < 12000) return true; + try { process.kill(state.pid, 0); return true; } + catch (err) { return err.code === 'EPERM'; } + } catch { return false; } + })(); + if (!live) { console.error('serve-question: no live question server for that key; the page it served is gone too. Re-present the round with --start and a fresh key, or fall back to the structured question tool.'); process.exit(2); } + const deliveredFile = path.join(QUESTION_DIR, `${key}.next.json`); + fs.copyFileSync(payloadPath, deliveredFile); + // The file's mtime is the delivery clock --wait's grace reads: stamp it + // here, because a copy that preserves the source payload's older mtime + // would start the grace already spent. + const deliveredAt = new Date(); + fs.utimesSync(deliveredFile, deliveredAt, deliveredAt); console.log('next round delivered; the page reloads itself'); process.exit(0); } @@ -301,7 +358,8 @@ if (hasFlag('start')) { const logFd = fs.openSync(logFile, 'a'); const child = spawn(process.execPath, [ fileURLToPath(import.meta.url), '--payload', payloadPath, '--detached-serve', '--key', key, - '--timeout', String(timeoutSec), ...(hasFlag('open') ? [] : ['--no-open']), + '--timeout', String(timeoutSec), ...(arg('idle-grace') ? ['--idle-grace', arg('idle-grace')] : []), + ...(hasFlag('open') ? [] : ['--no-open']), ], { detached: true, stdio: ['ignore', logFd, logFd] }); child.unref(); fs.closeSync(logFd); @@ -338,6 +396,13 @@ let localImages = []; // even when the round never rendered a toggle. let buildPathDefault = null; let liveBuildPath = null; +// True between a collected re-roll or followup answer and the --update that +// replaces the round: the window where GET / must serve the wait, not the +// answered cards. The timestamp anchors the delivery deadline server-side, +// so a native refresh re-enters the wait with the time already spent, never +// with a fresh allowance. +let awaitingNext = false; +let awaitingNextSince = 0; function loadRound(json) { const parsed = JSON.parse(json); @@ -387,6 +452,9 @@ function loadRound(json) { ? { value: parsed.buildPath.value, toggle: parsed.buildPath.toggle === true } : null; liveBuildPath = buildPathDefault?.value ?? null; + // Last: a round that failed to load anywhere above must leave the waiting + // window open, never resurrect the answered cards. + awaitingNext = false; } try { loadRound(raw); } catch (error) { console.error(`serve-question: ${error.message}`); process.exit(1); } const detachedKey = hasFlag('detached-serve') ? arg('key') : null; @@ -394,7 +462,11 @@ const nextFile = () => detachedKey ? path.join(QUESTION_DIR, `${detachedKey}.nex const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); -function page() { +function page(waiting = false) { + // The delivery deadline survives refreshes: a waiting page gets whatever + // remains of the original allowance, so reloading cannot renew it. Spent + // means the page renders already stalled and never starts a heartbeat. + const waitBudgetMs = waiting ? Math.max(0, awaitingNextSince + idleGraceMs - Date.now()) : idleGraceMs; const flipChip = (label) => ``; const expandChip = ``; // Structured anatomy: chips and one-line facts render when the payload @@ -866,6 +938,7 @@ function page() { not a recommendation. */ #canon { align-self: center; padding: 0 4px; font-family: var(--ks-mono); font-size: .66rem; letter-spacing: .08em; text-transform: uppercase; color: inherit; opacity: .45; background: transparent; border: none; border-bottom: 1px dotted currentColor; cursor: pointer; transition: opacity .2s ease; } #canon:hover { opacity: .85; } + #canon[disabled] { opacity: .18; cursor: default; } .card.skeleton .media { background: var(--ks-graphite); } .shimmer { width: 100%; height: 100%; background: linear-gradient(100deg, var(--ks-graphite) 35%, var(--ks-graphite-2) 50%, var(--ks-graphite) 65%); background-size: 220% 100%; animation: shimmer 1.4s linear infinite; } .card.skeleton .line { height: 11px; border-radius: 4px; background: linear-gradient(100deg, var(--ks-graphite) 35%, var(--ks-graphite-2) 50%, var(--ks-graphite) 65%); background-size: 220% 100%; animation: shimmer 1.4s linear infinite; } @@ -877,6 +950,8 @@ function page() { @keyframes shimmer { from { background-position: 120% 0; } to { background-position: -80% 0; } } @media (prefers-reduced-motion: reduce) { .shimmer, .card.skeleton .line { animation: none; } } .done { display: flex; flex-direction: column; align-items: center; gap: 1rem; padding: 7rem 1rem; font-family: var(--ks-font-display); font-size: 1.4rem; color: var(--ks-champagne); text-align: center; } + .stall { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 1.2rem; padding: 4.5rem 1rem; font-family: var(--ks-font-display); font-size: 1.4rem; color: var(--ks-champagne); text-align: center; } + .stall .choose { align-self: center; margin-top: 0; } @@ -945,11 +1020,22 @@ ${buildPath?.toggle ? `