the rewind and conflict-persistence rounds, plus the GM's reminder edit: the take-back and the honest error record.

The rewind (GM, 2026-11-17): "session rewind" came off the operator queue and was redesigned simpler than the turn-surgery proposal -- physical truncation, not typed cut events; fork is the preservation story (fork before rewinding keeps the branch, no fork no archaeology), and the derivation model made the simple design free: status, agenda, and the sheet are all scanState-derived from the log, so a cut re-derives every channel with zero compensation, and every log reader (the view, the scan, the carry walk, the story, housekeeping) sees the same shorter log with nothing new between them. As built: the send commits the rewind -- POST /turn takes optional rewind (a log line index naming one of your turns; that turn and everything after it leave the log, the send replaces it) and optional expect (the log line count the client composed against; the log only moves through sends, so a mismatch means a stale tab and refuses before anything rides -- the ask answer carries it too); gmTurn's order is pendingAsk-refusal -> expect -> expand -> truncate -> land, one commit inside the activity lock, a crash between truncate and land leaving a consistent shorter log and no rewound-but-waiting state ever existing; the floor is the start marker ({t:'note', kind:'start'} written once at start right after the carryover) -- the frozen opening never unwinds, the rule reads the LAST marker (a carried log may hold an older one inside its opening), and a pre-build log refuses loudly as unmarked; the player-facing records tools are OFF until rewind-compatible (their verbs mutate the session db, which a truncation does not compensate; the manifest carries ask_gm alone whatever the settings gate says, while the CLI's --gm filings never ride a turn and stand, rewind-safe by construction); and /retry never existed -- resending the same words after a rewind IS the retry (the GM had no recollection of where the idea came from; dropped, subsumed). The SPA stages the gesture client-side until the send: a per-GM-turn rewind control (the transcript walk's onRewind, offered live and ask-free only), two-click armed, the target's EXPANDED words auto-filling the composer (the log is truth, $vars baked), a composer tint plus a note naming the cut in entries (the colour alone says something is pending, not what dies), cancel restoring the pre-gesture state, text in the box disabling the buttons under the rename "to rewind delete your current input" (a visible affordance, not hiding), and a failed send keeping the gesture armed only on a 400 (anything else may have moved the log). The gm.md desync is parked to ROADMAP's deferred list (notes taken at turn 30 surviving a rewind to 20, orphaned from the narrative -- nothing mechanical is safe there, fork covers it meanwhile). Verified: typecheck green on both programs, smoke ALL PASS with +14 rewind assertions (the floor refusals, her-turn refusal, the stale-expect 409, the truncation 45->42 lines, the dead-range sheet record reverting, the story dropping the cut, the marker surviving), restart + reminder checks green, check-repo clean after staging, and a browser pass committing a real rewind through the UI end to end (the gesture staged, cancelled, re-staged, edited, sent: 20 turns to 8 on the table, the wire body exactly {line, expect, rewind}, zero console errors).

The conflict-persistence round (GM, 2026-11-18): conflicts stay in the contwin and are self-contained. The old view policy treated conflicts as transient (visible only while the latest word, elided after) -- overruled: a mistake remains visible so it is not made again. Self-contained means the conflict DESCRIBES ITS PROBLEM IN FULL, quoting the offending emission, because the block it answers strips from the view (STRIP_HERS takes her <model>/<mind>/<sheet>) -- an old conflict cannot lean on the turn it immediately follows, and the quote is the only visible trace of what went wrong. As built: renderView renders conflictOnly unconditionally (the lastGmIdx elision gone, the variable with it); a shared quote() helper (trim, collapse whitespace, cap at 160 -- enough to identify the mistake, never a wall) feeds the guards ("yours said: {...}" on <model> and <sheet>, "(you set: ...)" on the mind verb's per-key refusals, "-- yours: {the block}" on mind JSON that does not parse; the out-of-bounds mind already carried "(got 7)" and keeps its exact form); and the ripple caught: carry.mjs's visibleBytes counted conflicts as zero-cost on the grounds they "elide once the story moves on" -- carried conflicts now render in the new session, so they cost against the 96KB budget like the prose they are. The story keeps omitting conflicts (machinery, not deliverable) and invariants' one line still reads true, so no prompt-side change was needed. Verified: smoke ALL PASS with +3 assertions (both session-1 conflicts rendering in the view despite being old news, the model-guard quote, the sheet-guard quote), restart + reminder checks green, check-repo clean.

The GM's prompt-side edit rides the same commit: the reminder's decision passage gains the checked-action metrics -- three probes for when an action should be written as intent (external conditions: the lever; scope expansion: the mall; unilateral canonisation: the gasp at what is inside), each example attempt-form under the handbook's "the attempt, never the outcome", and the third deliberately bending that line with the price named in the same breath (the reaction is hers to have, the contents never hers to say, and the dud reveal embraced as a subversion vehicle -- purview taught as a negotiation, not a prohibition); the impulsive/irrational line now names the channel ("mention it in the narration"); the two tab-indented continuations normalized to the file's spaces.

Also: the smoke's final line now prints the draft id (a smoke draft survived cleanup because "run ids" never named it -- caught on the runs listing, deleted, the print is the fix). Docs: README's protocol passage carries the rewind and the conflict lifetime, with the records-off notes in the substrate section, the tiers table, and the layout; DECISIONS #15 gains the full amendment (the ruling record: a-g, expect, the ask refusal, records-off, the gm.md park); QUESTIONS' turn-surgery details closed (retry dropped, truncation ruled); ROADMAP's surgery sections built-and-amended, the operator queue line removed, the gm.md desync parked; DICTIONARY gains the rewind entry and amends the conflict and view entries. The box package and detention stay untracked WIP, untouched.
This commit is contained in:
2026-11-18 17:24:37 +00:00
parent eefb721675
commit 53f992a5e0
19 changed files with 806 additions and 297 deletions
+106 -1
View File
@@ -70,6 +70,23 @@ memory the agent owes itself across sessions.
- Shell command strings: plain ASCII only -- em-dashes and fancy quotes
get rejected.
- PowerShell's `Copy-Item -Recurse $src $dst` MERGES into an existing
$dst (and nests $src as a child when it exists) -- it never
replaces. Restoring a dir wholesale wants `Remove-Item $dst` first,
then the copy (bitten 2026-11-18 restoring state/ after the smoke:
the first attempt left the smoke's deployment.db at the top level
with the backup nested inside it).
- **state/ is precious now (2026-11-18):** the real refine wrote the
measured registry into state/models.json, which the old smoke
procedure ("Remove-Item state/") would destroy -- re-running refine
costs 9 minutes of real traffic. Amended procedure: back state/ up
to temp first, smoke on the clean slate, then clean-replace it back
(see the Copy-Item lesson) before the debug server restarts.
- `git add -A` STAGES THE GM'S WIP PACKAGES (near-miss 2026-11-18:
packages/box and packages/detention rode `add -A` into the index
and only the status read caught them -- they are untracked until
the GM says otherwise). Stage by path, or `git restore --staged
packages/box packages/detention` after any broad add.
- The edit tool matches bytes, and the console renders dashes
unreliably. When an edit fails on text that "looks right," dump char
codes via PowerShell before retrying; or transcribe from a fresh
@@ -137,7 +154,86 @@ memory the agent owes itself across sessions.
## State pointers
- **The sheet round is BUILT (2026-11-17, staged, uncommitted): the
- **The conflict-persistence round is BUILT (2026-11-18, GM ruling):
conflicts stay in the contwin and are self-contained.** The old
view policy treated conflicts as transient (visible only while
the latest word, elided after) -- the GM overruled it: a mistake
remains visible so it is not made again. Self-contained means the
conflict DESCRIBES ITS PROBLEM IN FULL, quoting the offending
emission, because the block it answers strips from the view
(STRIP_HERS takes her <model>/<mind>/<sheet>) -- an old conflict
cannot lean on the turn it immediately follows; the quote is the
only visible trace of what went wrong. As built: renderView's
conflictOnly branch renders unconditionally (the lastGmIdx
elision is gone, the variable with it); the guards quote (loop.mjs
`quote()` -- trim, collapse, cap 160 -- a shared helper): "yours
said: {...}" on the <model> and <sheet> guards, "(you set: ...)"
on the mind verb's per-key refusals, "-- yours: {block}" on mind
JSON that doesn't parse (the out-of-bounds mind already carried
"(got 7)" and keeps its exact form); parseMind's every error now
names what she wrote. Ripples caught: carry.mjs's visibleBytes
counted conflicts as zero-cost ("elides once the story moves on")
-- carried conflicts now render in the new session, so they cost
against the 96KB budget like the prose they are; the housekeeping
transcript already showed conflicts as "[conflict -- answered
in-band]" (untouched). Verified: typecheck both programs, smoke
ALL PASS (+3 assertions: both session-1 conflicts render in the
view, the model-guard quote, the sheet-guard quote), restart +
reminder checks green, check-repo clean. Docs: README's protocol
passage, DICTIONARY's conflict and view entries. The smoke's
final line now prints the draft id too (the 8a899168 leftover:
a smoke draft survived cleanup because "run ids" never named it
-- delete-by-list is the backstop, the print is the fix).
- **The rewind round is BUILT (2026-11-17, verified into 11-18):
the GM's take-back, riding the send.** The GM took "session
rewind" off their operator queue and simplified the design past
my cut-event proposal: physical truncation, not typed entries --
fork is the preservation story (no fork, no archaeology), and
with all state channels derived from the log (scanState), a cut
re-derives everything with zero compensation machinery. As built:
the send (`POST /turn`) carries optional `rewind` (a log line
index naming a GM turn) and `expect` (the log line count it was
composed against -- the staleness guard, a stale tab refuses
before anything rides; the ask answer carries it too); gmTurn's
order is pendingAsk-refusal -> expect -> expand -> truncate ->
land (one commit inside the lock; a crash between truncate and
land leaves a consistent shorter log); the floor is the start
marker -- `{t:'note', kind:'start'}` written once at start right
after the carryover (the frozen opening never unwinds; the rule
is "after the LAST marker" because a carried log may hold an
older one inside its opening; pre-build logs refuse loudly with
the unmarked-opening 409); the CLI records verbs stand but the
MODEL-FACING records tools are OFF (bundle.mjs toolList returns
ask_gm alone) until they are rewind-compatible -- the GM's --gm
filings never ride a turn, rewind-safe by construction. The SPA:
per-GM-turn rewind button (transcript walk's onRewind, live +
no-pending-ask only), two-click armed, the target's EXPANDED
words auto-fill the composer (the log is truth, $vars baked),
tint + note naming the cut (the colour alone says something is
pending, not what dies), cancel restores, text in the box
disables the buttons under the rename "to rewind delete your
current input", a failed send keeps the gesture armed only on
400 (nothing touched the log), /retry never existed -- resend
after rewind IS the retry. The gm.md desync is PARKED (ROADMAP
deferred: notes orphaned from the narrative after a rewind;
nothing mechanical is safe, fork covers it). Verified: typecheck
green both programs, smoke ALL PASS (+14 rewind assertions: the
floor refusals, her-turn refusal, stale-expect refusal, the
truncation 45->42, the sheet revert, the story dropping the cut,
the marker surviving), restart + reminder checks green,
check-repo clean after staging, and a full browser pass on the
refork run (the gesture staged, cancelled, re-staged, edited,
and committed through the real send: 20 turns -> 8 on the
table, wire body {line, expect, rewind}, zero console errors).
Docs: README (protocol passage, the records-off notes x3, the
layout), DECISIONS #15 amendment (the full ruling record),
QUESTIONS closed (retry dropped, truncation ruled), ROADMAP
(steal #2 and the surgery section built-and-amended, the
operator queue line removed, the gm.md park), DICTIONARY (the
rewind entry). The debug server runs the new code (state/
restored from backup, Chloe + Irene rebuilt).
- **The sheet round is BUILT (2026-11-17, committed eefb721 -- the
roadmap audit rides the same commit): the
GM's ledger of arbitrated run state, the second state channel.**
The rulings that shaped it (all from the 2026-11-17 conversation):
status and agenda are NOT on the sheet -- the split is semantic
@@ -522,6 +618,15 @@ memory the agent owes itself across sessions.
all (probe the
textarea via evaluate instead); clickable divs are invisible to the
a11y tree and the keyboard -- clickable things are buttons. Added
2026-11-18 (rewind round): the harness renamed evaluate's param --
it is `script` now, not `expression` (a wrong name fails with
"Missing key", and search() inside execute gives the true
signature); evaluate RETURNS {tab, value} -- use .value or you
build on the wrapper. And a wait's text match is no settlement
proof mid-action: waiting on a word that lives on a BUTTON label
("rewind") matches instantly while the send is still in flight and
the mid-flight DOM looks like failure -- probe the settled state
via evaluate on a later tick instead. Added
2026-11-14 (multiuser round): the a11y snapshot races async renders
-- waiting for static skeleton text ("RUNS", the aside headings)
snapshots BEFORE the fetches land and looks like a rendering bug;
+42
View File
@@ -313,6 +313,48 @@ content (phase 0); (d) surgery blocked while an ask_gm is pending.
The open details ((a) retry, (b) log representation) ride the build --
they stay in QUESTIONS until the feature does.
BUILT AND AMENDED (2026-11-17, the rewind round -- GM took "session
rewind" off their operator queue and redesigned it simpler):
**truncation, not typed cut events.** The proposed surgery event
never got built: the log is physically truncated at the commit, and
fork is the preservation story -- fork before rewinding keeps the
branch; without one there is no archaeology. What made the simple
design win: by 2026-11-17 status, agenda, and the sheet are all
derived from the log (scanState), so a truncation re-derives every
channel with zero compensation machinery, and every log reader (the
view, the scan, the carry walk, the story, housekeeping) sees the
same shorter log with nothing new between them. The GM's rulings,
as built: (a) live sessions only; (b) the carryover is frozen -- a
start marker notes the floor, and only GM turns below it rewind;
(c) tool turns are never targets (implicit: the target must be a
GM turn); (d) the target is a GM turn, its existing text auto-fills
the composer (the expanded line as logged -- $vars are baked, the
log is truth), and the SEND commits the rewind -- there is no
rewind endpoint and no rewound-but-waiting state: validate ->
expand -> truncate -> land the turn, one commit inside the activity
lock, and a crash between truncate and land leaves a consistent
shorter log; (e) text in the composer disables the rewind buttons
under the rename "to rewind delete your current input" (visible
affordance, not hiding), two-click armed with the warning that
fork-first keeps the branch; a pending tint on the composer plus a
note naming the cut (the colour alone says that something is
pending, not what dies); (f) the REST API is native -- optional
`rewind` (a log line index) and `expect` fields on the turn send,
no UX rules server-side; (g) /retry is DROPPED as a feature --
rewind-to-your-turn and resend the same words subsumes it (the
resend IS the keep). Plus, ruled in the same sitting: every send
carries `expect` (the log line count it was composed against -- the
log only moves through sends, so a mismatch means a stale tab, and
it refuses before anything rides; the ask answer carries it too);
a pending ask refuses the rewind-send (the agent's judgement call,
accepted); the player's records tools are OFF until
rewind-compatible (their verbs mutate the session db, which a
truncation does not compensate -- the manifest carries ask_gm
alone; the CLI's --gm filings never ride a turn and stand); and
the gm.md desync is PARKED (GM notes at turn 30, rewinds to 20:
the note stays, orphaned from the narrative -- nothing mechanical
is safe there; fork covers it meanwhile).
### 17. Status redesign -- RESOLVED (2026-11-12)
Adopted and written into system.md: freeform descriptions admitted by
the three-part gate (non-normal, acute, turn-affecting); the full paper
+23 -2
View File
@@ -210,7 +210,12 @@ WORDS.
mind verb's refusals and the `<model>` guard.
- **conflict** -- the self-heal message: a `<conflict>` block sent as
its own GM-side message, clean of prose; the model adjusts in the
same exchange. Capped at 3 heals per turn.
same exchange. Capped at 3 heals per turn. Conflicts stay in the
contwin (GM, 2026-11-18) -- a mistake remains visible so it is not
made again -- which is why every conflict is self-contained: it
describes its problem in full, quoting the offending emission,
because the block it answers strips from the view and an old
conflict cannot lean on the turn it immediately follows.
- **ask_gm** -- the player's tool for points of order, canon
questions, proposals. Pauses the turn mid-loop; the answer is
authoritative and never elides from the context.
@@ -246,6 +251,21 @@ WORDS.
- **fork** -- an atomic copy of any run under the forker, window
state honestly carried. No lineage; the only mark is
`forked: unixtime` in run.json beside the carried `created`.
- **the rewind** -- the GM's take-back (2026-11-17): the send that
carries `rewind` (a log line index naming a GM turn) replaces that
turn, and everything after it leaves the log outright -- physical
truncation, the one sanctioned break of the log's append-only.
Fork is the preservation story: fork before rewinding keeps the
branch, no fork no archaeology. Live sessions only; the floor is
the start marker (the frozen opening -- authored or carried --
never unwinds); a pending ask refuses the send. Every state
channel re-derives to the cut, so dead-range sheet records and
overrides revert with the prose. In the SPA: two-click armed, the
target's words auto-fill the composer (the expanded line as
logged), a tint marks the outgoing rewrite, and text in the box
blocks the gesture under the rename "to rewind delete your
current input". Resending the same words after a rewind is the
retry -- /retry was never built.
## Instrumentation
@@ -265,7 +285,8 @@ WORDS.
never goes back; old tool results elide to stubs (ask_gm answers
never); old status and agenda blocks elide; her own blocks strip
and the derived state stamps at her most recent turn's tail; one
live reminder at the freshest end.
live reminder at the freshest end; conflicts never elide
(2026-11-18 -- a mistake stays visible).
## Conventions the words lean on
+158 -212
View File
@@ -1,230 +1,176 @@
# Handoff -- working state
A living document: trim items as they complete. Durable decisions live in
`README.md` (architecture, protocol, observables), `ROADMAP.md` (SOTA
review, steals, extension points), and the prompts (`system.md`,
`README.md` (architecture, protocol, observables), `ROADMAP.md` (steal
list, extension points), and the prompts (`system.md`,
`housekeeper.md`). Unanswered questions live in `QUESTIONS.md`, the
decision queue; the agent's own working notes live in `AGENTS.md`. This
file is the "where did we leave off" map.
## Where we are
- **Everything is built, proven, and committed (through the
2026-11-16 night rounds -- see the git log).** The
full scope, each round mock-proven end to end and live-proven
where live could reach: the MVP substrate (clerk, server,
housekeeping job, SPA), multiuser (token identity, invites, fork,
user packages, story-only reads), the agenda, the per-turn reminder,
the variant round (variant literature, the crypto pick), the entity
round (/story, /table, the slidwin carry), the dormant-session
rework (the universal session lifecycle, move-at-stop, the start
lint, rebaseable housekeeping, carryover.jsonl + memory.json
packages), the format house rules (nine-rule check-repo), the
naming round, the JSDoc typing round (server, clerk, web), and the
2026-11-16 rounds: the play-protocol batch (OOC GM turns carry no
cache blocks; memory.json editable as authored draft material,
applied by the start gate over a fresh db; /story filters OOC
whole; the per-turn raw control on the table), and model discovery
(the two-step op act, the registry, registry-gated model use, the
five named knobs), the tunables UX round (the knob definitions
table with the hints and probed bounds, the explicit override
toggle, the shared hint bar, and the request recording -- resolved
model + effective params on every msg event, failed calls
included), the mind verb (the player sets its own sampling
for its next turn: <mind> JSON, one-shot, max_tokens excluded,
bounds enforced and conflict-healed, carried unconsumed across a
session boundary), and the full-block protocol (whole-list
status/agenda at her turn tail, stamped at the canon point, the
<model> display blocks, GM prose pure, silent over-cap eviction,
the delta verbs retired), and the state-scan round (2026-11-16,
evening): the log is the one truth for status and agenda -- the
db tiers retired (schema, verbs, canon views, dump sections gone;
old runs keep dead tables, never read, Irene hands-off),
scanState derives each kind newest-wins across her emissions, the
GM's override records, and the boundary state note; the agenda
cap applies on every derivation (an over-cap list is never
derivable -- the raw log is the only place her seven items live);
the stamp renders the canonical formats (status comma-separated,
agenda markdown bullets, the grammar invariants teaches); the
GM's block edits ride the turn (the pane editors stage, the send
attaches, node logs the override field on the GM turn, the
composition renders it as hers -- append-if-empty, OOC turns
refuse edits, the out-of-band POST routes retired); stop writes
the state note at the carry head (the resume-reconcile skips
it); the start gate's n=1 seeding died (her authored opening
turn IS the seed); continuation carryovers are writable in the
file editor during dormancy), and the GM-input round (2026-11-16,
night): the workbench renders no faces -- the composer overlay and
the transcript share colour-only tokens, source verbatim (the
caret-drift died with the faces), the story view carries its own
renderer (the book keeps bold/italic, asterisks spent), the
composer is turn-shaped (six-line floor, field-sizing growth,
50vh cap, the input's width is the pane's), and the transcript's
stick-to-bottom actually scrolls now (it was dead code -- main is
the scroller, not the div), and the reasoning-effort round
(2026-11-16, late night): the battery probes the effort ladder
per model (efforts + effortDefault in the registry), the knob is
first-class and the GM's alone -- hidden from the model (never in
the mind verb, never in the <model> block, riding the via record
for the raw surfaces), its unset state sends the measured
max-mean default, explicit null clears, the knob row a select
that follows the picked model. The design record lives in README /
DICTIONARY / ROADMAP; the build history in the git log.
- **The project is named: Tiny Worlds.** The invariant it names is
stated in README's premise -- each package is a tiny world on
purpose. The repo lives at `C:\data\opencode\tiny-worlds`; the
rename from `rp-test` is complete end to end (robocopy + session
repoint + a one-time sqlite edit of opencode's own db to repoint
the project record -- the desktop UI cannot delete or repoint
projects, anomalyco/opencode#28030). Launch sessions from the new
path.
- **The conflict-persistence round is BUILT and fully verified
(2026-11-18), staged with the rewind round.** GM ruling:
conflicts stay in the contwin (a mistake remains visible so it is
not made again) and are self-contained -- each describes its
problem in full, quoting the offending emission, because the
block it answers strips from the view. The view renders conflicts
unconditionally, the guards and the mind verb's refusals quote
what she wrote, and carried conflicts now count against the
carry budget. Verified end to end: typecheck, smoke (+3
assertions), restart + reminder checks, check-repo.
- **The rewind round is BUILT and fully verified (2026-11-17/18),
staged and awaiting the GM's commit.** The GM's take-back:
a send may carry `rewind` (a log line index naming one of your
turns) and replaces it, everything after leaving the log by
physical truncation -- fork is the preservation story. The
staleness guard `expect` rides every send (and the ask answer);
the floor is the start marker after the carryover; the
player-facing records tools are off until rewind-compatible (the
CLI --gm path stands); the SPA stages the gesture (two-click arm,
auto-fill, tint + note, cancel, the disabled rename when the box
holds text). gmTurn's order: ask-refusal -> expect -> expand ->
truncate -> land, one commit. Verified: typecheck both programs,
smoke ALL PASS (+14 rewind assertions), restart + reminder
checks, check-repo after staging, and a browser pass committing
a real rewind through the UI with zero console errors. The full
record: DECISIONS #15's amendment, the AGENTS state pointer.
- **Everything else is built and committed through `eefb721`
(2026-11-17).**
The three rounds of that day, each mock-proven and live-proven where
live could reach:
- **The progress round** (`bbaf336`): the provider always streams
(assembling the same response shape, feeding an optional
onProgress callback), the refine battery has a step meter with a
surviving receipt log (the job carries steps/lines; the bar moves
only on real completions), and her turn has a live meter
(`GET /progress` + the transcript-foot placeholder: phase, chars,
elapsed, scaled to her longest past turn or max_tokens, geometric
push-back past 100%, a chunk-stepped fallback strip when no
history). The REAL refine ran end to end (GM-authorized): 13
models in 541s, the meter behaved, and the registry gained the
effort measurements -- the deterministic default re-picked to
glm-5.3-max, with server.json's own pin (glm-5.3) still beating
it until the op edits server.json.
- **The prompt-craft round** (`5279dd3`): the handbook's pointers
section is "Story is the deliverable" with the audience doctrine
(player, GM, reader -- don't summarise or quote the GM's latest
turn; addressing the reader is priced, addressing GM in-character
is nonsensical), the purview example went third-person, Retcons
moved under Continuity; invariants gained the typography ruling
(emphasis is **bold**, italics are actions/thoughts/descriptions
-- codifying what both renderers already assume). Both retired
operator-queue items were struck.
- **The sheet round** (`eefb721`) plus the roadmap audit (same
commit): the GM's ledger of arbitrated run state -- the second
state channel, split from status/agenda by truth model
(self-report vs arbitrated). Schemaless JSON in a `<sheet>` chunk
at the freshest end (its own authoritative voice, never a
canon-point stamp), GM-only authorship riding turns newest-wins
whole-set, the boundary note carrying it across stops, the
read-only guard (the `<model>` sibling), the third pane
(sheetEditor, stage-and-ride). Mock- and browser-proven; the box
package is the first consumer. The roadmap audit retired the done
(582 -> 338 lines): the multiuser and SPA sections are tombstoned,
the stale clauses amended in place, the open steals keep their
numbering.
- **The plan: abandon Chloe, start a fresh run from the top.** The
max-effort result prompted it -- her one max turn thought 11,371
chars (9x her session max) with real continuity work inside (the
comparison is the 2026-11-17 conversation). Chloe's session 1 is
open-on-disk, never stopped, never housekept; the reconcile handles
her at any future start, and the GM may never touch her again.
- **Irene is broken and never runs again (GM, 2026-11-16).** Her logs
and db stay exactly as they are -- no compatibility is designed for
her, no replay, no continuation. What still works is reading her
files on disk (the calibration comparisons); anything live is off
the table. Her frozen session-1 bundle keeps its old handbook copy:
an artifact, hands off.
- **The live story is "La Caramba / Chloe"** (run 15001de3, gitignored
state, glm-5.3-high, owner debug): session one open, 52 GM + 53
player turns. The clean reminder/agenda experiment runs there --
her turn-length curve bends back down late-session where Irene's
ran away, and her reasoning blocks grow into real continuity work
(the calibration comparison against Irene is 2026-11-16
conversation, not a doc). She is MIGRATED to the log-as-truth
design (2026-11-16, same day): her most recent turn carries the
whole-list `<status>`/`<agenda>` blocks, hand-applied from the db's
values before the tiers retired -- her next context stamps them,
the panes derive them, and her db's dead tables sit as residue,
never read. Her older `<lost>/<gained>` tags stay as history (the
view leaves them, the story strips them). Her first stop carries
the first real housekeeping pass, the slidwin test, and the
boundary state note (step 2).
- **Model discovery is built and live-proven (2026-11-16).** The
two-step op act (discover: the free metadata scrape; refine: the
deterministic battery + the curator pass), the registry
(state/models.json -- the truth of selectable models; a fresh
deployment has none and model use is disabled), registry-gated
model routes and turn loop, and the named knobs per
role, run layer over deployment layer -- the five numeric ones
(temperature, top_p, top_k, repetition_penalty, max_tokens) sent
only when set, plus reasoning_effort (2026-11-16, late night --
the sixth, an enum whose unset state sends the measured default;
see the rounds bullet above).
Live-verified against the real endpoint across three refine runs:
gev fails the tool probe and drops (capability detection, no
names in code), off-switch spellings verified per model, the
curator pass curated (after two network-hiccup failures that
exercised the fallback exactly as designed -- machine labels,
deterministic defaults, job applied), and the alias rule works
("measures identical to X -- likely the same model behind both
ids"). The registry on disk is the alias-aware curated run.
RESOLVED (GM, 2026-11-16): the glm-5.2-max vs glm-5.3-max flip was
the dv endpoint's alias all along (one model behind both ids), and
the general rule is ruled and built: the pick ranks on the
reasoning bucket, not the raw token count (within a bucket the
differences are sampling noise -- the thresholds sit in the
endpoint's own observed gaps), and a full tie settles
sort-lex-pick-bottom. The mock registry carries a canned tie pair
(mock / mock-tie, same bucket, same windows) and the smoke asserts
the lex-bottom pick. The on-disk registry still names glm-5.2-max
as its default (the coin-flip run) -- inert while server.json
pins its own pick; the next refine re-picks deterministically
(glm-5.3-max, the lex bottom) and brings the effort measurements
(the registry predates the probe). PENDING: the curator.md review
(GM-led, the housekeeper.md precedent).
- **The server runs in debug mode** (the GM's session:
`node server/main.mjs --debug` -- auth bypassed, loopback-bound).
state/ holds the registry (models.json, the alias-aware curated
run) plus the debug boot's bootstrap-invite mint (no user ever
claimed; the first NORMAL start mints the real bootstrap invite
to state/bootstrap-invite.txt and the console).
and db stay exactly as they are -- reading her files on disk is all
that's left. Her frozen session-1 bundle keeps its old handbook: an
artifact, hands off.
- **The lore round (2026-11-17, conversation + la-caramba gm.md):**
the plot spine (the AI's satellite gambit to beach herself on the
bunker island, the lobotomized emergency model as the comedy that
was the clue) and the five seam answers: she waited for useful
hands; no crew, no robots -- persuasion is her only power; the
invisible AI swarm forum as her knowledge source (pre-lobotomy,
underexplained per the palette); the satellite is a dumb autopilot
deliberately provoked (one calculated event, no running threat, no
rescue because nobody cares); power wakes the real AI. Pinky is
foregone for this run -- without her, pink ice guards the bunker
door and the AI would spend a girl to open it (the door's mechanic
decides which one). gm.md is a garden of diverging paths, not a
plan: nothing is canon until played.
- **The box package is WIP (GM's, untracked, never commit until
said).** The backdrop is an incremental-game economy as ERP (GP/BP,
restraints as income-producing assets); still missing: the opening
turn, real memory seeds, a gm.md (the task stream, the facility's
voice, the release-target ruling) -- its current seeds are
la-caramba leftovers. `packages/detention/` is also WIP, untouched.
- **The debug server runs the current code** (port 7350, pid in the
temp pid file; sessions rebuilt for Chloe and Irene at boot).
state/ holds the refined registry. Three commits await the GM's
push (`bbaf336`, `5279dd3`, `eefb721` -- the ssh key takes a
passphrase, pushes are the GM's), plus the staged rewind round.
## Immediate next steps, in order
1. **First start under multiuser (op, one-time).** Start the server,
claim the bootstrap invite (`state/bootstrap-invite.txt` and the
console both carry it). Discovery is already done -- the registry
is on disk (models.json), so the selectors are populated from the
first load; re-running refine after the curator.md review
regenerates it in one click. No migration code exists, by ruling.
2. **Play Chloe to her first stop -- the memory test begins there.**
Her first close-and-housekeep carries the first real housekeeping
pass: review the manifest and the session log against the dump
diff (the audit surface). Everything from the session lives only
in context and in her logged blocks until this lands. The pass
ends in DORMANCY -- the review window is the point (edit
rings/prompts, then start). Her session two is also the
full-block protocol's first live run: the new prompts +
substrate meet her there, the boundary state note carries her
status and agenda across, and her session-one delta tags ride
the carry as history (the view leaves them, the story strips
them). Irene is broken and never runs again -- her files stay
as they are, reading only.
1. **First start under multiuser (op, one-time).** Start the server
normally, claim the bootstrap invite
(`state/bootstrap-invite.txt` and the console both carry it).
Nothing live has touched the auth spine yet -- mock-proven only.
2. **The fresh run.** Create it from la caramba (the box waits on its
files), pick the model and the effort at create time, and play.
It carries everything new at once: the 2026-11-17 prompt set's
first live test (the audience doctrine, the typography rule, the
no-echo teaching), the full-block protocol's first live run (her
first own whole-list emission is still unplayed), the measured
effort default riding unset turns, and the turn meter under real
use. Her first stop carries the first real housekeeping pass, the
slidwin carry test, and the boundary state note. Decide before
the first turn whether max effort is wanted: a fresh glm-5.3 run
sends `reasoning_effort: max` by the measured default (the
disposable test run's turns thought 12.1k/3.9k/6.5k chars against
~1.4k of prose) -- the knob is one click on the run's model box.
3. **Prompt reviews (GM-led).** housekeeper.md: read it, tweak,
replay -- the dry-run button re-runs housekeeping over the
session log with nothing applied. curator.md likewise: read it,
red-pen, re-run refine.
4. **Keep playing -- and watch the experiments.** Observables #12
(the status stays small and matches the transcripts -- now
structural under the state scan) and #14 (turn
lengthening -- the reminder is the countermeasure under test,
and Chloe's curve bends back down where Irene's ran away), plus
the fresh watchables: does thread-tracking move to the agenda;
cross-channel drift; whether description-only "empty turns" stay
on her side of the purview line; the protocol's own firsts --
whether she restates her blocks every turn or only on change,
whether the `<model>` blocks teach her anything (self-
calibration), and whether she ever states a `<mind>`. The
override's own watchable: whether a GM block edit reads as her
state to her (it must -- the composition is the design) and
whether she adopts or fights it on her next emission. The
effort knob's watchable: whether max-effort changes her texture
and her cost curve -- the first knob that changes how much she
thinks, not how she samples.
Variantary: the metric's curve (`/story` variance -- how often,
how many candidates), coin-flip personality (choices offloaded
to chance that should be character), and whether her variants
stay same-turn alternatives rather than sequences.
replay -- the dry-run button re-runs housekeeping with nothing
applied. curator.md likewise: read, red-pen, re-run refine (one
click; the meter watches it now).
4. **Finish the box** (GM's): the files above, then it becomes the
sheet's first consumer.
5. **Keep playing -- and watch.** The standing observables (#12
status discipline, #14 turn lengthening vs the reminder), the
protocol's firsts (does she restate her blocks every turn or on
change; does the `<model>` block teach her anything; does she
ever state a `<mind>`; does a GM override read as her state and
does she adopt or fight it), the effort knob's texture and cost
curve, the prompt-craft rules against a live model (no-echo,
bold-not-italics), the variantary firsts (the pick against a real
model, the metric's curve, coin-flip personality), and the sheet
once the box runs.
## Not yet exercised (expect first-use friction)
- **First start under multiuser** (step 1) -- nothing live has
touched the auth spine, invites, fork, or the non-owner reads yet;
all are mock-proven only.
- **A knob riding a real request** -- the knobs, their explicit-override
UX, and the request recording are smoke- and browser-proven, but no
live turn has carried one; the max-reasoning defaults are likewise
unplayed (Chloe runs -high; no turn has run on a -max model). The
effort knob doubly so: the registry on disk predates the probe, so
no live turn has carried reasoning_effort either -- the first
refine (the op's one click, post-curator-review) brings the
measured defaults, and the GLM ladder is already verified live by
hand (low suppresses, max elevates).
- **The full-block protocol against a live model** -- whole-list
emission, the stamping, the `<model>` blocks, and whether she ever
states a `<mind>` are all unexercised live; Chloe's session two
(post-review-window) is the first run of it. Her session-one turns
carry the old delta tags as history; the view leaves them (her
words), the story strips them. Her migrated blocks (the last
turn's whole lists) are in-context from her next turn, but she has
not EMITTED a whole list herself yet -- her first own emission is
still unplayed.
- **The GM override against a live model** -- the staging UX, the
turn-riding record, and the composition are smoke- and
browser-proven, but no live turn has carried one; whether a live
model reads the composed state as hers and adopts it is the open
question.
- ask_gm in live flow (pause/resume is mock-proven; the live model
simply made its own choices so far -- by design), the self-heal
conflict path in live flow (mock-proven; capped at 3 heals a turn),
the agenda and the reminder against a live model, records tools
through the server (needs a records-enabled run).
- The slidwin carry against a real session boundary in earnest
(Chloe's first stop), the story read as the review surface, the
OOC-hole showing in practice, and everything variantary live: the
pick against a real model, the metric's curve, coin-flip
personality.
- A live housekeeping rejection, and the recovery-apply path on a
real manifest.
- The in-flow missed-update prediction (ROADMAP, system-1 entry) --
- **First start under multiuser** -- the auth spine, invites, fork,
non-owner reads: all mock-proven only.
- **The rewind against a live model** -- mock- and browser-proven;
the fresh run's first real regret is its first live test, and the
expect guard's 409 has never fired outside the smoke.
- **The full-block protocol and the GM override against a live
model** -- whole-list emission, the stamping, the `<model>` blocks,
override adoption: the fresh run is the first run of it.
- **The sheet against a live model** -- mock- and browser-proven; the
box is the first consumer. The bookkeeper agent is parked
(ROADMAP), unbuilt.
- **The slidwin carry at a real session boundary** (the fresh run's
first stop), the story as the review surface, the OOC-hole in
practice.
- **ask_gm in live flow** (pause/resume is mock-proven; the live
model made its own choices so far), the self-heal conflict path
live (capped at 3 heals a turn), a live housekeeping rejection and
the recovery-apply path.
- **Everything variantary live**: the crypto pick against a real
model, the variance metric's curve, coin-flip personality,
same-turn alternatives rather than sequences.
- **The turn meter's fallback strip** -- every package so far has an
authored opening turn, which gives the meter a scale from the
first turn; the chunk-stepped animation only fires with no
assistant history at all.
- **The in-flow missed-update prediction** (ROADMAP, system-1) --
measurable from the second real session on.
+6 -7
View File
@@ -26,10 +26,9 @@ The GM may revisit later; non-blocking, since the seed copy stays
editable until the first session-open applies it. The rest of #19 is
settled (DECISIONS #19).
### Turn surgery, the open details -- OPEN (build-time)
The principle is decided (DECISIONS #15); the ROADMAP's Later list
carries the feature. Open when it is built: (a) player-turn retry --
same truncate with a re-call, recommended yes, near-zero cost;
(b) log representation -- the jsonl stays append-only and records
surgery as typed entries, the views render the effective history
(proposed).
### Turn surgery, the open details -- RESOLVED (2026-11-17, the rewind round)
Both details closed with the build: (a) the player-turn retry is
DROPPED -- a rewind to your own turn plus resending the same words
subsumes it; (b) the log representation is physical truncation, not
typed surgery entries -- fork is the preservation story. The full
record is the amendment under DECISIONS #15.
+38 -9
View File
@@ -282,7 +282,19 @@ consumes into the log, in one action.
with a pointer at the channel, the same guard `<model>` has.
Numbers that affect play live on the sheet, never in prose
alone -- prose numbers die with the contwin; sheet
numbers ride the scan forever. The mind verb rides the
numbers ride the scan forever. The rewind (2026-11-17) is the
GM's take-back, and it rides the send: a turn may carry
`rewind` -- a log line index naming one of your turns -- and
that send replaces the named turn, everything after it leaving
the log outright (physical truncation; fork is the preservation
story -- fork before rewinding keeps the branch, no fork no
archaeology). The state channels re-derive to the cut: a sheet
record or override inside the dead range reverts with it. The
floor is the frozen opening (the start marker right after the
carryover), never reached past; a pending ask refuses the send.
Every send also carries `expect` -- the log line count it was
composed against -- so a stale tab refuses before anything
rides. The mind verb rides the
same channel:
`<mind>{"temperature": 1.4}</mind>` in a player turn sets its
sampling knobs for its NEXT turn -- one-shot, JSON inside the
@@ -296,7 +308,12 @@ consumes into the log, in one action.
prose, rendered from the via record, the current call included,
suppressed when nothing is set; emitting one is refused with a
pointer at `<mind>`. The sampling itself becomes hers to speak
with. A player turn takes one of four shapes --
with. The self-heal channel's lifetime (2026-11-18): a conflict
stays in the contwin -- a mistake remains visible so it is not
made again -- and every conflict is self-contained, describing
its problem in full with the offending emission quoted, because
the block it answers strips from the view and an old conflict
cannot lean on the turn it follows. A player turn takes one of four shapes --
literature, variant literature, tool call, OOC message (the
reminder teaches them); variant literature is the randomness
channel: several complete candidate turns in one `<variants>`
@@ -357,7 +374,7 @@ Memory is **seven tiers**:
| **status** | descriptions of her immediate situation, admitted by a three-part gate: non-normal, acute, turn-affecting | stamped at her most recent turn's tail, the scan's derived value | **the player** (whole-list `<status>` block in its turns; absent = unchanged); GM override riding a turn, composing as hers |
| **agenda** | her hot queue of intentions -- what she's working towards right now; a fixed-cap recency buffer (new on top, overflow evicts the bottom), disposable by design | stamped at her most recent turn's tail, the scan's derived value (capped at five -- her full list lives only in the log) | **the player** (whole-list `<agenda>` block in its turns; over-cap never derivable); GM override riding a turn, composing as hers |
| **rings A/B** | salient memory -- facts, on her mind, MRU-evicted | always | housekeeper manifest |
| **records** | her files -- the card index, the ledger. Narrow query only, hard cap 10 (in the tool, not the prompt), never bulk-loaded | never -- on demand | **the player** (`file`/`amend`/`discard` at her desk); GM files ahead of play; housekeeper only `archive`s |
| **records** | her files -- the card index, the ledger. Narrow query only, hard cap 10 (in the tool, not the prompt), never bulk-loaded | never -- on demand | **the player** (`file`/`amend`/`discard` at her desk); GM files ahead of play; housekeeper only `archive`s. The player's records tools are off until rewind-compatible (2026-11-17) -- the CLI path stands |
| **cold** | forgotten or vetoed | never -- not even queryable | GM only (`revive`) |
The boundary that keeps the tiers honest: **stances are feelings (status,
@@ -376,6 +393,10 @@ tool refuses queries and record ops when the flag is off, and the rendered
views tell the model the current truth. Unlocking mid-story is a narrative
act: narrate the discovery (the salvaged manifest), flip the flag,
re-render -- the next session and the next housekeeping both see it.
(The player-facing records tools are off until they are
rewind-compatible, 2026-11-17: the flag keeps gating, the manifest
simply does not carry the verbs; the GM's CLI filings are
unaffected.)
The query discipline is an instruction test in itself: queries must be
narrow (what this beat needs, not a fishing expedition), and **a miss is a
@@ -529,8 +550,11 @@ ask_gm answers never do, a ruling must not vanish -- old GM-side
status blocks elide, her own blocks strip, and the derived state
stamps at her most recent turn's tail).
Tool-call pairing is validated before every call. The tool list is
the capability surface: ask_gm always; records only when the run's
gate allows. Chance in play is not a tool: she answers with **variant
the capability surface: ask_gm always; records are OFF for now
(2026-11-17: their verbs mutate the session db, which a rewind does
not compensate -- until they are rewind-compatible the manifest
carries ask_gm alone, whatever the settings gate says; the CLI's
--gm filings never ride a turn and stand). Chance in play is not a tool: she answers with **variant
literature** -- several complete candidate turns in one `<variants>`
block -- and the server picks one at random on reception; the pick is
logged, and the unpicked variants never render on any model-facing
@@ -706,12 +730,15 @@ server/ the substrate: a zero-dependency node:http service
model routes, and the turn loop gate on
bundle.mjs run context: prompt assembly (the trio system message,
the GM-message bundle, @ sigils + $ vars), the tool manifest
and its clerk dispatch
and its clerk dispatch (records off until
rewind-compatible, 2026-11-17)
session.mjs session lifecycle (dormant -> live -> finished: the
start lint and the session-0 memory apply, freeze
and consume; stop with the
move-at-stop slidwin), the append-only typed
jsonl, the view renderer (the stamping at the
move-at-stop slidwin), the typed
jsonl (append-only save the rewind's sanctioned
truncation), the rewind floor (the start
marker), the view renderer (the stamping at the
canon point, elision, thinking-strip,
variant resolution, pairing check)
loop.mjs the turn loop: ask_gm pause/resume, the
@@ -720,7 +747,9 @@ server/ the substrate: a zero-dependency node:http service
stamping), conflict carry, the variant pick, the
mind verb (one-shot <mind> layer over the knob
resolution, bounds enforced, the <model> guard),
the request record (via / req events); the
the request record (via / req events), the
rewind send (the expect staleness guard, the
truncation commit); the
scripted mock model
variants.mjs variant literature: strict parsing of the
<variants> block (malformed refuses loud, nothing
+39 -23
View File
@@ -6,10 +6,13 @@ be worked through one by one; statuses in caps, decisions dated.
## Operator's queue (don't edit, don't work on)
- entirely safe-for-work package. space?
- template package
- "create new package" in SPA
- sec review
- refactor to add first-class GM agent
- entirely safe-for-work package. space? vault?
- revisit what fetch does and SPA reactivity
- user manual
- session rewind
## The landscape (what exists, as of the review)
@@ -207,30 +210,37 @@ thinking never returns, OOC is the paren channel, the context meter,
the reminder's single-copy policy -- lives in README. What the audit
kept from this section is the one design not yet built:
- **Turn surgery, when it earns its build:** rewrite-here, not
forks -- an unfortunate GM turn is edited and the session restarts
from there; all turns since leave the live context, the append-only
log keeps them for audit. Window-scoped only: after housekeeping
the story is consolidated, and corrections become proper retcons.
Tool discipline for the rewrite (the saga rule): every player tool
is either session-pure (ask_gm, records_search -- truncation
removes their effects wholesale) or a journaled mutator (the
records verbs; amend/discard journal prior content, so compensation
is mechanical). Variant turns need no compensation -- the pick note
sits adjacent to its message and only the picked variant ever
applied. See steal #2.
- **Turn surgery -- BUILT as the rewind (2026-11-17).** The GM took
"session rewind" off the operator queue and ruled the simpler
design: rewrite-here stands (an unfortunate GM turn is re-sent,
everything after it leaves the live context), but the mechanism is
physical truncation at the send, not typed cut events -- fork is
the preservation story (fork before rewinding keeps the branch; no
fork, no archaeology). Window-scoped stands by construction: the
rings never move mid-session, so a live-session cut needs zero
compensation, and post-housekeeping corrections remain proper
retcons. The floor is the start marker (the frozen opening);
every send guards staleness via `expect` (the log line count it
was composed against). The full rulings live in the amendment
under DECISIONS #15. The records verbs are off until they are
rewind-compatible (same ruling) -- the journaled-mutator
compensation the original saga rule sketched is what their return
build owes.
## The steal list (work point by point)
### 2. Turn surgery: /retry, /edit in the bridge -- DECIDED (2026-11-12)
Rewrite-here, not fork-here: an unfortunate GM turn is edited in place
and the session restarts from there, losing all turns since. Window-
scoped only -- after a housekeeping run the story is consolidated and
corrections become proper retcons (the boundary falls out of the memory
model: pre-housekeeping events live in context only). Trivial typos are
tolerated as-is; the publishing pass catches them. Forks rejected as
unnecessary. The principle is DECISIONS #15; the open details ride in
QUESTIONS until the build.
### 2. Turn surgery: /retry, /edit in the bridge -- BUILT AS THE REWIND (2026-11-17)
Rewrite-here, not fork-here, exactly as decided (DECISIONS #15); the
build's amendment lives there too. What the build changed from the
original sketch: the jsonl keeps no surgery entries -- the send that
carries `rewind` truncates the log to its target and lands the new
turn in one commit (fork is the preservation story), and /retry never
existed -- resending the same words after a rewind is the retry
(the GM had no recollection of where /retry even came from; dropped).
The bridge itself was retired before this ever built; the feature
lives in the server's turn loop. The records half of the saga rule
(journaled-mutator compensation) is owed when the records tools
return.
### 5. Hybrid retrieval for records_search -- OPEN, DEFERRED
SOTA baseline is BM25 + vector + entity-boost (Mem0 v3, Zep). Our
@@ -280,6 +290,12 @@ Status: DEFERRED.
dormancy, save-linted, blocks included.) What remains deferred is
the purpose-built editing surface over the dormant view's
read-only render.
- **gm.md desync on rewind (GM, 2026-11-17).** Notes taken at turn
30 survive a rewind to turn 20, orphaned from the narrative --
references to events that never happened. Parked: nothing
mechanical is safe there (the substrate cannot know which note
lines anchor to which turns); the honest tools are GM discipline
and fork-covers-it (the fork copies the notepad with the branch).
## Distant extension points (someday, not scheduled)
+12 -1
View File
@@ -29,9 +29,20 @@ instead of the action.
Things to consider when making the decision:
- What seems logical to a reader? Your character has to make sense. If your character is acting impulsively or irrationally, say so.
- What seems logical to the reader? Your character has to make sense. If your character is acting impulsively or irrationally, mention it
in the narration.
- What makes the story better? Avoiding risk for your character introduces risk for the story.
Decide if the action should be checked (if yes, write it as intent). Example metrics for the decision:
- Does the action's result depend on some conditions external to your character? `*Alice pulls the lever with all her strength.*` leaves it
to GM to decide whether the strength is enough for the lever to move.
- Does the action's result meaningfully expand the scope? `*Alice gets ready to drive to the mall.*` leaves it to GM to diegetically object and
redirect your character if the mall in question isn't already canonised and GM would prefer not to pull it in.
- Does the action's result canonise important lore bits unilaterally? `*Alice looks inside and gasps in surprise.*` leaves it to GM to
introduce what's inside. It is your job to anticipate when this purview shift is appropriate, usually GM's turns that build towards a reveal
should be easy to spot. Sometimes the reveal will be a dud, this is normal and even encouraged as a vehicle to subvert the reader's expectations.
If you have several equal options, see Variance below. If you can't proceed, ask GM.
## Speech boundaries
+9 -1
View File
@@ -190,7 +190,15 @@ const RECORD_TOOLS = [
/** @param {string} runId @returns {import('./shapes.mjs').ToolDef[]} */
export function toolList(runId) {
return [ASK_GM_TOOL, ...(readSettings(runId).records === true ? RECORD_TOOLS : [])];
// Records are OFF for now (GM, 2026-11-17): their verbs mutate the
// session db, and a rewind does not compensate db state -- until the
// verbs are rewind-compatible the manifest carries ask_gm alone,
// whatever the run's settings say. The CLI's --gm path is
// unaffected: it never rides a turn, and GM filings ahead of play
// are rewind-safe by construction (the db only moves at housekeeping
// or by the GM's hand).
void runId;
return [ASK_GM_TOOL];
}
// tool name -> clerk argv
+7 -1
View File
@@ -38,6 +38,12 @@ function visibleBytes(lines, eff, i) {
// old GM turns elide their rides in the view
return String(e.m.content ?? '').replace(STRIP_BLOCKS, '').length;
}
if (e.m.role === 'user') {
// conflict traffic stays in the contwin (GM, 2026-11-18) -- a
// carried conflict renders in the new session, so it costs like
// the prose it now is
return String(e.m.content ?? '').length;
}
if (e.m.role === 'assistant') {
// variant turns count only the chosen variant; drafts are
// invisible and cost nothing; thinking rides in the message
@@ -45,7 +51,7 @@ function visibleBytes(lines, eff, i) {
const c = eff.has(i) ? eff.get(i) : e.m.content;
return String(c ?? '').length;
}
return 0; // conflict-only traffic elides once the story moves on
return 0;
}
if (e.t === 'tool') return String(e.m.content ?? '').length; // conservative: the full result, never the stub
return 0; // notes and bundle: machinery, never model prose
+52 -14
View File
@@ -25,7 +25,7 @@
/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */
import { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
import { renderView, cleanBlockList, AGENDA_CAP } from './session.mjs';
import { renderView, cleanBlockList, AGENDA_CAP, rewindTo } from './session.mjs';
import { parseVariants, pickVariant } from './variants.mjs';
import { registry, usable } from './discovery.mjs';
@@ -54,11 +54,18 @@ function needSession(ctx, runId) {
* @param {Ctx} ctx @param {string} runId @param {string} line @param {?Actor} user
* @param {?{ status?: string[], agenda?: string[] }} [override]
* @param {?Record<string, unknown>} [sheet]
* @param {?{ rewind?: ?number, expect?: ?number }} [send]
* @returns {Promise<TurnOut>}
*/
export async function gmTurn(ctx, runId, line, user, override = null, sheet = null) {
export async function gmTurn(ctx, runId, line, user, override = null, sheet = null, send = null) {
const s = needSession(ctx, runId);
if (s.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it first (POST /ask)');
// the staleness guard (GM, 2026-11-17): the client states the log it
// composed against. The log only moves through sends, so a mismatch
// means a stale tab -- refuse before anything rides, rewind or not
if (send?.expect != null && send.expect !== s.lines.length) {
throw new HttpError(409, `the session moved on -- this send was composed against a stale view (${send.expect} lines then, ${s.lines.length} now); refresh and re-send`);
}
// GM-input expansion (strict, DECISIONS #9): the line resolves at
// ingestion -- the log records the expanded words, which is what
// keeps continuation carryovers expansion-free forever. A refused
@@ -69,6 +76,12 @@ export async function gmTurn(ctx, runId, line, user, override = null, sheet = nu
} catch (e) {
throw new HttpError(400, `the line was not sent -- ${e.message}`);
}
// the rewind (GM, 2026-11-17): the target GM turn and everything
// after it leave the log, and this send takes its place. The commit
// happens here -- after the line expanded cleanly, so a refusal
// truncates nothing -- and as one landing with the turn: the log is
// never left rewound-and-waiting
if (send?.rewind != null) rewindTo(s, send.rewind);
// GM prose goes pure: no cache blocks ride any turn. A block edit,
// when given, rides this turn as the override record -- the
// composition overwrites her newest blocks with it (the scan reads
@@ -96,11 +109,16 @@ export async function openingCall(ctx, runId, user) {
/**
* @param {Ctx} ctx @param {string} runId @param {string} answer @param {?Actor} user
* @param {?number} [expect]
* @returns {Promise<TurnOut>}
*/
export async function answerAsk(ctx, runId, answer, user) {
export async function answerAsk(ctx, runId, answer, user, expect = null) {
const s = needSession(ctx, runId);
if (!s.pendingAsk) throw new HttpError(409, 'no pending question');
// the same staleness guard as the turn send: the answer appends too
if (expect != null && expect !== s.lines.length) {
throw new HttpError(409, `the session moved on -- this answer was composed against a stale view (${expect} lines then, ${s.lines.length} now); refresh and re-answer`);
}
// the answer is GM input: same strict expansion, same hand-back --
// a refusal leaves the pending question untouched
let resolved;
@@ -255,14 +273,19 @@ async function runLoop(ctx, runId, user) {
mindNext = mind.params;
}
// the <model> block is display-only: the read side of the mind
// verb, never hers to emit
// verb, never hers to emit. The <sheet> block is the same
// (GM, 2026-11-17) -- the GM's ledger, changes propose in prose.
// Both guards quote the offending emission: a conflict must be
// self-contained (GM, 2026-11-18) -- it stays in the contwin, and
// the block it answers strips from the view, so the quote is the
// only visible trace of what went wrong
if (/<model>/.test(text)) {
carry.push('the <model> block is a read-only display of your active parameters -- state them in a <mind> block');
const emitted = quote(String(text.match(/<model>([\s\S]*?)<\/model>/)?.[1] ?? ''));
carry.push(`the <model> block is a read-only display of your active parameters -- state them in a <mind> block (yours said: ${emitted})`);
}
// the <sheet> block is display-only the same way: the GM's ledger,
// read-only for her (GM, 2026-11-17) -- changes propose in prose
if (/<sheet>/.test(text)) {
carry.push('the <sheet> block is the GM\'s ledger -- propose changes in prose');
const emitted = quote(String(text.match(/<sheet>([\s\S]*?)<\/sheet>/)?.[1] ?? ''));
carry.push(`the <sheet> block is the GM's ledger -- propose changes in prose (yours said: ${emitted})`);
}
if (carry.length && heals < 3) {
// a conflict answers for itself: it goes back as its own message,
@@ -373,10 +396,25 @@ function rangeText(key, r) {
return `${key} accepts any number (-1 and 0 turn the filter off)`;
}
// a conflict quotes the offending emission (self-contained, GM,
// 2026-11-18): the conflict stays in the contwin, the block it
// answers strips from the view, so the quote is the only visible
// trace of what went wrong. Trim, collapse whitespace, cap the
// length -- enough to identify the mistake, never a wall
/** @param {string} s @returns {string} */
function quote(s) {
const flat = s.trim().replace(/\s+/g, ' ');
return flat.length > 160 ? `${flat.slice(0, 160)}...` : flat;
}
/** Parse one turn's <mind> blocks: a JSON object of knobs per block,
* all blocks combined (last wins per key, the same-verb rule). Every
* wrong thing is named -- the caller rides the conflict path, and
* she heals by restating.
* she heals by restating. The errors carry what she wrote: a
* conflict must describe its problem in full (GM, 2026-11-18), even
* when the problem originates in the turn it immediately follows --
* the block itself strips from the view, the conflict is what
* remains.
* @param {string} text @returns {{ params: Record<string, number>, errors: string[] }}
*/
function parseMind(text) {
@@ -388,25 +426,25 @@ function parseMind(text) {
try {
obj = JSON.parse(block);
} catch (e) {
errors.push(`the <mind> block wants a JSON object (${String(e.message ?? e).split('\n')[0].slice(0, 120)})`);
errors.push(`the <mind> block wants a JSON object -- yours: ${quote(block)} (${String(e.message ?? e).split('\n')[0].slice(0, 120)})`);
continue;
}
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
errors.push('the <mind> block wants a JSON object of knobs');
errors.push(`the <mind> block wants a JSON object of knobs -- yours: ${quote(block)}`);
continue;
}
for (const [key, v] of Object.entries(obj)) {
if (key === 'max_tokens') {
errors.push('max_tokens is not hers to set -- the mind verb sets temperature, top_p, top_k, repetition_penalty');
errors.push(`max_tokens is not hers to set -- the mind verb sets temperature, top_p, top_k, repetition_penalty (you set: max_tokens ${JSON.stringify(v)})`);
continue;
}
const range = KNOB_BOUNDS[key];
if (!range) {
errors.push(`the <mind> block names an unknown knob: ${key} -- ${Object.keys(KNOB_BOUNDS).join(', ')}`);
errors.push(`the <mind> block names an unknown knob: ${key} (you set: ${JSON.stringify(v)}) -- ${Object.keys(KNOB_BOUNDS).join(', ')}`);
continue;
}
if (typeof v !== 'number' || !Number.isFinite(v)) {
errors.push(`the <mind> block wants a number for ${key}`);
errors.push(`the <mind> block wants a number for ${key} (you set: ${JSON.stringify(v)})`);
continue;
}
if ((range.min !== undefined && (range.minExclusive ? v <= range.min : v < range.min))
+30 -2
View File
@@ -936,6 +936,30 @@ function readSheet(body) {
return /** @type {Record<string, unknown>} */ (body.sheet);
}
// The rewind and the staleness guard (GM, 2026-11-17), both optional
// fields on the send, both native API with no UX rules riding here:
// rewind names the GM turn (a log line index) this send replaces --
// the target and everything after it leave the log; expect states the
// log line count the send was composed against, and a mismatch (a
// stale tab; the log only moves through sends) refuses before
// anything rides. The SPA always sends expect; curl may omit it.
/** @param {Record<string, unknown>} body @returns {number} */
function readRewind(body) {
if (body.rewind === undefined || body.rewind === null) return Number.NaN;
if (!Number.isInteger(body.rewind)) {
throw new HttpError(400, 'rewind must be a log line index (an integer) -- the GM turn this send replaces');
}
return Number(body.rewind);
}
/** @param {Record<string, unknown>} body @returns {?number} */
function readExpect(body) {
if (body.expect === undefined || body.expect === null) return null;
if (!Number.isInteger(body.expect)) {
throw new HttpError(400, 'expect must be the log line count this send was composed against (an integer)');
}
return Number(body.expect);
}
route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
const line = String(body.line ?? '').trim();
if (!line) throw new HttpError(400, 'line is required');
@@ -944,15 +968,19 @@ route('POST', '/api/runs/:id/turn', async ({ params, body, user }) => {
if ((override || sheet) && line.startsWith('(')) {
throw new HttpError(400, 'a block edit cannot ride an OOC turn -- overrides arrive with a non-OOC GM turn');
}
const rewind = readRewind(body);
const expect = readExpect(body);
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user, override, sheet))) };
const send = { rewind: Number.isNaN(rewind) ? null : rewind, expect };
return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user, override, sheet, send))) };
});
route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
const answer = String(body.answer ?? '').trim();
if (!answer) throw new HttpError(400, 'answer is required');
const expect = readExpect(body);
requireOwner(user, params.id);
return { ok: true, ...(await ctx.enqueue(params.id, async () => answerAsk(ctx, params.id, answer, user))) };
return { ok: true, ...(await ctx.enqueue(params.id, async () => answerAsk(ctx, params.id, answer, user, expect))) };
});
// the turn meter's read (GM, 2026-11-17): the live progress record
+69 -10
View File
@@ -10,13 +10,17 @@
//
// The append-only jsonl is the truth; the in-memory context is a view
// rebuilt from it on boot. Entries are typed (bundle / msg / tool /
// note / opening) so later features (turn surgery) can append their
// own kinds without a format migration. The view renderer is pure
// note / opening) so later features can append their own kinds without
// a format migration. The one sanctioned break of append-only is the
// rewind (2026-11-17): a rewind-send truncates the log to its target
// and lands the new turn in one commit -- fork is the preservation
// story, no fork no archaeology. The view renderer is pure
// policy over the log: thinking never goes back, variant turns render
// only the picked variant, old tool results elide to stubs
// (the last few and every ask_gm answer stay), old GM-side
// <status>/<conflict> blocks elide -- the current status rides the
// newest GM turn.
// <status>/<conflict> blocks elide from GM prose -- the current status
// rides the newest GM turn -- and conflict messages never elide: a
// mistake stays visible so it is not made again (GM, 2026-11-18).
/** @typedef {import('./shapes.mjs').LogEvent} LogEvent */
/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */
/** @typedef {import('./shapes.mjs').PendingAsk} PendingAsk */
@@ -363,6 +367,56 @@ export function findStalledStop(runId) {
return null;
}
// --- rewind: the GM's take-back (GM, 2026-11-17) ------------------------------
//
// The in-place rollback of the live session, deliberately destructive:
// the target GM turn and everything after it leave the log, and the
// send that carries the rewind takes the target's place -- edit-and-
// resend, the turn-surgery principle of DECISIONS #15. Where the old
// proposal kept the discarded range as typed cut events, the ruling
// here is physical truncation: fork is the preservation story (fork
// before rewinding keeps the branch), and with no fork there is no
// archaeology. Truncation is also why the feature is cheap -- every
// reader of the log (the view, the state scan, the carry walk, the
// story, housekeeping) sees the same shorter log with zero new
// machinery; the rings never move mid-session, so nothing else needs
// compensating. The floor is the start marker: the frozen opening
// never unwinds. Called from the send path only, inside the run's
// activity lock, after the new line expanded cleanly -- the commit is
// one landing with the turn that replaces the cut.
/**
* @param {LiveSession} s @param {number} idx the target GM turn's line index
* @returns {number} the lines dropped
*/
export function rewindTo(s, idx) {
if (!Number.isInteger(idx) || idx < 0 || idx >= s.lines.length) {
throw err(400, `the rewind target ${JSON.stringify(idx)} is not a line of this session's log`);
}
const e = s.lines[idx];
if (e.t !== 'msg' || e.m.role !== 'user' || e.conflictOnly) {
throw err(400, 'the rewind target must be one of your turns (a GM turn)');
}
// the floor: the LAST start marker (a carried log may hold an older
// one inside its opening -- only turns after the newest marker are
// this session's live play)
let floor = -1;
for (const [i, x] of s.lines.entries()) {
if (x.t === 'note' && x.kind === 'start') floor = i;
}
if (floor === -1) {
throw err(409, 'this session predates the rewind build -- its opening boundary is unmarked, so nothing is rewindable');
}
if (idx <= floor) {
throw err(400, 'the opening is frozen -- rewind reaches your turns after it only');
}
const dropped = s.lines.length - idx;
s.lines = s.lines.slice(0, idx);
writeLog(s.file, s.lines);
derive(s); // mind and usage re-derive from the shorter log
return dropped;
}
// --- start: lint, freeze, consume, go live -------------------------------------
// the authored carryover's event vocabulary: her opening as msg
@@ -577,6 +631,10 @@ export function startSession(runId, { override = false } = {}) {
{ t: 'bundle', m: system, part: 'system' },
...bundle.map((m, i) => /** @type {LogEvent} */ ({ t: 'bundle', m, part: partNames[i] })),
...carry,
// the rewind floor (GM, 2026-11-17): the opening -- authored or
// carried -- is frozen; live play starts at this line, and a
// rewind may only ever target GM turns below it
{ t: 'note', kind: 'start' },
];
// the assembled context must be sound before anything lands:
// tool pairing, variants resolution, every render invariant
@@ -623,7 +681,6 @@ export function renderView(s, keepToolResults = 4) {
const toolIdx = [];
/** @type {number[]} */
const reminderIdx = [];
let lastGmIdx = -1;
// the stamping pre-pass (the full-block protocol): the canon point
// is her most recent prose turn -- the newest status and agenda
// stamp at its tail, whatever their source (her emission, a GM
@@ -635,7 +692,6 @@ export function renderView(s, keepToolResults = 4) {
let lastProse = -1;
s.lines.forEach((e, i) => {
if (e.t === 'tool') toolIdx.push(i);
if (e.t === 'msg' && e.m.role === 'user') lastGmIdx = i;
if (e.t === 'msg' && e.reminder) reminderIdx.push(i);
if (e.t === 'msg' && e.m.role === 'assistant') {
const c = eff.has(i) ? eff.get(i) : e.m.content;
@@ -691,10 +747,13 @@ export function renderView(s, keepToolResults = 4) {
if (e.m.tool_calls?.length) m.tool_calls = e.m.tool_calls;
msgs.push(m);
} else if (e.conflictOnly) {
// transient error traffic: visible while it is the latest word
// (the model answers it), elided entirely once the story moves
// on -- the log keeps it for provenance
if (i === lastGmIdx) msgs.push({ role: e.m.role, content: String(e.m.content ?? '').trim() });
// the self-heal channel stays in the contwin (GM, 2026-11-18):
// a mistake remains visible so it is not made again. This is
// why conflicts must be self-contained -- describe the problem
// in full, quoting the offending emission, because the
// emission itself strips from the view and an old conflict
// cannot lean on the turn it answered
msgs.push({ role: e.m.role, content: String(e.m.content ?? '').trim() });
} else {
// GM prose goes pure (the full-block protocol): the rides were
// server-composited, never GM words -- strip from every GM
+7 -1
View File
@@ -63,7 +63,13 @@ export {};
* scan reads it newest-wins (it loses to any emission inside the
* tail by position). */
/** @typedef {{ t: 'note', kind: 'state', status?: string[], agenda?: string[], sheet?: Record<string, unknown> }} StateNote */
/** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote|MindNote|StateNote} NoteEvent */
/** start: the frozen-opening boundary (rewind, GM, 2026-11-17) --
* written once at start, right after the consumed carryover: the
* opening (authored or carried) above it is what a rewind can never
* reach. A session whose log predates the build carries none, and
* its rewind refuses loudly. */
/** @typedef {{ t: 'note', kind: 'start' }} StartNote */
/** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote|MindNote|StateNote|StartNote} NoteEvent */
/** bundle: one frozen prompt part (system, backdrop, character, rings). */
/** @typedef {{ t: 'bundle', m: { role: 'user'|'system', content: string }, part: string }} BundleEvent */
+77 -4
View File
@@ -10,7 +10,14 @@
// every turn, the pass log's model), the mind verb (the player sets
// its sampling for its next turn: one-shot, JSON, bounds enforced,
// conflict-healed, carried unconsumed across a session boundary,
// inherited by a fork), the full-block protocol (whole-list status
// inherited by a fork), the rewind (GM, 2026-11-17: the send that
// carries it replaces its target GM turn -- physical truncation, the
// frozen-opening floor, the sheet records of the dead range reverting,
// the staleness guard on every send), the conflict channel's
// persistence (GM, 2026-11-18: conflicts stay in the contwin and are
// self-contained -- the offending emission quoted, because the block
// it answers strips from the view), the full-block protocol
// (whole-list status
// and agenda sets, absent = unchanged, the silent over-cap eviction,
// the view stamping at the canon point, the <model> display blocks,
// the emitted-<model> guard, GM prose pure), the state scan (the log
@@ -324,6 +331,11 @@ ok('her mind tags are write-only (stripped from the view)',
her1.every((m) => !/<mind>/.test(String(m.content ?? ''))), '');
ok('an emitted <model> block strips from the view',
her1.every((m) => !/\n<model>/.test(String(m.content ?? ''))), '');
const viewConflicts = view1.filter((m) => m.role === 'user' && /^<conflict>/.test(String(m.content ?? '')));
ok('past conflicts stay in the context (a mistake remains visible, GM 2026-11-18)',
viewConflicts.length === 2, `${viewConflicts.length} render`);
ok('a conflict describes its problem in full (the stripped emission quoted)',
viewConflicts.some((m) => /yours said: \{"temperature": 0\.1\}/.test(String(m.content ?? ''))), '');
ok('each past turn carries its <model> block when params rode',
her1.some((m) => String(m.content ?? '').startsWith('<model>{"temperature":1.2}</model>')), '');
ok('the <model> block hides the effort knob (not her call)',
@@ -648,8 +660,9 @@ ok('the scan derives the sheet newest-wins', JSON.stringify(r.data.sheet) === '{
// script's ask position -- answer it, then the view asserts (pairing
// must be whole for renderView)
if (r.data.pendingAsk) {
r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'clear enough' } });
ok('the sheet battery answers the script ask', r.status === 200, r.data.error ?? '');
const preAsk = await call(`/runs/${runId}/session`, { token: op });
r = await call(`/runs/${runId}/ask`, { method: 'POST', token: op, body: { answer: 'clear enough', expect: preAsk.data.entries.length } });
ok('the sheet battery answers the script ask (a fresh expect passes)', r.status === 200, r.data.error ?? '');
}
{
const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null });
@@ -685,6 +698,9 @@ ok('her emitted sheet never applies (the scan holds the GM\'s record)',
const view = renderView({ lines: jsonl(runId, 4, 'log.jsonl'), pendingAsk: null });
ok('the view strips her emitted sheet (the chunk alone carries it)',
view.every((m) => m.role !== 'assistant' || !/<sheet>/.test(String(m.content ?? ''))), 'her emission rode the view');
const sheetConf = view.find((m) => m.role === 'user' && /GM's ledger/.test(String(m.content ?? '')));
ok('the sheet guard quotes her emission (self-contained)',
!!sheetConf && /yours said: \{"gp": 99\}/.test(String(sheetConf?.content ?? '')), String(sheetConf?.content ?? 'no conflict in the view'));
}
r = await call(`/runs/${runId}/story`, { token: op });
ok('the story strips her emitted sheet',
@@ -717,7 +733,64 @@ ok('the sheet crossed the boundary (the note feeds the new session\'s scan)', JS
ok('session 5 renders the sheet chunk from the carried note', chunk?.content === '<sheet>{}</sheet>', chunk?.content ?? 'no chunk');
}
console.log(`\nrun ids: source=${runId} fork=${forkId} second=${secondId} refork=${reforkId}`);
// 24. the rewind (GM, 2026-11-17): the GM's take-back. The send that
// carries rewind replaces the target GM turn -- the target and
// everything after it leave the log (physical truncation; fork is the
// preservation story). The floor is the start marker (the frozen
// opening), and every send guards against a stale view via expect.
{
// the floor marker rides session 5's log, after the carry
const s5 = jsonl(runId, 5, 'log.jsonl');
const marker = s5.map((e, i) => (e.t === 'note' && e.kind === 'start' ? i : -1)).filter((i) => i >= 0).pop();
ok('the start marker rides the log (the rewind floor)', marker != null && marker >= 0, String(marker ?? 'none'));
// two turns with ledger records: the rewind will revert the second
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Rewind battery one.*', sheet: { rb: 1 } } });
ok('rewind battery: turn one sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Rewind battery two.*', sheet: { rb: 2 } } });
ok('rewind battery: turn two sends', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}`, { token: op });
ok('rewind battery: the second record leads', JSON.stringify(r.data.sheet) === '{"rb":2}', JSON.stringify(r.data.sheet));
const now = await call(`/runs/${runId}/session`, { token: op });
const len = now.data.entries.length;
const target = now.data.entries.findIndex((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly && /Rewind battery one\./.test(String(e.m.content ?? '')));
ok('the target GM turn is addressed by log index', target >= 0, String(target));
// the staleness guard: a wrong expect refuses before anything rides
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Stale.*', expect: len - 1 } });
ok('a stale expect refuses the send', r.status === 409 && /stale/.test(r.data.error), r.data.error ?? '');
// her turn is not a valid target
const herIdx = now.data.entries.map((e, i) => (e.t === 'msg' && e.m.role === 'assistant' && !e.m.tool_calls?.length ? i : -1)).filter((i) => i >= 0).pop();
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*No.*', rewind: herIdx, expect: len } });
ok('her turn is not a rewind target', r.status === 400 && /your turns/.test(r.data.error), r.data.error ?? '');
// the frozen opening: a carried GM turn (above the marker) refuses
const carriedGm = now.data.entries.findIndex((e, i) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly && i < (marker ?? 0));
ok('the battery found a carried GM turn above the floor', carriedGm >= 0, 'none before the marker');
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*No.*', rewind: carriedGm, expect: len } });
ok('the frozen opening refuses the rewind', r.status === 400 && /frozen/.test(r.data.error), r.data.error ?? '');
// the refusals landed nothing
r = await call(`/runs/${runId}/session`, { token: op });
ok('the refused rewinds touched nothing', r.data.entries.length === len, `${len} -> ${r.data.entries.length}`);
// the rewind send itself: the edited turn replaces its target, the
// ledger record restated as part of the rewrite
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Rewind battery one, edited.*', sheet: { rb: 1 }, rewind: target, expect: len } });
ok('the rewind send lands', r.status === 200, r.data.error ?? '');
r = await call(`/runs/${runId}/session`, { token: op });
ok('the log truncated (the target replaced, everything after it gone)',
r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'user' && /Rewind battery one, edited/.test(String(e.m.content ?? '')))
&& r.data.entries.every((e) => !/Rewind battery (one\.|two)/.test(JSON.stringify(e)))
&& r.data.entries.length < len,
`${len} -> ${r.data.entries.length}`);
ok('the marker survives the cut (the floor holds)', r.data.entries.some((e) => e.t === 'note' && e.kind === 'start'), '');
r = await call(`/runs/${runId}`, { token: op });
ok("the dead range's records re-derive away (the sheet reverts)", JSON.stringify(r.data.sheet) === '{"rb":1}', JSON.stringify(r.data.sheet));
r = await call(`/runs/${runId}/story`, { token: op });
ok('the story drops the cut range', r.data.sessions.every((s) => s.turns.every((t) => !/Rewind battery two/.test(t.text))), 'the dropped prose survived in the story');
}
console.log(`\nrun ids: source=${runId} draft=${draftId} fork=${forkId} second=${secondId} refork=${reforkId}`);
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0);
+4
View File
@@ -185,6 +185,10 @@
</aside>
<footer>
<div id="rewind-note" hidden>
<span id="rewind-note-text"></span>
<button id="rewind-cancel">cancel rewind</button>
</div>
<div id="gm-stack">
<pre id="gm-hl" aria-hidden="true"></pre>
<textarea id="gm-input" rows="6" placeholder="GM turn -- Enter newlines, Ctrl+Space sends" disabled></textarea>
+14 -1
View File
@@ -290,6 +290,9 @@ h1 { font-size: 15px; letter-spacing: 0.1em; color: var(--dim); font-weight: nor
.turn { margin: 0 0 20px; max-width: 760px; }
.turn .who { display: flex; align-items: baseline; gap: 8px; font-size: 11px; letter-spacing: 0.12em; color: var(--dim); margin-bottom: 3px; }
.turn .who .raw-toggle { margin-left: auto; font-size: 11px; padding: 0 8px; color: var(--dim); }
/* the rewind control rides beside the raw toggle (the play view owns
its arm state; the disabled rename is the affordance, not hiding) */
.turn .who .rewind-toggle { font-size: 11px; padding: 0 8px; color: var(--dim); }
.turn.gm .who { color: var(--accent); }
.turn.player .who { color: var(--ok); }
.raw-slot { margin: 10px 0 2px; }
@@ -443,7 +446,17 @@ footer {
background: var(--panel); border-top: 1px solid var(--line);
display: none;
}
body.play footer { display: flex; }
body.play footer { display: flex; flex-wrap: wrap; }
/* the rewind note (GM, 2026-11-17): a full-width row above the
composer while a rewind is armed -- it names the cut and explains
the tint (the colour alone says that something is pending, not
what dies) */
#rewind-note { flex-basis: 100%; display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--accent); }
#rewind-note[hidden] { display: none; }
#rewind-note button { font-size: 12px; padding: 2px 12px; }
/* the armed composer: the background tint is the mark of an outgoing
rewrite -- the turn in the box replaces its target on send */
#gm-stack.rewind-pending { background: rgba(201, 162, 109, 0.10); border-radius: 4px; }
#gm-stack { position: relative; flex: 1; display: grid; min-width: 0; }
#gm-stack.off { opacity: 0.4; }
/* the highlight overlay: the setup editor's stack pattern -- a pre
+14 -4
View File
@@ -199,6 +199,7 @@ function noteText(e) {
if (e.sheet) parts.push(`sheet ${JSON.stringify(e.sheet)}`);
return `boundary state carried across the stop: ${parts.join(' | ')}`;
}
if (e.kind === 'start') return 'the frozen opening ends here -- rewind reaches your turns below this line';
return null;
}
@@ -296,11 +297,15 @@ export function renderRaw(entries) {
// onRaw, when given, puts a small control on every GM/player turn
// that shows that one entry's wire form inline -- the play view owns
// the fetch (the raw session is the audit surface; the walks are
// index-aligned, so table entry i is session entry i). The opening
// event (her opening status) renders as machinery, mirroring
// index-aligned, so table entry i is session entry i). onRewind, when
// given, puts the rewind control on every GM turn (the play view
// passes it only while it may fire: live, no pending ask) -- the
// callback receives the entry's index, its text, and the button, and
// owns the two-click arm and everything the gesture stages. The
// opening event (her opening status) renders as machinery, mirroring
// the wire policy: it is set once, never re-sent.
/** @param {LogEvent[]} entries @param {{ onConflict?: (text: string) => void, onRaw?: (idx: number, slot: HTMLElement) => Promise<void> }} [opts] */
export function renderTranscript(entries, { onConflict, onRaw } = {}) {
/** @param {LogEvent[]} entries @param {{ onConflict?: (text: string) => void, onRaw?: (idx: number, slot: HTMLElement) => Promise<void>, onRewind?: (idx: number, text: string, btn: HTMLButtonElement) => void }} [opts] */
export function renderTranscript(entries, { onConflict, onRaw, onRewind } = {}) {
const t = $('transcript');
t.textContent = '';
/** @type {BundleEvent[]} */ const bundleParts = [];
@@ -376,6 +381,11 @@ export function renderTranscript(entries, { onConflict, onRaw } = {}) {
if (e.override) d.appendChild(el('div', 'machinery', overrideText(e.override)));
if (e.sheet) d.appendChild(el('div', 'machinery', sheetText(e.sheet)));
if (onRaw) addRawControl(head, d, idx);
if (onRewind) {
const btn = /** @type {HTMLButtonElement} */ (el('button', 'rewind-toggle', 'rewind'));
head.appendChild(btn);
onRewind(idx, String(e.m.content ?? ''), btn);
}
t.appendChild(d);
}
/** @param {MsgEvent} e @param {number} idx */
+99 -4
View File
@@ -25,6 +25,70 @@ import { renderRaw, renderTranscript, stickBottom, viaLine } from './transcript.
/** @type {?string} */ let rawRun = null;
let rawOpen = false;
// --- the rewind (GM, 2026-11-17) -------------------------------------------------
//
// The GM's take-back, staged client-side and committed by the send:
// clicking rewind on one of your turns fills the box with that turn's
// words (the expanded line as logged -- $vars are baked, the log is
// truth) and arms the send; sending replaces the turn and everything
// after it leaves the log (truncation -- fork first if you want the
// branch kept). Until the send the log is untouched: a reload or the
// cancel drops the gesture whole. The tinted composer is the mark --
// the note under it says what the colour means and names the cut.
/** @type {?{ idx: number, drop: number, label: string }} */ let pendingRewind = null;
let entryCount = 0; // the log length the last render saw -- the send's expect
/** @returns {void} */
function syncRewind() {
const blocked = pendingRewind !== null || /** @type {HTMLTextAreaElement} */ ($('gm-input')).value.trim().length > 0;
for (const b of /** @type {NodeListOf<HTMLButtonElement>} */ ($('transcript').querySelectorAll('button.rewind-toggle'))) {
b.disabled = blocked;
// the armed confirm text holds its place until it fires or disarms
b.textContent = b.dataset.armed === '1'
? 'sure? click again to rewind here'
: (blocked ? 'to rewind delete your current input' : 'rewind');
}
$('rewind-note').hidden = pendingRewind === null;
$('gm-stack').classList.toggle('rewind-pending', pendingRewind !== null);
if (pendingRewind) {
$('rewind-note-text').textContent =
`rewind armed: sending replaces this turn and drops the ${pendingRewind.drop} entries after it -- the tinted box marks the outgoing rewrite`;
}
}
/** @param {number} idx @param {string} text @param {HTMLButtonElement} btn */
function offerRewind(idx, text, btn) {
/** @type {?ReturnType<typeof setTimeout>} */ let timer = null;
btn.addEventListener('click', () => {
if (btn.disabled) return;
if (btn.dataset.armed !== '1') {
btn.dataset.armed = '1';
syncRewind();
clearTimeout(timer ?? undefined);
timer = setTimeout(() => { btn.dataset.armed = ''; if (btn.isConnected) syncRewind(); }, 5000);
return;
}
clearTimeout(timer ?? undefined);
btn.dataset.armed = '';
// the gesture: client-side only -- the send commits it. The label
// is the first words of the turn as the note's handle on it
pendingRewind = { idx, drop: entryCount - idx, label: text.split('\n')[0].slice(0, 60) };
/** @type {HTMLTextAreaElement} */ ($('gm-input')).value = text;
renderInputHl();
syncRewind();
/** @type {HTMLTextAreaElement} */ ($('gm-input')).focus();
});
}
/** @returns {void} */
function cancelRewind() {
pendingRewind = null;
/** @type {HTMLTextAreaElement} */ ($('gm-input')).value = '';
renderInputHl();
syncRewind();
}
// her two blocks, split along the seam: how she is (the status) vs
// what she means to do (the agenda). Both render compact, mirroring
// the wire formats the model cites. The edit button stages a block
@@ -75,6 +139,8 @@ export function leave() {
export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters play with a run id
if (rawRun !== id) { rawRun = id; rawOpen = false; } // a new run starts at the table
pendingRewind = null; // the gesture belongs to the run it was staged on
entryCount = 0;
statusPane.reset();
agendaPane.reset();
theSheet.reset();
@@ -119,6 +185,9 @@ async function refreshPlay(id, seq) {
theSheet.setEditable(detail.phase === 'live');
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = false;
// a pending gesture cannot outlive the live session (a stop or a
// failed send ends the table it was staged on)
if (detail.phase !== 'live') pendingRewind = null;
$('table-tabs').hidden = true; // the tabs are the live session's
if (detail.phase === 'live') {
// the table has two faces: the curated projection (thinking never
@@ -130,12 +199,22 @@ async function refreshPlay(id, seq) {
if (rawOpen) {
/** @type {TableResponse} */ const session = await api(`/runs/${id}/session`);
if (seq !== state.seq) return;
entryCount = session.entries.length;
renderRaw(session.entries);
} else {
/** @type {TableResponse} */ const session = await api(`/runs/${id}/table`);
if (seq !== state.seq) return;
renderTranscript(session.entries, { onConflict: showConflict, onRaw: showRawEntry });
entryCount = session.entries.length;
// the rewind control rides GM turns while it may fire: a pending
// ask refuses sends anyway, so the buttons stay off until it
// resolves (the server would refuse -- the surface says so first)
renderTranscript(session.entries, {
onConflict: showConflict,
onRaw: showRawEntry,
...(detail.pendingAsk ? {} : { onRewind: offerRewind }),
});
}
syncRewind();
} else if (detail.phase === 'dormant') {
// the review window: the carryover is the preview of the next
// contwin's opening, rendered exactly as the table will hold it
@@ -145,8 +224,10 @@ async function refreshPlay(id, seq) {
if (carry && carry.entries.length) renderTranscript(carry.entries, {});
else $('transcript').appendChild(el('div', 'hint', 'nothing carries -- the next session opens on the bundle alone'));
$('transcript').prepend(dormantBar(detail, carry));
syncRewind();
} else {
$('transcript').textContent = '';
syncRewind();
}
// controls
@@ -470,8 +551,11 @@ async function sendTurn() {
// staged block edits ride the turn (the override): only the kinds
// staged attach, whole-list. The staged sheet rides the same way --
// the GM's ledger record ({} is a live empty ledger, so the null
// check, not truthiness)
/** @type {{ line: string, status?: string[], agenda?: string[], sheet?: Record<string, unknown> }} */ const body = { line };
// check, not truthiness). The pending rewind names the GM turn this
// send replaces; expect states the log this was composed against --
// a stale tab refuses before anything rides
/** @type {{ line: string, status?: string[], agenda?: string[], sheet?: Record<string, unknown>, rewind?: number, expect?: number }} */ const body = { line, expect: entryCount };
if (pendingRewind) body.rewind = pendingRewind.idx;
if (statusPane.staged) body.status = statusPane.staged;
if (agendaPane.staged) body.agenda = agendaPane.staged;
if (theSheet.staged !== null) body.sheet = theSheet.staged;
@@ -490,10 +574,16 @@ async function sendTurn() {
statusPane.clearStaged(); // sent -- the panes re-render from the scan
agendaPane.clearStaged();
theSheet.clearStaged();
pendingRewind = null; // committed -- the new log is the truth now
} catch (e) {
failed = e.message;
/** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line
renderInputHl();
// a 400 refused before anything touched the log (validation,
// expansion, a bad rewind target) -- the gesture stays armed for
// the re-send. Anything else may have moved the log: drop it and
// let the re-render show the truth
if (e.status !== 400) pendingRewind = null;
}
meterStop();
setBusy(false);
@@ -510,7 +600,7 @@ async function sendAnswer() {
meterStart();
let failed = null;
try {
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer, expect: entryCount } });
} catch (e) {
failed = e.message;
/** @type {HTMLInputElement} */ ($('ask-answer')).value = answer;
@@ -627,6 +717,11 @@ $('gm-send').addEventListener('click', sendTurn);
$('gm-input').addEventListener('keydown', (e) => {
if (e.key === ' ' && e.ctrlKey) { e.preventDefault(); sendTurn(); }
});
// text in the box blocks the rewind gesture (GM, 2026-11-17): the
// button disables and renames rather than hiding, so the affordance
// says what unlocks it. Clearing the box re-enables it
$('gm-input').addEventListener('input', syncRewind);
$('rewind-cancel').addEventListener('click', cancelRewind);
// the GM input's highlight overlay: the setup editor's stack pattern
// -- the pre behind a transparent-text textarea renders the tokens in