the state-scan round: the log is the one truth for status and agenda, the db tiers retired -- scanState (server/session.mjs) derives each kind newest-wins across her emissions (the picked variant's text), the GM's override records, and the boundary state notes; the panes, the run detail, and the stamp all read it, GET /status and detail.status are derived reads, no clerk call, no db copy; the agenda cap is a derivation rule (GM, 2026-11-16: we log all seven items on reception, but the only way to see all seven is the raw event -- at no point an over-cap list can be derived), the reception note still shows the GM what sank; the stamp renders the canonical grammar -- status comma-separated, agenda markdown bullets, matching the line the GM added to invariants; the GM's block edits are overrides (GM, 2026-11-16: mutate during the contwin composition, the logs record the overrides arriving with the GM's turn as they should, the model sees the blocks overwritten with GM's edits attached to her turn, append if empty): the pane editors STAGE (paneEditor reworked -- no save callback, staged state, pending marker, discard), the send attaches them to POST /turn, node logs the override field on the GM turn, the composition renders it as hers -- the log never mutates, her words stay verbatim, the raw surfaces show the record; OOC turns refuse edits client and server both, the out-of-band POST /status and /agenda routes retired; stop writes the boundary state note at the carry head always (the crash-reconcile filters it before comparing), the start gate's n=1 seeding is dead (her authored opening turn IS the seed, the lint keeps requiring it), continuation carryovers are writable in the file editor during dormancy -- the review window's one editing surface, blocks included, no new pane; the clerk lost the tiers wholesale (schema tables, four verbs, canon status/agenda views, dump sections, report fields; the events CHECK keeps the historical op names; old dbs keep dead tables, never read, never dropped -- Irene is hands-off, and by the same day's ruling she is broken and never runs again: logs and db kept as they are, no replay, no continuation, no compatibility designed for her); Chloe hand-migrated to the new protocol -- her most recent turn carries the whole-list blocks applied from her db's exact values, her next context stamps them, her older lost/gained tags stay as history; the mock's agenda blocks went bullet, a new script position for the override turn's reply restates the mind so the boundary assert holds; smoke reworked to the scan battery (+ the 10f override block: the record rides its turn, the composition stamps at her canon point, the log keeps her emission verbatim, the OOC refusal, the boundary note at the carry head, the retired routes 404) -- ALL PASS; restart + reminder + repo checks green; the browser pass caught and fixed two real bugs (the pending marker's display:flex beat the hidden attribute -- any display rule needs a [hidden] override; setEditable(true) never ran the widget sync so the edit button stayed hidden) and proved the whole UX end to end with zero console errors -- staging, send-with-turn, the machinery lines on the table and raw, the OOC gate banner, discard, dormant read-only panes, the boundary note in the dormant preview; typecheck green on both programs; README/DICTIONARY carry the single-truth design, HANDOFF the round record and the Irene rewording, AGENTS the state pointer and the browser lessons
This commit is contained in:
@@ -137,6 +137,46 @@ memory the agent owes itself across sessions.
|
||||
|
||||
## State pointers
|
||||
|
||||
- **The state-scan round is BUILT (2026-11-16, evening): the log is
|
||||
the one truth for status and agenda, the db tiers are retired.**
|
||||
scanState (server/session.mjs) derives each kind newest-wins
|
||||
across her emissions (the picked variant's text), the GM's
|
||||
override fields, and the boundary state notes; the panes, the run
|
||||
detail, and the stamp all read it (GET /status and detail.status
|
||||
are derived reads; no clerk call). The cap is a derivation rule:
|
||||
an over-cap agenda is never derivable anywhere, the raw log is
|
||||
the only place her seven items live, the reception note still
|
||||
shows the GM what sank. The stamp renders canonical formats:
|
||||
status comma-separated, agenda markdown bullets (the grammar
|
||||
invariants teaches -- the GM added the line themselves). The GM's
|
||||
block edits are overrides: the pane editors STAGE (paneEditor
|
||||
reworked -- no save callback, staged state + pending marker +
|
||||
discard), the send attaches them to POST /turn, node logs the
|
||||
override field on the GM turn (the log never mutates -- GM,
|
||||
2026-11-16: "mutate during the contwin composition... the model
|
||||
sees the blocks overwritten with GM's edits attached to her
|
||||
turn"; append-if-empty; OOC turns refuse edits, client and
|
||||
server both). stop writes the state note at the carry head
|
||||
always (the resume-reconcile filters it out before comparing);
|
||||
the start gate's n=1 seeding is dead (her authored opening turn
|
||||
IS the seed); continuation carryovers are rw in the file editor
|
||||
during dormancy (the save lint unchanged). The clerk lost the
|
||||
status/agenda tiers wholesale (schema, four verbs, canon views,
|
||||
dump sections, report fields; the events CHECK keeps the
|
||||
historical op names; old dbs keep dead tables, never read, never
|
||||
dropped -- Irene is hands-off). Chloe is MIGRATED: her last turn
|
||||
carries the whole-list blocks hand-applied from her db's values
|
||||
(the db's now-dead tables agreed at cutover by construction).
|
||||
Browser lessons of the round: a CSS display rule on a class
|
||||
BEATS the hidden attribute (the pending marker showed un-staged
|
||||
-- .pane-pending[hidden] { display: none } is the fix, and any
|
||||
widget that uses hidden + a display rule needs the [hidden]
|
||||
override); a widget whose sync() runs on only some paths drifts
|
||||
(setEditable(true) never synced -- always run the full sync,
|
||||
unconditionally); the SPA is served with no cache headers, so
|
||||
the browser heuristically caches ES modules across reloads --
|
||||
after editing web/ warm them with fetch(url, {cache:'reload'})
|
||||
from evaluate before judging the page stale or fresh.
|
||||
- **The 2026-11-16 rounds are built and live-proven: the
|
||||
play-protocol batch and model discovery.** The protocol batch: OOC
|
||||
GM turns (paren-led, post-expansion) carry no status/agenda blocks;
|
||||
@@ -318,19 +358,13 @@ memory the agent owes itself across sessions.
|
||||
by the agenda (DECISIONS #32/#33). **Verbosity**: completions
|
||||
lengthened 103 -> 668 chars across session one; the per-turn reminder
|
||||
is the countermeasure now built -- the next live session is the test.
|
||||
**Irene is retired to calibration (GM, 2026-11-15): her run
|
||||
(4f261452) is never continued -- it survives untouched as
|
||||
calibration material, and a NEW run becomes the live story: the
|
||||
memory test and the first real housekeeping pass start there.**
|
||||
The hand-stamp still matters -- story-only reads mean an ownerless
|
||||
Irene is unreadable past her story surface, so stamping her owner
|
||||
(the op's one-time act, HANDOFF step 1) is her calibration access.
|
||||
Her frozen session-1 bundle keeps its old handbook copy: an
|
||||
artifact now, hands off. The stamp is DONE for the debug identity
|
||||
(2026-11-16, GM): run.json carries owner "debug" -- full surface
|
||||
under --debug, ownerless again in normal mode (the id never
|
||||
resolves against a real users table) until a real-id re-stamp,
|
||||
which is optional and can wait.
|
||||
**Irene is broken and never runs again (GM, 2026-11-16, superseding
|
||||
the calibration retirement): her run (4f261452) is kept exactly as
|
||||
it is -- logs and db untouched, no replay, no continuation, no
|
||||
compatibility designed for her. Reading her files on disk (the
|
||||
calibration comparisons) is all that's left; the hand-stamp talk
|
||||
is moot.** Her frozen session-1 bundle keeps its old handbook
|
||||
copy: an artifact now, hands off.
|
||||
**Replay-after-housekeeping is dead** (found in the SPA round) --
|
||||
RESOLVED BY PLAN (2026-11-15): the dormant-session rework kills
|
||||
the autorestart, and during dormancy the latest log IS the
|
||||
|
||||
+18
-8
@@ -128,14 +128,23 @@ WORDS.
|
||||
the three-part gate (non-normal, acute, turn-affecting). Hers to
|
||||
write: the whole-list `<status>` block in her own turns (the
|
||||
full-block protocol -- absent means unchanged, never blank),
|
||||
stamped at her most recent turn's tail in the view; entirely
|
||||
hers -- the housekeeper never writes it, the GM's override is
|
||||
model-invisible. Renamed from "paper" -- see Ruled renames.
|
||||
stamped at her most recent turn's tail in the view. The log is
|
||||
the one truth (the state scan derives it; no db holds a copy) --
|
||||
entirely hers to write, the housekeeper never touches it, and the
|
||||
GM's override composes as if she had stated it (the model never
|
||||
sees an override as an act, only as state). Renamed from "paper"
|
||||
-- see Ruled renames.
|
||||
- **the agenda** -- her second self-kept block: intentions -- what she
|
||||
means to do -- in a cap-5 recency queue. The whole-list `<agenda>`
|
||||
block in her own turns; over-cap evicts from the bottom silently
|
||||
(ruled a feature); disposable by design. The seam with the
|
||||
means to do -- in a cap-5 recency queue (markdown bullets; the
|
||||
full-list lives only in the log -- an over-cap list is never
|
||||
derivable, ruled a feature). The whole-list `<agenda>` block in
|
||||
her own turns; disposable by design. The seam with the
|
||||
status: how she is vs what she means to do.
|
||||
- **the override** -- the GM's block edit: staged in a pane, it rides
|
||||
the next non-OOC GM turn as a record on it, and the composition
|
||||
renders it as if she had stated it -- mutated in place at her
|
||||
newest blocks. The log keeps her words verbatim; the raw surfaces
|
||||
show the record; the model sees only state.
|
||||
- **records** -- her files: the card index, the ledger, whatever she
|
||||
keeps. Diegetic and per-run (the settings gate); narrow query,
|
||||
hard cap 10 in the tool; a miss is a miss. Filed at her desk by
|
||||
@@ -238,8 +247,9 @@ WORDS.
|
||||
operations exactly.
|
||||
- **the view** -- the rendered live context under policy: thinking
|
||||
never goes back; old tool results elide to stubs (ask_gm answers
|
||||
never); old status and agenda blocks elide; the current status and
|
||||
agenda ride every GM turn; one live reminder at the freshest end.
|
||||
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.
|
||||
|
||||
## Conventions the words lean on
|
||||
|
||||
|
||||
+57
-34
@@ -46,7 +46,24 @@ file is the "where did we leave off" map.
|
||||
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). The design record lives in README /
|
||||
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. 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
|
||||
@@ -56,30 +73,27 @@ file is the "where did we leave off" map.
|
||||
the project record -- the desktop UI cannot delete or repoint
|
||||
projects, anomalyco/opencode#28030). Launch sessions from the new
|
||||
path.
|
||||
- **The first real story is live: "La Caramba / Irene"** (run
|
||||
4f261452, gitignored state). Session one open, 53 GM + 53 player
|
||||
story turns, ~23K prompt tokens -- single-digit percent of the
|
||||
contwin. She is migrated to the new session layout (2026-11-15,
|
||||
hand-migration per the ruling: fork proven end to end first, then
|
||||
real her, zero writes to her log); her historical turn-0 event
|
||||
stays GM-attributed, and her dead authored files (turn-0.md,
|
||||
seed.json) sit in `sessions/1/` as inert archival -- whether they
|
||||
stay is the GM's call. She is ownerless until the op's hand-stamp
|
||||
(step 1). RETIRED TO CALIBRATION (GM, 2026-11-15): never
|
||||
continued, survives untouched as calibration material -- her open
|
||||
session keeps its old handbook copy as an artifact, and the clean
|
||||
reminder/agenda experiment starts on a fresh run instead.
|
||||
- **The housekeeping dry-run ran on her once:** works mechanically,
|
||||
output not yet as expected -- the housekeeper.md review is pending
|
||||
(step 3), and the GM has not read the prompt yet.
|
||||
- **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). Her first stop carries the first real
|
||||
housekeeping pass and the slidwin test (step 2).
|
||||
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
|
||||
@@ -121,29 +135,27 @@ file is the "where did we leave off" map.
|
||||
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. Irene's stamp is DONE for the debug
|
||||
identity (2026-11-16); re-stamping her run.json with the real
|
||||
user id is optional -- without it she reads ownerless (story
|
||||
only) in normal mode. No migration code exists, by ruling.
|
||||
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 status 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, and
|
||||
her session-one delta tags ride the carry as history (the view
|
||||
leaves them, the story strips them). Irene is hands-off
|
||||
calibration material: read her, replay against her if wanted
|
||||
(owner-only, spends a call), never continue her.
|
||||
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.
|
||||
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 full-block protocol) and #14 (turn
|
||||
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;
|
||||
@@ -151,7 +163,10 @@ file is the "where did we leave off" map.
|
||||
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>`.
|
||||
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.
|
||||
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
|
||||
@@ -171,7 +186,15 @@ file is the "where did we leave off" map.
|
||||
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.
|
||||
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),
|
||||
|
||||
@@ -152,8 +152,9 @@ consumes into the log, in one action.
|
||||
one JSON event per line, the same format every session's carryover
|
||||
uses. `{"t":"msg","m":{"role":"assistant","content":"..."}}` is one
|
||||
of her turns, `{"t":"msg","m":{"role":"user","content":"..."}}` is
|
||||
one of yours, `{"t":"opening","status":["..."]}` is her opening
|
||||
status (at most one). End it however you want the game to open: on
|
||||
one of yours, and her opening status rides her own last turn as a
|
||||
`<status>` block (the opening event is retired; old carryovers keep
|
||||
theirs as inert history). End it however you want the game to open: on
|
||||
her turn the table waits for your input, on your turn start sends
|
||||
it automatically as her cue. Start lints it -- only clean openings
|
||||
go live.
|
||||
@@ -215,9 +216,10 @@ consumes into the log, in one action.
|
||||
material: raw log events, expanded at start when authored
|
||||
(session one's), never expanded when carried (live prose) -- and
|
||||
a carryover ending on a GM turn is sent automatically as her cue.
|
||||
In play the current status rides every in-character GM turn
|
||||
the same way (the per-turn ride lands with the server; an OOC GM
|
||||
turn carries none). (On a tight
|
||||
In play the turn reminder rides every GM turn the same way (its
|
||||
own system chunk, one live copy in the view; her status and
|
||||
agenda never ride GM turns -- they stamp at her own tail). (On a
|
||||
tight
|
||||
session, ring B is optional loading -- ring A is the spine.)
|
||||
Substitution has two classes: `@PC` (her name) and `@Package` (the
|
||||
display name) are identity sigils resolved from the run's
|
||||
@@ -244,18 +246,25 @@ consumes into the log, in one action.
|
||||
protocol, 2026-11-16): the player emits whole `<status>` and
|
||||
`<agenda>` blocks in its own turns -- a present block is a
|
||||
whole-list SET (a present-but-empty one is a deliberate clear),
|
||||
an absent block means unchanged, never blank. The view strips
|
||||
every copy and stamps the newest value of each kind at the tail
|
||||
of her most recent turn, exactly where she left it: the status
|
||||
is the game world as of her turn -- the canon point -- and the
|
||||
context reads as the same sequence of events the game had. An
|
||||
over-cap agenda evicts from the bottom silently (ruled a
|
||||
feature: immersive, human-like, fun chaos -- silent to her, the
|
||||
note shows the GM what sank). GM prose goes pure: no blocks ride
|
||||
any turn, old logs' composited rides strip (they were never GM
|
||||
words), and the GM's pane/CLI sets are model-invisible -- the
|
||||
compositing that once showed them was a side-effect, not a
|
||||
purpose; the GM's lever is narrative. The mind verb rides the
|
||||
an absent block means unchanged, never blank. The log is the one
|
||||
truth: the state scan derives each kind newest-wins across her
|
||||
emissions, the GM's override records, and the boundary state
|
||||
note -- the panes, the run detail, and the stamp all read it,
|
||||
no db holds a copy. The view strips every copy and stamps the
|
||||
derived value of each kind at the tail of her most recent turn,
|
||||
exactly where she left it: the status is the game world as of
|
||||
her turn -- the canon point -- and the context reads as the same
|
||||
sequence of events the game had. An over-cap agenda is never
|
||||
derivable (the scan caps every derivation at the top five; the
|
||||
log keeps her full list, and the note shows the GM what sank --
|
||||
ruled a feature: immersive, human-like, fun chaos). GM prose
|
||||
goes pure: no blocks ride any turn, old logs' composited rides
|
||||
strip (they were never GM words). The GM's block edits are
|
||||
overrides: the pane editors stage them, they ride the next
|
||||
non-OOC GM turn as a record on it, and the composition renders
|
||||
them as if she had stated them -- mutated in place at her
|
||||
newest blocks, invisible to the model as an act, visible only
|
||||
as state. 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
|
||||
@@ -327,8 +336,8 @@ Memory is **seven tiers**:
|
||||
|---|---|---|---|
|
||||
| **backdrop** | the world as everyone knows it -- public knowledge, the general setting; never memory, never forgotten | always | GM, rarely (retcons) |
|
||||
| **identity** | the character sheet -- concept, drives, skills, voice; changes rarely | always | GM, rarely; housekeeper may propose via open questions; blanks are the player's to invent |
|
||||
| **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 newest of her whole-list `<status>` blocks | **the player** (whole-list `<status>` block in its turns; absent = unchanged); GM override out-of-band, model-invisible |
|
||||
| **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 newest of her whole-list `<agenda>` blocks | **the player** (whole-list `<agenda>` block in its turns; over-cap evicts silently); GM override out-of-band, model-invisible |
|
||||
| **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 |
|
||||
| **cold** | forgotten or vetoed | never -- not even queryable | GM only (`revive`) |
|
||||
@@ -499,8 +508,8 @@ JSON. Boot-rebuilds open sessions from the session logs on start; the
|
||||
append-only jsonl is the truth, the live context is a view under
|
||||
policy (thinking never goes back, old tool results elide to stubs --
|
||||
ask_gm answers never do, a ruling must not vanish -- old GM-side
|
||||
status blocks elide, the current status rides every in-character
|
||||
GM turn).
|
||||
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
|
||||
@@ -632,9 +641,9 @@ names-female.txt the name dictionary -- one name per line; the new-run
|
||||
tool/
|
||||
memory.mjs the clerk: packages, runs, create, save-package, init,
|
||||
render, apply, insert, delete, revive, file,
|
||||
amend, discard, search, unarchive, status,
|
||||
status-set, agenda,
|
||||
agenda-set, pick, dump, restore, report
|
||||
amend, discard, search, unarchive, pick, dump,
|
||||
restore, report (her status and agenda never lived
|
||||
here in the end -- the log is their one truth)
|
||||
(--run <id>; --session <n> addresses one session,
|
||||
defaulting to the active -- the live one, else the
|
||||
latest; --owner stamps a run's owner; --gm for
|
||||
@@ -758,7 +767,9 @@ test/ the mock smoke, kept next to the code
|
||||
server.example.json copy to server.json (gitignored) -- bind, endpoint +
|
||||
key env, models, contwin, params passthrough
|
||||
db/
|
||||
schema.sql entries, records, status, agenda, events journal (shared)
|
||||
schema.sql entries, records, events journal (shared; the status
|
||||
and agenda tables are retired -- the log is their
|
||||
one truth, old runs keep dead tables, never read)
|
||||
state/ per-deployment people + shared packages (gitignored):
|
||||
deployment.db (users, invites), bootstrap-invite.txt,
|
||||
models.json (the discovered registry -- the truth of
|
||||
|
||||
+10
-28
@@ -27,37 +27,19 @@ CREATE TABLE IF NOT EXISTS records (
|
||||
created TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- her status: freeform descriptions of her immediate
|
||||
-- situation, admitted by the three-part gate (non-normal, acute,
|
||||
-- turn-affecting). No keys, no baselines -- just what's true right now.
|
||||
-- the player mutates it with <lost>/<gained> deltas (exact match);
|
||||
-- the GM overrides out-of-band. Descriptions never contain commas:
|
||||
-- both the delta lists and the <status> block are comma-separated.
|
||||
CREATE TABLE IF NOT EXISTS status (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
descr TEXT NOT NULL UNIQUE,
|
||||
added TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- her agenda: the hot queue of what drives her -- intentions, not
|
||||
-- states (those live in her status). Id order IS queue order:
|
||||
-- newest-added at the top, the bottom evicted on overflow -- a recency
|
||||
-- ring buffer for free. The player mutates it with <add>/<drop>
|
||||
-- deltas (comma-separated adds, index-based drops); the GM overrides
|
||||
-- with agenda-set. Items never contain commas: the add transport is
|
||||
-- comma-separated, same as the status descriptions.
|
||||
CREATE TABLE IF NOT EXISTS agenda (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
descr TEXT NOT NULL UNIQUE,
|
||||
added TEXT NOT NULL
|
||||
);
|
||||
-- her status and agenda lived here once (the paper model's runtime
|
||||
-- half). Retired 2026-11-16: the log is the one truth -- the state
|
||||
-- scan reads her blocks, and no db table holds a copy. Old runs keep
|
||||
-- their dead tables on disk, never read, never dropped (Irene is
|
||||
-- hands-off; dumps tolerate their presence, restore skips what the
|
||||
-- schema lacks).
|
||||
|
||||
-- append-only audit journal; nothing here is ever updated or deleted.
|
||||
-- target is 'e<id>' for entries, 'r<id>' for records, 'p<id>' for status
|
||||
-- rows, 'p' for whole-status replaces.
|
||||
-- target is 'e<id>' for entries, 'r<id>' for records.
|
||||
-- prior captures the replaced state of a journaled mutator (the saga
|
||||
-- rule): amend/discard carry the old record content, status ops carry
|
||||
-- what was lost -- so turn surgery can compensate mechanically.
|
||||
-- rule): amend/discard carry the old record content -- so turn
|
||||
-- surgery can compensate mechanically. The status/agenda op names
|
||||
-- stay in the CHECK for the historical journals that used them.
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session TEXT NOT NULL,
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@ from memory. For contrast, "suspicious" is a status token when your character do
|
||||
|
||||
A similar `<agenda>` block has the same lifecycle, but different purpose. Instead of the current situation, it should hold goals that your
|
||||
character is working towards right now. This isn't a storage space for detailed plans, it's the hot view of what drives the character.
|
||||
The goals may be long term, but they should represent what's currently on the mind.
|
||||
The goals may be long term, but they should represent what's currently on the mind. The block format is a markdown bullet list.
|
||||
|
||||
The list is a fixed size ordered ring buffer that's intentionally tiny. If you add a new item on the full agenda, the last one gets evicted.
|
||||
New items arrive at the top, imitating recency bias. The items form a queue ("First buy groceries, then make dinner."). You can reorder items.
|
||||
|
||||
@@ -256,10 +256,11 @@ export { callHousekeeper };
|
||||
// manifests). model, when given, is the pass's model -- the apply
|
||||
// log names it (a hand apply has none). The rebase is the
|
||||
// re-enterability: every run starts
|
||||
// from a fresh copy of the finished session's frozen db (her status
|
||||
// and agenda carry; the rings reset to the base the manifest lands
|
||||
// on) -- so re-runs never double-apply, and hand edits made in
|
||||
// between are overwritten, ruled fine.
|
||||
// from a fresh copy of the finished session's frozen db (the rings
|
||||
// carry, the manifest lands on them; her status and agenda never
|
||||
// lived here -- the log is their one truth) -- so re-runs never
|
||||
// double-apply, and hand edits made in between are overwritten,
|
||||
// ruled fine.
|
||||
/** @param {string} runId @param {string} manifestPath @param {number} n @param {?string} [model] */
|
||||
export function applyToDormant(runId, manifestPath, n, model = null) {
|
||||
const target = sessionDir(runId, n + 1);
|
||||
|
||||
+42
-28
@@ -6,25 +6,26 @@
|
||||
// answer call resumes the loop. GM prose goes pure (the full-block
|
||||
// protocol, GM 2026-11-16): no cache blocks ride any turn -- her
|
||||
// <status>/<agenda>/<mind> blocks ride at her own tail, the view
|
||||
// stamps the newest of each kind at her most recent turn, and the
|
||||
// clerk holds the one truth for the panes. The player's present
|
||||
// blocks are whole-list SETs (absent means unchanged, never blank);
|
||||
// conflicts (a refused <mind>, an emitted <model>) ride the
|
||||
// self-heal channel. GM input expands at ingestion (strict,
|
||||
// DECISIONS #9): @PC/@Package and $vars resolve before the line is
|
||||
// logged; an expansion error refuses the turn and the line is handed
|
||||
// back for editing. Every provider request records its resolved
|
||||
// model and effective params on the resulting msg event (via); a
|
||||
// failed call lands a req event with the failure -- the turn still
|
||||
// fails loud.
|
||||
// stamps the scan's newest values at her most recent turn, and the
|
||||
// log is the one truth (the state scan -- the db holds no copy). A
|
||||
// GM block edit rides its GM turn as the override record; the
|
||||
// composition overwrites her newest blocks with it, the log keeps
|
||||
// her words verbatim. The player's present blocks are whole-list
|
||||
// SETs (absent means unchanged, never blank); conflicts (a refused
|
||||
// <mind>, an emitted <model>) ride the self-heal channel. GM input
|
||||
// expands at ingestion (strict, DECISIONS #9): @PC/@Package and
|
||||
// $vars resolve before the line is logged; an expansion error
|
||||
// refuses the turn and the line is handed back for editing. Every
|
||||
// provider request records its resolved model and effective params
|
||||
// on the resulting msg event (via); a failed call lands a req event
|
||||
// with the failure -- the turn still fails loud.
|
||||
/** @typedef {import('./shapes.mjs').Ctx} Ctx */
|
||||
/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */
|
||||
/** @typedef {import('./shapes.mjs').Actor} Actor */
|
||||
/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */
|
||||
|
||||
import { clerkJson } from './clerk.mjs';
|
||||
import { toolList, runTool, assembleReminder, expandVars } from './bundle.mjs';
|
||||
import { renderView, blockList } from './session.mjs';
|
||||
import { renderView, cleanBlockList, AGENDA_CAP } from './session.mjs';
|
||||
import { parseVariants, pickVariant } from './variants.mjs';
|
||||
import { registry, usable } from './discovery.mjs';
|
||||
|
||||
@@ -51,9 +52,10 @@ function needSession(ctx, runId) {
|
||||
|
||||
/**
|
||||
* @param {Ctx} ctx @param {string} runId @param {string} line @param {?Actor} user
|
||||
* @param {?{ status?: string[], agenda?: string[] }} [override]
|
||||
* @returns {Promise<TurnOut>}
|
||||
*/
|
||||
export async function gmTurn(ctx, runId, line, user) {
|
||||
export async function gmTurn(ctx, runId, line, user, override = null) {
|
||||
const s = needSession(ctx, runId);
|
||||
if (s.pendingAsk) throw new HttpError(409, 'a question is pending -- answer it first (POST /ask)');
|
||||
// GM-input expansion (strict, DECISIONS #9): the line resolves at
|
||||
@@ -66,10 +68,11 @@ export async function gmTurn(ctx, runId, line, user) {
|
||||
} catch (e) {
|
||||
throw new HttpError(400, `the line was not sent -- ${e.message}`);
|
||||
}
|
||||
// GM prose goes pure: no cache blocks ride any turn. Her blocks
|
||||
// stamp at her own tail in the view (renderView); the clerk holds
|
||||
// the one truth for the panes
|
||||
s.append({ t: 'msg', m: { role: 'user', content: prose } });
|
||||
// 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
|
||||
// it newest-wins), the log keeps her words verbatim
|
||||
s.append({ t: 'msg', m: { role: 'user', content: prose }, ...(override ? { override } : {}) });
|
||||
// the reminder follows the GM's prose as its own system chunk --
|
||||
// every turn, one live copy (older ones elide in the view)
|
||||
const reminder = assembleReminder(runId);
|
||||
@@ -203,16 +206,20 @@ async function runLoop(ctx, runId, user) {
|
||||
// for variant literature). The full-block protocol (GM,
|
||||
// 2026-11-16): a present block is a whole-list SET -- absent
|
||||
// means unchanged, never blank; a present-but-empty block is a
|
||||
// deliberate clear. Same-verb blocks combine into one set.
|
||||
// deliberate clear. Same-verb blocks combine into one set. No
|
||||
// apply happens -- the log is the truth; the notes are the GM's
|
||||
// receipt and the housekeeper's reading, the derivation is the
|
||||
// scan's (its clean, its cap)
|
||||
const carry = [];
|
||||
if (/<status>/.test(text)) {
|
||||
const set = clerkJson(runId, 'status-set', ...blockList(text, 'status'));
|
||||
s.append({ t: 'note', kind: 'status', set });
|
||||
s.append({ t: 'note', kind: 'status', set: cleanBlockList(text, 'status') });
|
||||
}
|
||||
if (/<agenda>/.test(text)) {
|
||||
const r = clerkJson(runId, 'agenda-set', ...blockList(text, 'agenda'));
|
||||
// the eviction is silent to her, visible to the GM (the note)
|
||||
s.append({ t: 'note', kind: 'agenda', set: r.set, evicted: r.evicted });
|
||||
const items = cleanBlockList(text, 'agenda');
|
||||
// the cap is a derivation rule: the log keeps all her items,
|
||||
// every derived surface shows the top five. The eviction is
|
||||
// silent to her, visible to the GM (the note)
|
||||
s.append({ t: 'note', kind: 'agenda', set: items.slice(0, AGENDA_CAP), evicted: items.slice(AGENDA_CAP) });
|
||||
}
|
||||
// the mind verb: parse now so a refused statement heals in-turn
|
||||
// like any conflict; the stash itself lands only at the completing
|
||||
@@ -383,7 +390,8 @@ export { parseMind };
|
||||
// whole-list status and agenda sets, then a restated agenda, an
|
||||
// over-cap agenda with a valid mind, the <model> guard and its
|
||||
// plain-prose heal, an out-of-bounds mind and its restating heal,
|
||||
// and everything after is plain prose.
|
||||
// the GM-override turn's reply (no blocks, the mind restated), and
|
||||
// everything after is plain prose.
|
||||
/** @typedef {import('./shapes.mjs').WireMessage} WireMessage */
|
||||
|
||||
/**
|
||||
@@ -416,16 +424,16 @@ function mockModel(s, view) {
|
||||
}
|
||||
if (count === 2 && toolResults >= 1) {
|
||||
// the full-block protocol: whole-list sets
|
||||
return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\n<status>cuffed, belted, naked, barefoot, settled, curious about the clicking</status>\n<agenda>find fresh water\nsignal any passing ship\nbuild a shelter</agenda>' };
|
||||
return { role: 'assistant', content: 'Mock: good to know. *She exhales and lets her shoulders drop.*\n<status>cuffed, belted, naked, barefoot, settled, curious about the clicking</status>\n<agenda>\n- find fresh water\n- signal any passing ship\n- build a shelter\n</agenda>' };
|
||||
}
|
||||
if (count === 3) {
|
||||
// a restated agenda replaces the list (the first item is done)
|
||||
return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n<agenda>signal any passing ship\nbuild a shelter</agenda>' };
|
||||
return { role: 'assistant', content: 'Mock: *She settles on the first task and starts walking.*\n<agenda>\n- signal any passing ship\n- build a shelter\n</agenda>' };
|
||||
}
|
||||
if (count === 4) {
|
||||
// an over-cap agenda evicts from the bottom, silently; a valid
|
||||
// mind rides the same turn
|
||||
return { role: 'assistant', content: 'Mock: *Her thoughts race ahead of her feet.*\n<agenda>item one\nitem two\nitem three\nitem four\nitem five\nitem six\nitem seven</agenda>\n<mind>{"temperature": 1.2}</mind>' };
|
||||
return { role: 'assistant', content: 'Mock: *Her thoughts race ahead of her feet.*\n<agenda>\n- item one\n- item two\n- item three\n- item four\n- item five\n- item six\n- item seven\n</agenda>\n<mind>{"temperature": 1.2}</mind>' };
|
||||
}
|
||||
if (count === 5) {
|
||||
// the <model> block is display-only: the guard conflicts
|
||||
@@ -444,5 +452,11 @@ function mockModel(s, view) {
|
||||
// last word of the session, so it rides the boundary unconsumed)
|
||||
return { role: 'assistant', content: 'Mock: *She breathes until the numbers behave.*\n<mind>{"temperature": 1.2}</mind>' };
|
||||
}
|
||||
if (count === 9) {
|
||||
// the GM-override turn's reply: no blocks (the override stands as
|
||||
// the newest word), the mind restated so it rides the boundary
|
||||
// unconsumed
|
||||
return { role: 'assistant', content: 'Mock: *She nods to herself and settles in.*\n<mind>{"temperature": 1.2}</mind>' };
|
||||
}
|
||||
return { role: 'assistant', content: 'Mock: *She watches the water and waits for the world to move.*' };
|
||||
}
|
||||
|
||||
+70
-49
@@ -59,8 +59,8 @@ const ctx = /** @type {Ctx} */ (ctxBase);
|
||||
// Serializes every async mutation span (turn, ask, start, the
|
||||
// housekeeping job, fork) so a fork can never torn-copy mid-turn and
|
||||
// two concurrent turns can never interleave across their awaits.
|
||||
// Sync-only handlers (status-set, file writes) need no lock: they
|
||||
// block the event loop and are atomic by construction.
|
||||
// Sync-only handlers (file writes) need no lock: they block the
|
||||
// event loop and are atomic by construction.
|
||||
ctx.locks = new Map();
|
||||
ctx.enqueue = (runId, fn) => {
|
||||
const prev = ctx.locks.get(runId) ?? Promise.resolve();
|
||||
@@ -441,6 +441,7 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
|
||||
const id = params.id;
|
||||
requireOwner(user, id); // the table's face: panes, meter, phase -- the owner's
|
||||
const st = clerkJson(id, '--json', 'report');
|
||||
const state = derivedState(id); // the log's truth, not the db's
|
||||
const s = ctx.sessions.get(id);
|
||||
const meta = bundle.runMeta(id);
|
||||
const owner = resolveOwner(meta?.owner);
|
||||
@@ -470,8 +471,8 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
|
||||
sessions: latest ?? 0,
|
||||
draft: phase === 'dormant' && latest === 1, // a never-started run
|
||||
ready: sm.ready ?? null,
|
||||
status: st.status,
|
||||
agenda: st.agenda,
|
||||
status: state.status,
|
||||
agenda: state.agenda,
|
||||
records: st.records,
|
||||
fill: st.rings,
|
||||
events: st.events,
|
||||
@@ -490,10 +491,11 @@ route('GET', '/api/runs/:id', async ({ params, user }) => {
|
||||
// A fixed whitelist, not a path API: state dirs are the clerk's
|
||||
// alone. The ADDRESSED session is the live one while one plays, else
|
||||
// the latest (the dormant one during the review window). Its bundle
|
||||
// (the frozen craft) is writable only while dormant; the authored
|
||||
// carryover of session one is authoring material (writable), a
|
||||
// continuation carryover is conversation (read-only until the editor
|
||||
// task); memory.json is the draft's starting memories -- authored
|
||||
// (the frozen craft) is writable only while dormant; the carryover
|
||||
// is the review window's one editing surface (an authored opening
|
||||
// and a continuation alike -- GM edits during dormancy show on the
|
||||
// story's live edge, and a block edit there is a hand override);
|
||||
// memory.json is the draft's starting memories -- authored
|
||||
// material while the run is a draft (the start gate applies it),
|
||||
// provenance after. housekeeper.md is substrate-internal (repo-fed
|
||||
// at housekeeping, never copied, not exposed here) and gm.md lives
|
||||
@@ -518,7 +520,7 @@ function fileSurface(runId) {
|
||||
'handbook.md': { mode: rw, path: path.join(dir, 'bundle', 'handbook.md') },
|
||||
'backdrop.md': { mode: rw, path: path.join(dir, 'bundle', 'backdrop.md') },
|
||||
'character.md': { mode: rw, path: path.join(dir, 'bundle', 'character.md') },
|
||||
'carryover.jsonl': { mode: dormant && n === 1 ? 'rw' : 'ro', path: path.join(dir, 'carryover.jsonl') },
|
||||
'carryover.jsonl': { mode: rw, path: path.join(dir, 'carryover.jsonl') }, // the review window's one editing surface (blocks included)
|
||||
'memory.json': { mode: dormant && n === 1 ? 'rw' : 'ro', path: path.join(dir, 'memory.json') }, // the draft's starting memories; the start gate applies them
|
||||
'settings.json': { mode: 'ro', path: path.join(root, 'settings.json') },
|
||||
'run.json': { mode: 'ro', path: path.join(root, 'run.json') },
|
||||
@@ -883,11 +885,39 @@ route('GET', '/api/runs/:id/story', async ({ params }) => {
|
||||
return { run: params.id, display: bundle.runDisplay(params.id), owner, ownerName: owner == null ? null : userName(owner), sessions };
|
||||
});
|
||||
|
||||
// a block edit rides its turn (the pane editors stage their lists
|
||||
// client-side and the send attaches them): only the kinds sent are
|
||||
// overridden, whole-list. Descriptions never contain commas -- the
|
||||
// transport is comma-separated -- so a comma inside an item is a
|
||||
// 400, not a silent split in every later parse.
|
||||
/** @param {Record<string, unknown>} body @returns {?{ status?: string[], agenda?: string[] }} */
|
||||
function readOverride(body) {
|
||||
/** @type {?{ status?: string[], agenda?: string[] }} */ let override = null;
|
||||
for (const kind of ['status', 'agenda']) {
|
||||
const items = body[kind];
|
||||
if (items === undefined || items === null) continue;
|
||||
if (!Array.isArray(items)) throw new HttpError(400, `${kind} (an array of descriptions) is required -- an empty array clears it`);
|
||||
for (const it of items) {
|
||||
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, `every ${kind} item must be a non-empty string`);
|
||||
if (it.includes(',')) throw new HttpError(400, `${kind} items never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
|
||||
}
|
||||
const clean = items.map((it) => String(it).trim());
|
||||
if (override === null) override = {};
|
||||
if (kind === 'status') override.status = clean;
|
||||
else override.agenda = clean;
|
||||
}
|
||||
return override;
|
||||
}
|
||||
|
||||
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');
|
||||
const override = readOverride(body);
|
||||
if (override && line.startsWith('(')) {
|
||||
throw new HttpError(400, 'a block edit cannot ride an OOC turn -- overrides arrive with a non-OOC GM turn');
|
||||
}
|
||||
requireOwner(user, params.id);
|
||||
return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user))) };
|
||||
return { ok: true, ...(await ctx.enqueue(params.id, async () => gmTurn(ctx, params.id, line, user, override))) };
|
||||
});
|
||||
|
||||
route('POST', '/api/runs/:id/ask', async ({ params, body, user }) => {
|
||||
@@ -907,47 +937,38 @@ route('POST', '/api/runs/:id/fork', async ({ params, user }) => {
|
||||
return ctx.enqueue(params.id, async () => forkRun(ctx, params.id, u));
|
||||
});
|
||||
|
||||
// the state read: the log is the one truth (the state scan -- the
|
||||
// db holds no copy). The latest session's log is the whole story
|
||||
// since its start; during dormancy the carryover is the live edge
|
||||
// and rides along. A run with no sessions derives nothing.
|
||||
/** @param {string} runId @returns {{ status: string[], agenda: string[] }} */
|
||||
function derivedState(runId) {
|
||||
const live = ctx.sessions.get(runId);
|
||||
const latest = session.latestSession(runId);
|
||||
if (latest == null) return { status: [], agenda: [] };
|
||||
const n = live?.n ?? latest;
|
||||
const dir = session.sessionDir(runId, n);
|
||||
/** @type {import('./shapes.mjs').LogEvent[]} */ const lines = [];
|
||||
/** @param {string} p @returns {import('./shapes.mjs').LogEvent[]} */
|
||||
const readJsonl = (p) => fs.existsSync(p)
|
||||
? fs.readFileSync(p, 'utf8').split('\n').filter((l) => l.trim())
|
||||
.map((l) => /** @type {import('./shapes.mjs').LogEvent} */ (JSON.parse(l)))
|
||||
: [];
|
||||
if (live) {
|
||||
lines.push(...live.lines);
|
||||
} else {
|
||||
lines.push(...readJsonl(path.join(dir, 'log.jsonl')));
|
||||
if (session.sessionMeta(runId, n).phase === 'dormant') {
|
||||
lines.push(...readJsonl(path.join(dir, 'carryover.jsonl')));
|
||||
}
|
||||
}
|
||||
const st = session.scanState(lines);
|
||||
return { status: st.status ?? [], agenda: st.agenda ?? [] };
|
||||
}
|
||||
|
||||
route('GET', '/api/runs/:id/status', async ({ params, user }) => {
|
||||
requireOwner(user, params.id); // status and agenda are machinery
|
||||
return { status: clerkJson(params.id, 'status'), agenda: clerkJson(params.id, 'agenda') };
|
||||
});
|
||||
|
||||
// the GM's out-of-band status override: whole-status replace via the
|
||||
// clerk (which journals the prior state). Descriptions never contain
|
||||
// commas -- the transport is comma-separated -- so a comma inside an
|
||||
// item is a 400, not a silent corruption later.
|
||||
route('POST', '/api/runs/:id/status', async ({ params, body, user }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
requireOwner(user, id);
|
||||
const items = body.items;
|
||||
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required -- an empty array clears the status');
|
||||
for (const it of items) {
|
||||
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
|
||||
if (it.includes(',')) throw new HttpError(400, `descriptions never contain commas (the transport is comma-separated): ${JSON.stringify(it)}`);
|
||||
}
|
||||
const status = clerkJson(id, '--gm', 'status-set', ...items);
|
||||
return { ok: true, status };
|
||||
});
|
||||
|
||||
// the GM's out-of-band agenda override: whole-queue replace via the
|
||||
// clerk (journaled). Items land in written order, first = top; an
|
||||
// empty array clears it. Commas are the add transport's separator --
|
||||
// an item containing one is a 400, not a silent split later.
|
||||
route('POST', '/api/runs/:id/agenda', async ({ params, body, user }) => {
|
||||
const id = params.id;
|
||||
bundle.requireRun(id);
|
||||
requireOwner(user, id);
|
||||
const items = body.items;
|
||||
if (!Array.isArray(items)) throw new HttpError(400, 'items (an array of descriptions) is required -- an empty array clears the agenda');
|
||||
for (const it of items) {
|
||||
if (typeof it !== 'string' || !it.trim()) throw new HttpError(400, 'every item must be a non-empty string');
|
||||
if (it.includes(',')) throw new HttpError(400, `items never contain commas (the add transport is comma-separated): ${JSON.stringify(it)}`);
|
||||
}
|
||||
const r = clerkJson(id, '--gm', 'agenda-set', ...items);
|
||||
// the set enforces the cap silently (ruled a feature); the evicted
|
||||
// ride along for the record
|
||||
return { ok: true, agenda: r.set, evicted: r.evicted };
|
||||
return derivedState(params.id);
|
||||
});
|
||||
|
||||
route('POST', '/api/runs/:id/housekeeping', async ({ params, user }) => {
|
||||
|
||||
+125
-39
@@ -203,7 +203,7 @@ function derive(s) {
|
||||
// markers stripped -- the grammar the pane editors use and the
|
||||
// full-block protocol speaks. A present-but-empty block is a
|
||||
// deliberate clear (an empty list). Shared with the turn loop (the
|
||||
// player's live sets) and the start gate (the authored seed).
|
||||
// player's live sets) and the state scan.
|
||||
/** @param {string} text @param {'status'|'agenda'} kind @returns {string[]} */
|
||||
export function blockList(text, kind) {
|
||||
const out = [];
|
||||
@@ -215,6 +215,62 @@ export function blockList(text, kind) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- the state scan: the log is the one truth ---------------------------------
|
||||
//
|
||||
// The full-block protocol made her logged blocks the model's only
|
||||
// channel; the clerk's status and agenda tiers were a second home and
|
||||
// are retired for it -- the panes, the run detail, and the stamp all
|
||||
// read this scan, the db holds no copy. Newest-wins per kind across
|
||||
// three sources, all in the log:
|
||||
// - her emissions: the <status>/<agenda> blocks at her turn tails
|
||||
// (the picked variant's text, for variant literature);
|
||||
// - the GM's overrides: the override field on a GM turn -- the
|
||||
// composition renders them as if she had stated them (the model
|
||||
// never sees an override as an act, only as state);
|
||||
// - the state note: the boundary snapshot at a carryover's head.
|
||||
// null = never set; [] = deliberately cleared (a present-but-empty
|
||||
// block is a clear, absent means unchanged). The agenda cap applies
|
||||
// here, on every derivation: an over-cap list is never derivable
|
||||
// from the log, the raw event is the only place her seven items live.
|
||||
export const AGENDA_CAP = 5;
|
||||
|
||||
// the same clean the old clerk applies admitted: trim, drop empties,
|
||||
// dedupe -- first occurrence wins
|
||||
/** @param {string[]} items @returns {string[]} */
|
||||
const cleanList = (items) => [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
|
||||
|
||||
// blockList + the clean, as one step: what every reader of a block
|
||||
// derives from raw text (the scan for her emissions, the loop for its
|
||||
// reception notes)
|
||||
/** @param {string} text @param {'status'|'agenda'} kind @returns {string[]} */
|
||||
export function cleanBlockList(text, kind) {
|
||||
return cleanList(blockList(text, kind));
|
||||
}
|
||||
|
||||
/** @param {LogEvent[]} lines @returns {{ status: ?string[], agenda: ?string[] }} */
|
||||
export function scanState(lines) {
|
||||
const eff = effectiveContents(lines);
|
||||
/** @type {?string[]} */ let status = null;
|
||||
/** @type {?string[]} */ let agenda = null;
|
||||
for (const [i, e] of lines.entries()) {
|
||||
if (e.t === 'msg' && e.m.role === 'assistant' && !e.m.tool_calls?.length) {
|
||||
const c = eff.has(i) ? eff.get(i) : e.m.content;
|
||||
if (typeof c === 'string') {
|
||||
if (/<status>/.test(c)) status = cleanBlockList(c, 'status');
|
||||
if (/<agenda>/.test(c)) agenda = cleanBlockList(c, 'agenda');
|
||||
}
|
||||
} else if (e.t === 'msg' && e.m.role === 'user' && e.override) {
|
||||
if (e.override.status) status = cleanList(e.override.status);
|
||||
if (e.override.agenda) agenda = cleanList(e.override.agenda);
|
||||
} else if (e.t === 'note' && e.kind === 'state') {
|
||||
if (e.status) status = cleanList(e.status);
|
||||
if (e.agenda) agenda = cleanList(e.agenda);
|
||||
}
|
||||
}
|
||||
if (agenda !== null && agenda.length > AGENDA_CAP) agenda = agenda.slice(0, AGENDA_CAP);
|
||||
return { status, agenda };
|
||||
}
|
||||
|
||||
// --- stop: the manual close ----------------------------------------------------
|
||||
//
|
||||
// (1) move N's tail into the new dormant N+1 as its carryover;
|
||||
@@ -236,19 +292,34 @@ export function stopSession(runId, N) {
|
||||
const lines = readLogLines(logFile(runId, N));
|
||||
if (fs.existsSync(carry)) {
|
||||
// the crash landed mid-move: the carryover is written; truncate
|
||||
// the log to match it (the moved lines are the carryover now)
|
||||
const carried = fs.readFileSync(carry, 'utf8').split('\n').filter((l) => l.trim());
|
||||
const k = carried.length;
|
||||
// the log to match it (the moved lines are the carryover now).
|
||||
// The boundary state note is not log material -- the reconcile
|
||||
// compares the carry's conversation lines only.
|
||||
const carried = fs.readFileSync(carry, 'utf8').split('\n').filter((l) => l.trim())
|
||||
.map((l) => /** @type {LogEvent} */ (JSON.parse(l)));
|
||||
const conv = carried.filter((e) => !(e.t === 'note' && e.kind === 'state'));
|
||||
const k = conv.length;
|
||||
if (lines.length > k) {
|
||||
const tail = lines.slice(lines.length - k).map((e) => JSON.stringify(e));
|
||||
if (JSON.stringify(tail) !== JSON.stringify(carried)) {
|
||||
if (JSON.stringify(tail) !== JSON.stringify(conv.map((e) => JSON.stringify(e)))) {
|
||||
throw err(500, `stop cannot resume: session ${N}'s log does not end with its own carryover -- fix by hand`);
|
||||
}
|
||||
writeLog(logFile(runId, N), lines.slice(0, lines.length - k));
|
||||
} // else: already truncated -- nothing to move
|
||||
} else {
|
||||
const start = tailStart(lines);
|
||||
fs.writeFileSync(carry, lines.slice(start).map((e) => JSON.stringify(e)).join('\n') + (start < lines.length ? '\n' : ''));
|
||||
// the boundary snapshot: the closing log's current state rides at
|
||||
// the carry's head, so the new session derives it even when her
|
||||
// newest emission fell outside the slidwin tail. The scan reads
|
||||
// it newest-wins -- anything inside the tail wins over it by
|
||||
// position, so it is safe to write always
|
||||
const st = scanState(lines);
|
||||
/** @type {LogEvent[]} */ let head = [];
|
||||
if (st.status !== null || st.agenda !== null) {
|
||||
head = [{ t: 'note', kind: 'state', ...(st.status !== null ? { status: st.status } : {}), ...(st.agenda !== null ? { agenda: st.agenda } : {}) }];
|
||||
}
|
||||
const moved = [...head, ...lines.slice(start)];
|
||||
fs.writeFileSync(carry, moved.map((e) => JSON.stringify(e)).join('\n') + (moved.length ? '\n' : ''));
|
||||
writeLog(logFile(runId, N), lines.slice(0, start));
|
||||
}
|
||||
|
||||
@@ -333,6 +404,18 @@ export function lintCarryover(lines, { authored }) {
|
||||
errors.push(`${at}: malformed variants block -- ${e2.message}`);
|
||||
}
|
||||
}
|
||||
// both kinds: the boundary state note must be well-formed (stop
|
||||
// writes it; a hand edit must not corrupt it)
|
||||
if (e.t === 'note' && e.kind === 'state') {
|
||||
/** @type {Record<string, unknown>} */ const st = { status: e.status, agenda: e.agenda };
|
||||
for (const k of ['status', 'agenda']) {
|
||||
const v = st[k];
|
||||
if (v === undefined) continue;
|
||||
if (!Array.isArray(v) || v.some((x) => typeof x !== 'string' || !x.trim())) {
|
||||
errors.push(`${at}: state.${k} must be an array of non-empty strings`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (authored && openings > 1) errors.push('at most one opening event');
|
||||
// the full-block protocol (GM, 2026-11-16): the initial status rides
|
||||
@@ -351,7 +434,19 @@ export function lintCarryover(lines, { authored }) {
|
||||
/** @param {string} runId @param {LogEvent[]} lines @returns {LogEvent[]} */
|
||||
function expandCarryover(runId, lines) {
|
||||
return /** @type {LogEvent[]} */ (lines.map((e) => {
|
||||
if (e.t === 'msg') return { ...e, m: { ...e.m, content: expandVars(runId, e.m.content) } };
|
||||
if (e.t === 'msg') {
|
||||
const m = { ...e.m, content: expandVars(runId, e.m.content) };
|
||||
if (e.override) {
|
||||
// an authored carryover may carry a GM override (the opening
|
||||
// author writes one like any GM turn would); its items are
|
||||
// prompt-side like the prose
|
||||
/** @type {{ status?: string[], agenda?: string[] }} */ const o = {};
|
||||
if (e.override.status) o.status = e.override.status.map((it) => expandVars(runId, it));
|
||||
if (e.override.agenda) o.agenda = e.override.agenda.map((it) => expandVars(runId, it));
|
||||
return { ...e, m, override: o };
|
||||
}
|
||||
return { ...e, m };
|
||||
}
|
||||
if (e.t === 'opening') return { ...e, status: e.status.map((it) => expandVars(runId, it)) };
|
||||
return e;
|
||||
}));
|
||||
@@ -447,21 +542,12 @@ export function startSession(runId, { override = false } = {}) {
|
||||
});
|
||||
}
|
||||
// the full-block protocol (GM, 2026-11-16): the initial state
|
||||
// rides her last authored turn -- the gate seeds the clerk from
|
||||
// her blocks, so the panes and the stamped view read the same
|
||||
// words. The opening event is retired: old carryovers keep theirs
|
||||
// as inert history (tolerated by the lint, never applied -- and
|
||||
// its old double-landing, pre-bundle and in-carry, dies here)
|
||||
const lastHer = /** @type {?import('./shapes.mjs').MsgEvent} */ ([...carry].reverse().find((e) => e.t === 'msg' && e.m?.role === 'assistant') ?? null);
|
||||
const herText = typeof lastHer?.m?.content === 'string' ? lastHer.m.content : '';
|
||||
if (/<status>/.test(herText)) {
|
||||
const sr = clerkTry(runId, '--session', String(n), 'status-set', ...blockList(herText, 'status'));
|
||||
if (sr.code !== 0) throw err(422, `the opening status did not apply: ${(sr.err || sr.out).split('\n')[0]}`);
|
||||
}
|
||||
if (/<agenda>/.test(herText)) {
|
||||
const ar = clerkTry(runId, '--session', String(n), 'agenda-set', ...blockList(herText, 'agenda'));
|
||||
if (ar.code !== 0) throw err(422, `the opening agenda did not apply: ${(ar.err || ar.out).split('\n')[0]}`);
|
||||
}
|
||||
// rides her last authored turn -- the scan reads her blocks, the
|
||||
// stamp renders them, the panes derive them. No seeding, no
|
||||
// second home: her opening turn IS the seed. The opening event
|
||||
// is retired the same way: old carryovers keep theirs as inert
|
||||
// history (tolerated by the lint, never read -- and its old
|
||||
// double-landing, pre-bundle and in-carry, dies here)
|
||||
}
|
||||
|
||||
// fresh views, then the bundle: one assembly, baked here and
|
||||
@@ -526,14 +612,14 @@ export function renderView(s, keepToolResults = 4) {
|
||||
/** @type {number[]} */
|
||||
const reminderIdx = [];
|
||||
let lastGmIdx = -1;
|
||||
// the stamping pre-pass (the full-block protocol): the newest
|
||||
// status and agenda values across her turns, and her most recent
|
||||
// prose turn -- the canon point where they stamp. The status is the
|
||||
// game world as of her turn; after it the GM's turn happens, then
|
||||
// her new turn -- the context must read as that same sequence of
|
||||
// events (GM, 2026-11-16)
|
||||
/** @type {?string} */ let lastStatus = null;
|
||||
/** @type {?string} */ let lastAgenda = null;
|
||||
// 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
|
||||
// override, the boundary note -- the state scan's newest-wins).
|
||||
// The status is the game world as of her turn; after it the GM's
|
||||
// turn happens, then her new turn -- the context must read as that
|
||||
// same sequence of events (GM, 2026-11-16)
|
||||
const st = scanState(s.lines);
|
||||
let lastProse = -1;
|
||||
s.lines.forEach((e, i) => {
|
||||
if (e.t === 'tool') toolIdx.push(i);
|
||||
@@ -541,13 +627,7 @@ export function renderView(s, keepToolResults = 4) {
|
||||
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;
|
||||
if (typeof c === 'string') {
|
||||
if (c.trim()) lastProse = i;
|
||||
const sm = c.match(/<status>([\s\S]*?)<\/status>/);
|
||||
if (sm) lastStatus = sm[1];
|
||||
const am = c.match(/<agenda>([\s\S]*?)<\/agenda>/);
|
||||
if (am) lastAgenda = am[1];
|
||||
}
|
||||
if (typeof c === 'string' && c.trim()) lastProse = i;
|
||||
}
|
||||
});
|
||||
const keep = new Set(toolIdx.slice(-keepToolResults));
|
||||
@@ -576,9 +656,15 @@ export function renderView(s, keepToolResults = 4) {
|
||||
content = `<model>${JSON.stringify(e.via.params)}</model>\n${content}`;
|
||||
}
|
||||
if (i === lastProse) {
|
||||
// the canonical stamp: status comma-separated (the wire
|
||||
// grammar invariants teaches), agenda as bullets. A
|
||||
// cleared kind renders its empty tag -- present-but-empty
|
||||
// is the deliberate clear the grammar promises
|
||||
/** @type {string[]} */ const stamp = [];
|
||||
if (lastStatus !== null) stamp.push(`<status>${lastStatus}</status>`);
|
||||
if (lastAgenda !== null) stamp.push(`<agenda>${lastAgenda}</agenda>`);
|
||||
if (st.status !== null) stamp.push(`<status>${st.status.join(', ')}</status>`);
|
||||
if (st.agenda !== null) {
|
||||
stamp.push(`<agenda>${st.agenda.length ? `\n${st.agenda.map((d) => `- ${d}`).join('\n')}\n` : ''}</agenda>`);
|
||||
}
|
||||
if (stamp.length) content = `${content}\n${stamp.join('\n')}`;
|
||||
}
|
||||
}
|
||||
|
||||
+13
-3
@@ -30,8 +30,11 @@ export {};
|
||||
* everything else about a turn lives in its content. via is the
|
||||
* request record: the resolved model and the effective params (the
|
||||
* merged layer actually sent) -- model-facing surfaces never render
|
||||
* it, the raw surfaces always do. */
|
||||
/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, params: RoleParams } }} MsgEvent */
|
||||
* it, the raw surfaces always do. override is the GM's block edit,
|
||||
* arriving with a non-OOC GM turn: the log's record of it. The
|
||||
* composition overwrites her newest blocks with these values (the
|
||||
* scan reads it newest-wins); the log itself never changes. */
|
||||
/** @typedef {{ t: 'msg', m: WireMessage, reminder?: boolean, conflictOnly?: boolean, usage?: Usage, via?: { model: string, params: RoleParams }, override?: { status?: string[], agenda?: string[] } }} MsgEvent */
|
||||
|
||||
/** req: a failed provider request -- the resolved model, the
|
||||
* effective params, and the failure. No message resulted (the turn
|
||||
@@ -53,7 +56,14 @@ export {};
|
||||
/** @typedef {{ t: 'note', kind: 'status', applied?: { lost: string[], gained: string[] }, set?: string[], conflicts?: string[] }} StatusNote */
|
||||
/** @typedef {{ t: 'note', kind: 'agenda', applied?: { added: string[], dropped: string[], evicted: string[] }, set?: string[], evicted?: string[], conflicts?: string[] }} AgendaNote */
|
||||
/** @typedef {{ t: 'note', kind: 'mind', params: RoleParams }} MindNote */
|
||||
/** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote|MindNote} NoteEvent */
|
||||
/** state: the boundary snapshot -- stop writes it at the carryover's
|
||||
* head when the closing log holds any status or agenda, so the new
|
||||
* session derives state even when her newest emission fell outside
|
||||
* the slidwin tail. Machinery like every note: never rendered, the
|
||||
* scan reads it newest-wins (it loses to any emission inside the
|
||||
* tail by position). */
|
||||
/** @typedef {{ t: 'note', kind: 'state', status?: string[], agenda?: string[] }} StateNote */
|
||||
/** @typedef {SessionNote|AskNote|PickNote|StatusNote|AgendaNote|MindNote|StateNote} NoteEvent */
|
||||
|
||||
/** bundle: one frozen prompt part (system, backdrop, character, rings). */
|
||||
/** @typedef {{ t: 'bundle', m: { role: 'user'|'system', content: string }, part: string }} BundleEvent */
|
||||
|
||||
+55
-17
@@ -10,7 +10,10 @@
|
||||
// inherited by a fork), 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 session lifecycle
|
||||
// the emitted-<model> guard, GM prose pure), the state scan (the log
|
||||
// is the one truth -- no db tier; the GM's block edit rides its turn
|
||||
// as the override and composes over her newest blocks, the boundary
|
||||
// state note rides the carry head), the session lifecycle
|
||||
// (create dormant -> start -> live ->
|
||||
// stop -> dormant -> re-run -> start -> the auto-send rule -> the
|
||||
// start lint), the draft's memory.json (authored while draft, the
|
||||
@@ -174,7 +177,7 @@ ok('live', r.data.phase === 'live' && r.data.open === true);
|
||||
ok('the draft edit is what she starts with', r.data.fill.a === 5 && r.data.fill.b === 1, JSON.stringify(r.data.fill));
|
||||
const filesLive = await call(`/runs/${runId}/files`, { token: op });
|
||||
ok('memory.json is provenance once live', filesLive.data.files['memory.json']?.mode === 'ro', filesLive.data.files['memory.json']?.mode ?? 'missing');
|
||||
ok('her authored blocks seed the clerk', JSON.stringify(r.data.status) === '["cuffed","belted","naked","barefoot","worried"]', JSON.stringify(r.data.status));
|
||||
ok('her authored blocks are the seed (the scan derives them)', JSON.stringify(r.data.status) === '["cuffed","belted","naked","barefoot","worried"]', JSON.stringify(r.data.status));
|
||||
r = await call(`/runs/${runId}/table`, { token: op });
|
||||
ok('the opening renders on the table', r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /Modesty, decency or respect/.test(e.m.content ?? '')));
|
||||
ok('the opening event is retired (her authored blocks are the seed)', r.data.entries.every((e) => e.t !== 'opening'), 'an opening event rode the log');
|
||||
@@ -226,6 +229,8 @@ r = await call(`/runs/${runId}/session`, { token: op });
|
||||
const evictNote = r.data.entries.find((e) => e.t === 'note' && e.kind === 'agenda' && e.evicted?.length);
|
||||
ok('the eviction is visible to the GM (the note)',
|
||||
!!evictNote && JSON.stringify(evictNote.evicted) === '["item six","item seven"]', JSON.stringify(evictNote ?? null));
|
||||
ok('the log keeps all seven items (raw is the only place they live)',
|
||||
r.data.entries.some((e) => e.t === 'msg' && e.m.role === 'assistant' && /- item six\n- item seven/.test(e.m.content ?? '')), 'her emission was capped in the log');
|
||||
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*Dawn breaks.*' } });
|
||||
ok('next gm turn is clean', r.status === 200 && !r.data.conflicts, r.data.error ?? JSON.stringify(r.data.conflicts ?? null));
|
||||
|
||||
@@ -252,8 +257,10 @@ ok('the mind verb: her next turn rides at the stated mind',
|
||||
const lastGm = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && !e.conflictOnly);
|
||||
ok('no conflict attached to the GM turn', !/<conflict>/.test(lastGm.m.content), lastGm.m.content.slice(-100));
|
||||
ok('GM prose goes pure', !/<\/?(status|agenda)>/.test(lastGm.m.content), lastGm.m.content.slice(-120));
|
||||
r = await call(`/runs/${runId}/agenda`, { method: 'POST', token: op, body: { items: ['climb the ridge', 'rest'] } });
|
||||
ok('agenda-set (GM override)', r.status === 200 && JSON.stringify(r.data.agenda) === '["climb the ridge","rest"]', JSON.stringify(r.data.agenda));
|
||||
r = await call(`/runs/${runId}/status`, { method: 'POST', token: op, body: { items: [] } });
|
||||
ok('the out-of-band status route is retired', r.status === 404, `${r.status}`);
|
||||
r = await call(`/runs/${runId}/agenda`, { method: 'POST', token: op, body: { items: [] } });
|
||||
ok('the out-of-band agenda route is retired', r.status === 404, `${r.status}`);
|
||||
|
||||
// 10d. an OOC GM turn: the paren channel carries no cache blocks -- an
|
||||
// OOC exchange does not move her state, the next IC turn re-carries them
|
||||
@@ -284,11 +291,11 @@ const her1 = view1.filter((m) => m.role === 'assistant');
|
||||
const lastHer = [...her1].reverse().find((m) => typeof m.content === 'string' && /breathes until the numbers behave/.test(m.content));
|
||||
ok('the view stamps the newest status and agenda at her latest turn',
|
||||
!!lastHer && /<status>cuffed, belted, naked, barefoot, settled, curious about the clicking<\/status>/.test(lastHer.content)
|
||||
&& /<agenda>item one\nitem two\nitem three\nitem four\nitem five\nitem six\nitem seven<\/agenda>/.test(lastHer.content),
|
||||
(lastHer?.content ?? 'none').slice(-220));
|
||||
ok('the stamped agenda is her own emission (the eviction stays silent to her)',
|
||||
!!lastHer && (lastHer.content.match(/<agenda>/g) ?? []).length === 1 && /item seven<\/agenda>/.test(lastHer.content),
|
||||
'the stamp leaked the clerk truth');
|
||||
&& /<agenda>\n- item one\n- item two\n- item three\n- item four\n- item five\n<\/agenda>/.test(lastHer.content),
|
||||
(lastHer?.content ?? 'none').slice(-260));
|
||||
ok('the capped agenda is what derives (the eviction stays silent to her)',
|
||||
!!lastHer && (lastHer.content.match(/<agenda>/g) ?? []).length === 1 && !/item (six|seven)/.test(lastHer.content),
|
||||
'the stamp leaked the over-cap items');
|
||||
ok('superseded copies strip from the view',
|
||||
her1.filter((m) => m !== lastHer).every((m) => !/<\/?(status|agenda)>/.test(String(m.content ?? ''))), '');
|
||||
ok('her mind tags are write-only (stripped from the view)',
|
||||
@@ -305,8 +312,6 @@ r = await call(`/runs/${runId}/session`, { token: op });
|
||||
const reminders = r.data.entries.filter((e) => e.reminder);
|
||||
ok('reminder rode every GM turn', reminders.length === 6 && reminders.every((x) => x.m.role === 'system'), `${reminders.length} in the log`);
|
||||
ok('reminder carries the turn protocol', /How to compose your turn/i.test(reminders[0]?.m.content ?? ''), (reminders[0]?.m.content ?? '').slice(0, 60));
|
||||
r = await call(`/runs/${runId}/agenda`, { method: 'POST', token: ash, body: { items: [] } });
|
||||
ok('agenda override owner-only', r.status === 403);
|
||||
r = await call(`/runs/${runId}/status`, { token: op });
|
||||
ok('status endpoint carries both', Array.isArray(r.data.status) && Array.isArray(r.data.agenda), JSON.stringify(r.data).slice(0, 120));
|
||||
|
||||
@@ -355,6 +360,32 @@ r = await call(`/runs/${forkId}/session`, { token: ash });
|
||||
const forkReply = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
|
||||
ok('the fork inherits her unconsumed mind', forkReply?.via?.params?.temperature === 1.2, JSON.stringify(forkReply?.via ?? null));
|
||||
|
||||
// 10f. the GM's block edit rides its turn (the override): the log
|
||||
// records the field, the composition overwrites her newest blocks
|
||||
// with it, the log keeps her words verbatim, and the model never
|
||||
// sees an override as an act -- only as state
|
||||
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '*A cooler wind picks up.*', agenda: ['climb the ridge', 'rest'] } });
|
||||
ok('the override turn sends', r.status === 200, r.data.error ?? '');
|
||||
r = await call(`/runs/${runId}/session`, { token: op });
|
||||
const ovrTurn = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'user' && e.override);
|
||||
ok('the override rides its GM turn as the record',
|
||||
!!ovrTurn && JSON.stringify(ovrTurn.override.agenda) === '["climb the ridge","rest"]' && ovrTurn.override.status === undefined,
|
||||
JSON.stringify(ovrTurn?.override ?? null));
|
||||
ok('the override turn\'s prose stays pure', !/<\/?(status|agenda)>/.test(String(ovrTurn?.m.content ?? '')), String(ovrTurn?.m.content ?? '').slice(-80));
|
||||
r = await call(`/runs/${runId}/status`, { token: op });
|
||||
ok('the composed agenda is the override', JSON.stringify(r.data.agenda) === '["climb the ridge","rest"]', JSON.stringify(r.data.agenda));
|
||||
ok('the untouched status derives unchanged',
|
||||
JSON.stringify(r.data.status) === '["cuffed","belted","naked","barefoot","settled","curious about the clicking"]', JSON.stringify(r.data.status));
|
||||
const view1b = renderView({ lines: jsonl(runId, 1, 'log.jsonl'), pendingAsk: null });
|
||||
const lastHerB = [...view1b].reverse().find((m) => m.role === 'assistant' && typeof m.content === 'string' && m.content.trim());
|
||||
ok('the composition stamps the override at her canon point',
|
||||
/<agenda>\n- climb the ridge\n- rest\n<\/agenda>/.test(lastHerB.content), String(lastHerB.content).slice(-180));
|
||||
ok('the log keeps her words verbatim (the over-cap emission is intact)',
|
||||
jsonl(runId, 1, 'log.jsonl').some((e) => e.t === 'msg' && e.m.role === 'assistant' && /- item six\n- item seven/.test(e.m.content ?? '')),
|
||||
'her emission was rewritten');
|
||||
r = await call(`/runs/${runId}/turn`, { method: 'POST', token: op, body: { line: '( ooc with an edit )', status: ['x'] } });
|
||||
ok('an override cannot ride an OOC turn', r.status === 400 && /OOC/.test(r.data.error), r.data.error ?? '');
|
||||
|
||||
// 12b. models: per-run overrides of the deployment defaults, the
|
||||
// registry-gated picks, and the named sampling knobs
|
||||
r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { player: 'mock', housekeeper: 'mock-cheap' } });
|
||||
@@ -377,13 +408,15 @@ r = await call(`/runs/${forkId}/model`, { method: 'POST', token: ash, body: { ba
|
||||
ok('unknown role rejected', r.status === 400);
|
||||
r = await call(`/runs/${forkId}`, { token: ash });
|
||||
ok('detail exposes models + defaults', r.data.run.models?.player === 'mock' && !!r.data.run.modelDefaults?.player && r.data.run.params?.player?.max_tokens === 4096 && !!r.data.run.paramDefaults, JSON.stringify(r.data.run.models));
|
||||
// a turn on the knob-carrying run: the recording proves what was sent
|
||||
// a turn on the knob-carrying run: the recording proves what was
|
||||
// sent -- the run's knob under the mind layer (her restated mind
|
||||
// rides over the run layer, the layering the tunables round built)
|
||||
r = await call(`/runs/${forkId}/turn`, { method: 'POST', token: ash, body: { line: '*She keeps watch.*' } });
|
||||
ok('gm turn on the fork (post-knobs)', r.status === 200, r.data.error ?? '');
|
||||
r = await call(`/runs/${forkId}/session`, { token: ash });
|
||||
const viaTurn = [...r.data.entries].reverse().find((e) => e.t === 'msg' && e.m.role === 'assistant');
|
||||
ok('the recorded request carries the run\'s knobs',
|
||||
!!viaTurn?.via && viaTurn.via.model === 'mock' && viaTurn.via.params.max_tokens === 4096 && viaTurn.via.params.temperature === undefined,
|
||||
ok('the recorded request carries the run\'s knobs under the mind layer',
|
||||
!!viaTurn?.via && viaTurn.via.model === 'mock' && viaTurn.via.params.max_tokens === 4096 && viaTurn.via.params.temperature === 1.2,
|
||||
JSON.stringify(viaTurn?.via ?? null));
|
||||
r = await call('/models', { token: ash });
|
||||
ok('model listing (the registry)', r.status === 200 && r.data.phase === 'refined' && r.data.models.some((m) => m.id === 'mock' && m.label === 'Mock'), JSON.stringify(r.data.phase));
|
||||
@@ -462,8 +495,13 @@ const log1 = jsonl(runId, 1, 'log.jsonl');
|
||||
const carry2 = jsonl(runId, 2, 'carryover.jsonl');
|
||||
ok('the tail moved out of session 1', carry2.length > 0 && log1.every((e) => !carry2.some((c) => JSON.stringify(c) === JSON.stringify(e))),
|
||||
`${carry2.length} carried lines`);
|
||||
ok('the carry holds whole exchanges', carry2[0]?.t === 'msg' && carry2[0]?.m?.role === 'user' && !carry2[0]?.conflictOnly
|
||||
&& carry2.some((e) => e.t === 'msg' && e.m.role === 'assistant'), carry2[0]?.t ?? 'nothing carried');
|
||||
ok('the boundary state note rides the carry head',
|
||||
carry2[0]?.t === 'note' && carry2[0]?.kind === 'state'
|
||||
&& JSON.stringify(carry2[0]?.agenda) === '["climb the ridge","rest"]'
|
||||
&& JSON.stringify(carry2[0]?.status) === '["cuffed","belted","naked","barefoot","settled","curious about the clicking"]',
|
||||
JSON.stringify(carry2[0] ?? null));
|
||||
ok('the carry holds whole exchanges', carry2[1]?.t === 'msg' && carry2[1]?.m?.role === 'user' && !carry2[1]?.conflictOnly
|
||||
&& carry2.some((e) => e.t === 'msg' && e.m.role === 'assistant'), carry2[1]?.t ?? 'nothing carried');
|
||||
ok('the carry ends on her turn (no auto-send)', [...carry2].reverse().find((e) => e.t === 'msg' && !e.reminder)?.m?.role === 'assistant');
|
||||
ok('no markers anywhere in the logs', log1.concat(carry2).every((e) => e.carried === undefined));
|
||||
r = await call(`/runs/${runId}/carryover`, { token: op });
|
||||
@@ -473,7 +511,7 @@ ok('the dormant preview renders the carry', r.status === 200 && r.data.session =
|
||||
// the story reads whole, through dormancy, with no doubles
|
||||
r = await call(`/runs/${runId}/story`, { token: op });
|
||||
const gmTexts = r.data.sessions.flatMap((s) => s.turns.filter((t) => t.who === 'gm').map((t) => t.text));
|
||||
ok('the story has every GM turn exactly once', gmTexts.length === 5 && new Set(gmTexts).size === 5, `${gmTexts.length} gm turns across ${r.data.sessions.length} sessions`);
|
||||
ok('the story has every GM turn exactly once', gmTexts.length === 6 && new Set(gmTexts).size === 6, `${gmTexts.length} gm turns across ${r.data.sessions.length} sessions`);
|
||||
ok('the story carries no OOC', r.data.sessions.every((s) => s.turns.every((t) => !/^\(/.test(t.text) && !/\( mock GM checking in \)/.test(t.text))), 'OOC leaked into the story');
|
||||
ok('the story reads the dormant carryover at the live edge', r.data.sessions.some((s) => s.turns.length >= 10));
|
||||
const storyPlayer = r.data.sessions.flatMap((s) => s.turns.filter((t) => t.who === 'player').map((t) => t.text));
|
||||
|
||||
+25
-179
@@ -23,7 +23,7 @@
|
||||
// all; pc never rides; --owner stamps)
|
||||
// init build session one of a fresh run
|
||||
// (the low-level primitive under create)
|
||||
// render write canon/ring-a.md, ring-b.md, status.md
|
||||
// render write canon/ring-a.md, ring-b.md
|
||||
// apply <manifest.json> apply a housekeeper manifest (validated, transactional)
|
||||
// reapply session-0's housekeeping: rebuild session
|
||||
// one's rings from its memory.json over a
|
||||
@@ -39,15 +39,6 @@
|
||||
// discard <rid> "reason" the PC discards a record (--gm likewise)
|
||||
// search <terms...> query the records (max 10; a miss is a miss)
|
||||
// unarchive <rid> [a|b] GM pulls a record back into the rings
|
||||
// status her status, as JSON (the status tier)
|
||||
// status-set "descr" ... whole-status replace -- the GM override
|
||||
// and the player's <status> block alike
|
||||
// (no descrs = clear it)
|
||||
// agenda the agenda, as JSON (the intentions tier)
|
||||
// agenda-set "item" ... whole-queue replace -- the GM override
|
||||
// and the player's <agenda> block alike;
|
||||
// over-cap evicts the bottom, silently
|
||||
// (no items = clear it)
|
||||
// pick "a" "b" "c" ... dice for prose -- uniform random choice
|
||||
// dump canonical dump to dumps/memory.sql
|
||||
// (also auto-written by every mutation)
|
||||
@@ -58,7 +49,11 @@
|
||||
// review window). State is per-deployment and per-session: every
|
||||
// session owns its db, canon views, dumps, and housekeeping logs.
|
||||
//
|
||||
// report counts, caps, the status, what's sinking
|
||||
// report counts, caps, what's sinking
|
||||
//
|
||||
// her status and agenda never lived here in the end: the log is the
|
||||
// one truth (the server's state scan reads her blocks); the clerk
|
||||
// keeps the rings and the records only.
|
||||
|
||||
/** @typedef {import('../server/shapes.mjs').Manifest} Manifest */
|
||||
/** @typedef {import('../server/shapes.mjs').InsertOp} InsertOp */
|
||||
@@ -72,10 +67,6 @@
|
||||
/** @typedef {{ id: number, ring: 'a'|'b'|'cold', type: 'place'|'person'|'fact'|'thread', label: string, detail: string, created: string, last_touched: string }} EntryRow */
|
||||
/** A records table row. */
|
||||
/** @typedef {{ id: number, kind: string, label: string, detail: string, created: string }} RecordRow */
|
||||
/** A status table row. */
|
||||
/** @typedef {{ id: number, descr: string, added: string }} StatusRow */
|
||||
/** An agenda table row. */
|
||||
/** @typedef {{ id: number, descr: string, added: string }} AgendaRow */
|
||||
/** An events table row: the append-only journal, never updated or deleted. */
|
||||
/** @typedef {{ id: number, session: string, op: string, target: string, reason: string, prior: string }} EventRow */
|
||||
|
||||
@@ -112,7 +103,6 @@ const RUNS_DIR = path.join(ROOT, 'runs');
|
||||
// dials -- retune freely
|
||||
/** @type {Record<string, number>} */
|
||||
const CAPS = { a: 500, b: 3000 };
|
||||
const AGENDA_CAP = 5; // dial -- retune freely (invariants.md: "intentionally tiny")
|
||||
const TYPES = ['place', 'person', 'fact', 'thread'];
|
||||
const RINGS = ['a', 'b']; // renderable; 'cold' is beyond the models
|
||||
|
||||
@@ -245,14 +235,13 @@ if (RUN != null && cmd !== 'init') setSessionRoot(resolveSession(sessionOverride
|
||||
|
||||
// the freeze ruling, enforced: which phases each mutating verb may
|
||||
// touch. Ring edits are the dormancy window (live is unnecessary and
|
||||
// dangerous, finished is frozen); the status and agenda are runtime
|
||||
// channels (live) and the dormancy edit surface; apply targets the
|
||||
// dormant session's rings -- the housekeeping write.
|
||||
// dangerous, finished is frozen); the records verbs are runtime
|
||||
// channels (live); apply targets the dormant session's rings -- the
|
||||
// housekeeping write.
|
||||
/** @type {Record<string, string[]>} */
|
||||
const PHASE_RULES = {
|
||||
insert: ['dormant'], delete: ['dormant'], revive: ['dormant'], unarchive: ['dormant'],
|
||||
apply: ['dormant'], reapply: ['dormant'],
|
||||
'status-set': ['dormant', 'live'], 'agenda-set': ['dormant', 'live'],
|
||||
file: ['dormant', 'live'], amend: ['dormant', 'live'], discard: ['dormant', 'live'],
|
||||
};
|
||||
/** @param {string} verb */
|
||||
@@ -408,44 +397,6 @@ function renderRing(db, ring) {
|
||||
return { file, count: rows.length };
|
||||
}
|
||||
|
||||
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
|
||||
function renderStatus(db) {
|
||||
const rows = /** @type {StatusRow[]} */ (db.prepare('SELECT * FROM status ORDER BY id').all());
|
||||
const lines = [
|
||||
'# Status',
|
||||
'',
|
||||
'The status is the player\'s -- stances and feelings; facts live in the rings.',
|
||||
'',
|
||||
];
|
||||
if (!rows.length) lines.push('(a blank sheet -- fresh start)');
|
||||
for (const r of rows) lines.push(`- ${r.descr}`);
|
||||
lines.push('');
|
||||
const file = path.join(CANON_DIR, 'status.md');
|
||||
fs.mkdirSync(CANON_DIR, { recursive: true });
|
||||
fs.writeFileSync(file, lines.join('\n'));
|
||||
return { file, count: rows.length };
|
||||
}
|
||||
|
||||
// the agenda view: the queue, top (newest) first, numbered as the wire
|
||||
// renders it -- what the model cites, what the GM reads
|
||||
/** @param {DatabaseSync} db @returns {{ file: string, count: number }} */
|
||||
function renderAgenda(db) {
|
||||
const items = agendaList(db);
|
||||
const lines = [
|
||||
'# Agenda -- what drives her',
|
||||
'',
|
||||
'The queue is the player\'s -- intentions, not facts; facts live in the rings.',
|
||||
'',
|
||||
];
|
||||
if (!items.length) lines.push('(a clear head -- nothing queued)');
|
||||
items.forEach((d, i) => lines.push(`- ${i}. ${d}`));
|
||||
lines.push('');
|
||||
const file = path.join(CANON_DIR, 'agenda.md');
|
||||
fs.mkdirSync(CANON_DIR, { recursive: true });
|
||||
fs.writeFileSync(file, lines.join('\n'));
|
||||
return { file, count: items.length };
|
||||
}
|
||||
|
||||
/** @param {DatabaseSync} db */
|
||||
function renderAll(db) {
|
||||
// --json means stdout carries JSON only; the view paths are human garnish
|
||||
@@ -454,10 +405,6 @@ function renderAll(db) {
|
||||
const { file, count } = renderRing(db, ring);
|
||||
if (talk) console.log(`${rel(file)} -- ${count} entries`);
|
||||
}
|
||||
const { file, count } = renderStatus(db);
|
||||
if (talk) console.log(`${rel(file)} -- ${count} descriptions`);
|
||||
const a = renderAgenda(db);
|
||||
if (talk) console.log(`${rel(a.file)} -- ${a.count} queued`);
|
||||
}
|
||||
|
||||
// canonical serialization: id-ordered, one row per line, restorable SQL.
|
||||
@@ -479,12 +426,6 @@ function dumpDb(db) {
|
||||
for (const r of /** @type {RecordRow[]} */ (db.prepare('SELECT * FROM records ORDER BY id').all())) {
|
||||
L.push(`INSERT INTO records VALUES (${r.id},${q(r.kind)},${q(r.label)},${q(r.detail)},${q(r.created)});`);
|
||||
}
|
||||
for (const r of /** @type {StatusRow[]} */ (db.prepare('SELECT * FROM status ORDER BY id').all())) {
|
||||
L.push(`INSERT INTO status VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
|
||||
}
|
||||
for (const r of /** @type {AgendaRow[]} */ (db.prepare('SELECT * FROM agenda ORDER BY id').all())) {
|
||||
L.push(`INSERT INTO agenda VALUES (${r.id},${q(r.descr)},${q(r.added)});`);
|
||||
}
|
||||
for (const r of /** @type {EventRow[]} */ (db.prepare('SELECT * FROM events ORDER BY id').all())) {
|
||||
L.push(`INSERT INTO events VALUES (${r.id},${q(r.session)},${q(r.op)},${q(r.target)},${q(r.reason)},${q(r.prior)});`);
|
||||
}
|
||||
@@ -1176,8 +1117,10 @@ function cmdRestore(force = false) {
|
||||
// an old dump embeds its own old schema -- normalize before rendering:
|
||||
// the renames first (the schema exec's CREATE IF NOT EXISTS would
|
||||
// collide with a table awaiting rename), then the schema (creates
|
||||
// tables the dump predates, e.g. agenda). Old dumps self-heal
|
||||
// through the same path as openDb.
|
||||
// tables the dump predates). Old dumps self-heal through the same
|
||||
// path as openDb. An old dump's status/agenda tables restore as
|
||||
// dead residue (the tiers are retired): present on disk, never
|
||||
// read, never dropped.
|
||||
migrateStatusNames(db);
|
||||
db.exec(fs.readFileSync(SCHEMA_PATH, 'utf8'));
|
||||
console.log(`restored ${rel(DB_PATH)} from ${rel(dumpFile)}`);
|
||||
@@ -1225,108 +1168,20 @@ function cmdDiscard(ridStr, reason) {
|
||||
// can re-file it exactly (id included, so rid references stay valid)
|
||||
journal(db, AS_GM ? 'gm' : 'pc', 'discard', `r${rid}`, reason ?? 'discarded',
|
||||
JSON.stringify({ id: row.id, kind: row.kind, label: row.label, detail: row.detail, created: row.created }));
|
||||
console.log(`discarded [r${rid}] **${row.label}**`);
|
||||
console.log(`discarded [r${row.id}] **${row.label}**`);
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
// --- her status (the status tier) -------------------------------------------------
|
||||
// --- her status and agenda: RETIRED (GM, 2026-11-16) -------------------------------
|
||||
//
|
||||
// Freeform descriptions, no keys, no baselines. The player mutates via
|
||||
// <lost>/<gained> deltas in its own turns -- exact match, non-blocking,
|
||||
// misses relayed back to the model as a <conflict> block by the caller.
|
||||
// The GM overrides out-of-band with status-set. Descriptions never contain
|
||||
// commas: both the delta lists and the <status> block are comma-separated.
|
||||
|
||||
/** @param {DatabaseSync} db @returns {string[]} */
|
||||
const statusList = (db) => /** @type {{ descr: string }[]} */ (db.prepare('SELECT descr FROM status ORDER BY id').all()).map((r) => r.descr);
|
||||
|
||||
function cmdStatus() {
|
||||
console.log(JSON.stringify(statusList(openDb())));
|
||||
}
|
||||
|
||||
// whole-status replace (GM override and the player's <status> block --
|
||||
// the full-block protocol); the journal keeps
|
||||
// the full prior status so turn surgery can compensate mechanically
|
||||
/** @param {DatabaseSync} db @param {string[]} items @param {string} reason @param {string} win @returns {string[]} */
|
||||
function setStatus(db, items, reason, win) {
|
||||
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
|
||||
const prior = statusList(db);
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
db.prepare('DELETE FROM status').run();
|
||||
for (const d of clean) {
|
||||
db.prepare('INSERT INTO status (descr, added) VALUES (?, ?)').run(d, today());
|
||||
}
|
||||
journal(db, win, 'status-set', 'p', reason, JSON.stringify(prior));
|
||||
db.exec('COMMIT');
|
||||
} catch (e) {
|
||||
db.exec('ROLLBACK');
|
||||
fail(`status-set failed, rolled back: ${e.message}`);
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
|
||||
/** @param {string[]} items */
|
||||
function cmdStatusSet(items) {
|
||||
const db = openDb();
|
||||
const clean = setStatus(db, items, AS_GM ? 'GM override' : 'status set', AS_GM ? 'gm' : 'pc');
|
||||
console.log(JSON.stringify(clean));
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
|
||||
// --- the agenda (intentions tier) ---------------------------------------------
|
||||
//
|
||||
// The hot queue of what drives her: goals she is working towards right
|
||||
// now -- intentions, never states (those are the status's). Fixed cap
|
||||
// (a dial); id order IS queue order -- the first item is the top, a
|
||||
// whole-list set lands in written order, over-cap evicts the bottom,
|
||||
// a recency ring buffer for free. The player mutates by restating the
|
||||
// whole <agenda> block in its own turns (the full-block protocol,
|
||||
// 2026-11-16); the GM overrides whole-list with agenda-set.
|
||||
|
||||
/** @param {DatabaseSync} db @returns {string[]} */
|
||||
const agendaList = (db) => /** @type {{ descr: string }[]} */ (db.prepare('SELECT descr FROM agenda ORDER BY id DESC').all()).map((r) => r.descr);
|
||||
|
||||
function cmdAgenda() {
|
||||
console.log(JSON.stringify(agendaList(openDb())));
|
||||
}
|
||||
|
||||
// whole-list replace (GM override and the player's <agenda> block --
|
||||
// the full-block protocol); the journal keeps the prior queue so turn
|
||||
// surgery can compensate mechanically (the saga rule). Over-cap lists
|
||||
// evict from the bottom silently -- ruled a feature (GM, 2026-11-16):
|
||||
// immersive, human-like, fun chaos. Silent to her; the caller surfaces
|
||||
// the evicted to the GM.
|
||||
/** @param {DatabaseSync} db @param {string[]} items @param {string} reason @param {string} win @returns {{ set: string[], evicted: string[] }} */
|
||||
function setAgenda(db, items, reason, win) {
|
||||
const clean = [...new Set(items.map((s) => String(s ?? '').trim()))].filter(Boolean);
|
||||
const set = clean.slice(0, AGENDA_CAP);
|
||||
const evicted = clean.slice(AGENDA_CAP);
|
||||
const prior = agendaList(db);
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
db.prepare('DELETE FROM agenda').run();
|
||||
for (const d of [...set].reverse()) { // first item = the top of the queue
|
||||
db.prepare('INSERT INTO agenda (descr, added) VALUES (?, ?)').run(d, today());
|
||||
}
|
||||
journal(db, win, 'agenda-set', 'agenda', reason, JSON.stringify(prior));
|
||||
db.exec('COMMIT');
|
||||
} catch (e) {
|
||||
db.exec('ROLLBACK');
|
||||
fail(`agenda-set failed, rolled back: ${e.message}`);
|
||||
}
|
||||
return { set, evicted };
|
||||
}
|
||||
|
||||
/** @param {string[]} items */
|
||||
function cmdAgendaSet(items) {
|
||||
const db = openDb();
|
||||
const r = setAgenda(db, items, AS_GM ? 'GM override' : 'agenda set', AS_GM ? 'gm' : 'pc');
|
||||
console.log(JSON.stringify(r));
|
||||
renderAll(db);
|
||||
dumpDb(db);
|
||||
}
|
||||
// The full-block protocol made her logged blocks the model's only
|
||||
// channel, and a second home in the db was a stale mirror, not a
|
||||
// truth -- the panes and the stamp read the server's state scan of
|
||||
// the log now (server/session.mjs: scanState). The verbs, the
|
||||
// tables, and the canon views are gone; old runs keep their dead
|
||||
// tables on disk, never read, never dropped (Irene is hands-off).
|
||||
// The events journal keeps the historical status-*/agenda-* rows and
|
||||
// the CHECK constraint still names their ops.
|
||||
|
||||
/** @param {string[]} options */
|
||||
function cmdPick(options) {
|
||||
@@ -1370,13 +1225,11 @@ function cmdUnarchive(ridStr, ring = 'b') {
|
||||
function cmdReport() {
|
||||
const db = openDb();
|
||||
if (AS_JSON) {
|
||||
/** @type {{ run: ?string, records: number, recordsEnabled: boolean, status: string[], agenda: string[], events: number, rings: Record<string, number>, sinking: Record<string, { id: number, last_touched: string, label: string }[]> }} */
|
||||
/** @type {{ run: ?string, records: number, recordsEnabled: boolean, events: number, rings: Record<string, number>, sinking: Record<string, { id: number, last_touched: string, label: string }[]> }} */
|
||||
const out = {
|
||||
run: RUN,
|
||||
records: Number(db.prepare('SELECT COUNT(*) AS n FROM records').get()?.n ?? 0),
|
||||
recordsEnabled: recordsEnabled(),
|
||||
status: statusList(db),
|
||||
agenda: agendaList(db),
|
||||
events: Number(db.prepare('SELECT COUNT(*) AS n FROM events').get()?.n ?? 0),
|
||||
rings: {},
|
||||
sinking: {},
|
||||
@@ -1395,9 +1248,6 @@ function cmdReport() {
|
||||
console.log(`run: ${RUN}${recordsEnabled() ? '' : ' (no records)'}`);
|
||||
const nr = Number(db.prepare('SELECT COUNT(*) AS n FROM records').get()?.n ?? 0);
|
||||
console.log(`records: ${nr}`);
|
||||
const status = statusList(db);
|
||||
console.log(`status: ${status.length ? '' : '(a blank sheet)'}`);
|
||||
for (const d of status) console.log(` - ${d}`);
|
||||
for (const ring of ['a', 'b', 'cold']) {
|
||||
const n = Number(db.prepare('SELECT COUNT(*) AS n FROM entries WHERE ring = ?').get(ring)?.n ?? 0);
|
||||
const cap = CAPS[ring] ?? 'none';
|
||||
@@ -1432,10 +1282,6 @@ switch (cmd) {
|
||||
case 'file': (args.length >= 2) ? cmdFile(args[0], args[1], args[2] ?? '', args[3]) : fail('usage: file <kind> "Label" "detail" ["reason"]'); break;
|
||||
case 'amend': (args.length >= 2) ? cmdAmend(args[0], args[1]) : fail('usage: amend <rid> "new detail"'); break;
|
||||
case 'discard': (args.length >= 1) ? cmdDiscard(args[0], args[1]) : fail('usage: discard <rid> "reason"'); break;
|
||||
case 'status': cmdStatus(); break;
|
||||
case 'status-set': cmdStatusSet(args); break; // no args = clear the status (a deliberate clear -- the player's empty block or a GM override)
|
||||
case 'agenda': cmdAgenda(); break;
|
||||
case 'agenda-set': cmdAgendaSet(args); break; // no args = clear the agenda
|
||||
case 'pick': cmdPick(args); break;
|
||||
case 'search': cmdSearch(args); break;
|
||||
case 'unarchive': (args.length >= 1) ? cmdUnarchive(args[0], args[1]) : fail('usage: unarchive <rid> [a|b]'); break;
|
||||
@@ -1443,6 +1289,6 @@ switch (cmd) {
|
||||
case 'dump': cmdDump(); break;
|
||||
case 'restore': cmdRestore(FORCE); break;
|
||||
default:
|
||||
console.error('usage: node tool/memory.mjs <packages|runs|create|save-package|init|render|apply|reapply|insert|delete|revive|file|amend|discard|search|unarchive|status|status-set|agenda|agenda-set|pick|dump|restore|report>');
|
||||
console.error('usage: node tool/memory.mjs <packages|runs|create|save-package|init|render|apply|reapply|insert|delete|revive|file|amend|discard|search|unarchive|pick|dump|restore|report>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
@@ -384,6 +384,9 @@ body.play #play-aside { display: block; }
|
||||
.pane-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
|
||||
.pane-editor-actions { display: flex; gap: 6px; margin-top: 6px; }
|
||||
.pane-editor-actions button { font-size: 12px; padding: 2px 12px; }
|
||||
.pane-pending { margin-top: 6px; display: flex; align-items: center; gap: 8px; color: var(--accent); font-size: 12px; }
|
||||
.pane-pending[hidden] { display: none; }
|
||||
.pane-pending button { font-size: 12px; padding: 2px 12px; }
|
||||
|
||||
#conflict {
|
||||
margin-top: 10px; padding: 8px; border: 1px solid var(--danger);
|
||||
|
||||
@@ -149,6 +149,17 @@ export function viaLine(via, fail = null) {
|
||||
return fail ? `[request failed] ${via.model}${p} -- ${fail}` : `[request] ${via.model}${p}`;
|
||||
}
|
||||
|
||||
// the GM's block edit, as the machinery line both walks show: the
|
||||
// override rides its turn as the record; the composition overwrites
|
||||
// her newest blocks with it
|
||||
/** @param {{ status?: string[], agenda?: string[] }} o @returns {string} */
|
||||
function overrideText(o) {
|
||||
const parts = [];
|
||||
if (o.status) parts.push(`status ${JSON.stringify(o.status)}`);
|
||||
if (o.agenda) parts.push(`agenda ${JSON.stringify(o.agenda)}`);
|
||||
return `[block edit] ${parts.join(' | ')} -- composes over her newest blocks`;
|
||||
}
|
||||
|
||||
// the note line, shared by both walks
|
||||
/** @param {NoteEvent} e @returns {?string} */
|
||||
function noteText(e) {
|
||||
@@ -166,6 +177,12 @@ function noteText(e) {
|
||||
}
|
||||
if (e.kind === 'pick') return `variant literature: ${e.count} offered, #${e.chosen + 1} picked`;
|
||||
if (e.kind === 'mind') return `mind: ${Object.entries(e.params ?? {}).map(([k, v]) => `${k} ${v}`).join(', ')} -- rides her next turn`;
|
||||
if (e.kind === 'state') {
|
||||
const parts = [];
|
||||
if (e.status) parts.push(`status ${JSON.stringify(e.status)}`);
|
||||
if (e.agenda) parts.push(`agenda ${JSON.stringify(e.agenda)}`);
|
||||
return `boundary state carried across the stop: ${parts.join(' | ')}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -227,6 +244,7 @@ export function renderRaw(entries) {
|
||||
if (e.t === 'msg' && e.m.role === 'user') {
|
||||
const d = block(e.conflictOnly ? 'gm -- conflict only' : 'gm');
|
||||
d.appendChild(el('pre', null, String(e.m.content ?? '')));
|
||||
if (e.override) d.appendChild(el('div', 'machinery', overrideText(e.override)));
|
||||
continue;
|
||||
}
|
||||
if (e.t === 'msg' && e.m.role === 'assistant') {
|
||||
@@ -326,6 +344,7 @@ export function renderTranscript(entries, { onConflict, onRaw } = {}) {
|
||||
d.appendChild(body);
|
||||
const { conflict } = renderContent(body, e.m.content, { extract: true });
|
||||
if (conflict) onConflict?.(conflict);
|
||||
if (e.override) d.appendChild(el('div', 'machinery', overrideText(e.override)));
|
||||
if (onRaw) addRawControl(head, d, idx);
|
||||
t.appendChild(d);
|
||||
}
|
||||
|
||||
+24
-10
@@ -27,7 +27,10 @@ let rawOpen = false;
|
||||
|
||||
// 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 wire formats the model cites. The edit button stages a block
|
||||
// edit -- it rides the next GM turn as the override (the composition
|
||||
// overwrites her newest blocks; the panes then show the composed
|
||||
// truth the scan derives).
|
||||
const statusPane = paneEditor({
|
||||
section: 'status-pane',
|
||||
body: 'status',
|
||||
@@ -39,7 +42,6 @@ const statusPane = paneEditor({
|
||||
fromText: (text) => text
|
||||
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+/, '').split(','))
|
||||
.map((x) => x.trim()).filter(Boolean),
|
||||
save: (items) => api(`/runs/${state.runId}/status`, { method: 'POST', body: { items } }),
|
||||
});
|
||||
const agendaPane = paneEditor({
|
||||
section: 'agenda-pane',
|
||||
@@ -47,14 +49,13 @@ const agendaPane = paneEditor({
|
||||
empty: 'a clear head',
|
||||
placeholder: 'one item per line, top first -- empty clears the agenda',
|
||||
rows: 4,
|
||||
// the pane renders bullets; the wire keeps the numbered form the
|
||||
// model cites (drops reference the indexes it was shown)
|
||||
// the pane renders bullets; the block grammar is the bullet list
|
||||
// invariants teaches
|
||||
format: (items) => items.map((d) => `- ${d}`).join('\n'),
|
||||
toText: (items) => items.join('\n'),
|
||||
fromText: (text) => text
|
||||
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(','))
|
||||
.map((x) => x.trim()).filter(Boolean),
|
||||
save: (items) => api(`/runs/${state.runId}/agenda`, { method: 'POST', body: { items } }),
|
||||
});
|
||||
|
||||
const models = modelsBox('models-pane', { title: 'models' });
|
||||
@@ -102,10 +103,12 @@ async function refreshPlay(id, seq) {
|
||||
agendaPane.set(detail.agenda);
|
||||
$('conflict').hidden = true;
|
||||
|
||||
// the owner's table: everything here edits -- anyone else was
|
||||
// redirected to the story above
|
||||
statusPane.setEditable(true);
|
||||
agendaPane.setEditable(true);
|
||||
// the owner's table, live only for the panes: a block edit rides a
|
||||
// turn, and turns need a live session -- dormancy edits the
|
||||
// carryover (the review window's one editing surface). Anyone else
|
||||
// was redirected to the story above.
|
||||
statusPane.setEditable(detail.phase === 'live');
|
||||
agendaPane.setEditable(detail.phase === 'live');
|
||||
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = false;
|
||||
|
||||
$('table-tabs').hidden = true; // the tabs are the live session's
|
||||
@@ -338,13 +341,24 @@ function setInput(ok) {
|
||||
async function sendTurn() {
|
||||
const line = /** @type {HTMLInputElement} */ ($('gm-input')).value.trim();
|
||||
if (!line || !state.runId) return;
|
||||
// staged block edits ride the turn (the override): only the kinds
|
||||
// staged attach, whole-list
|
||||
/** @type {{ line: string, status?: string[], agenda?: string[] }} */ const body = { line };
|
||||
if (statusPane.staged) body.status = statusPane.staged;
|
||||
if (agendaPane.staged) body.agenda = agendaPane.staged;
|
||||
if ((body.status || body.agenda) && line.startsWith('(')) {
|
||||
banner('a block edit cannot ride an OOC turn -- send it as a normal GM turn, or discard the edit');
|
||||
return; // the line stays in the box, the staging stays staged
|
||||
}
|
||||
/** @type {HTMLInputElement} */ ($('gm-input')).value = '';
|
||||
renderInputHl();
|
||||
setInput(false);
|
||||
setBusy(true);
|
||||
let failed = null;
|
||||
try {
|
||||
await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } });
|
||||
await api(`/runs/${state.runId}/turn`, { method: 'POST', body });
|
||||
statusPane.clearStaged(); // sent -- the panes re-render from the scan
|
||||
agendaPane.clearStaged();
|
||||
} catch (e) {
|
||||
failed = e.message;
|
||||
/** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line
|
||||
|
||||
+31
-27
@@ -4,7 +4,8 @@
|
||||
// - armedButton: the two-click confirm (no JS confirm() -- it blocks
|
||||
// the embedded pane; every destructive act is armed instead)
|
||||
// - paneEditor: the status/agenda pattern -- a body line, an edit
|
||||
// button, an inline editor; the section shell stays in index.html
|
||||
// button, an inline editor; the edit stages, the send rides it
|
||||
// with the turn; the section shell stays in index.html
|
||||
// - modelsBox: the per-run player/housekeeper selects over the
|
||||
// registry plus the sampling knobs (knobs.mjs owns the knob row
|
||||
// and its definitions table); setup and the play aside each carry
|
||||
@@ -14,7 +15,6 @@ import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { render } from './router.mjs';
|
||||
import { knobsBox } from './knobs.mjs';
|
||||
|
||||
// two-click confirm -- the second click within 5s fires; anything
|
||||
@@ -35,14 +35,16 @@ export function armedButton(btn, { label, confirm, fire }) {
|
||||
});
|
||||
}
|
||||
|
||||
// a pane: body line + edit button + inline editor. save(items)
|
||||
// resolves on success and throws on failure -- a failed save keeps
|
||||
// the editor open, nothing was changed. setEditable(false) is the
|
||||
// not-the-owner state: no edit button, an open editor cancels.
|
||||
/** @typedef {{ section: string|HTMLElement, body: string|HTMLElement, empty: string, placeholder: string, rows: number, format: (items: string[]) => string, toText: (items: string[]) => string, fromText: (text: string) => string[], save: (items: string[]) => Promise<unknown> }} PaneOpts */
|
||||
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[] }} Pane */
|
||||
// a pane: body line + edit button + inline editor. The edit does
|
||||
// not save anywhere -- it STAGES a block edit that rides the next
|
||||
// GM turn (the server logs the override on the turn; the composition
|
||||
// overwrites her newest blocks with it). setEditable(false) is the
|
||||
// not-live state: no edit button, an open editor cancels, a staged
|
||||
// edit drops -- dormancy edits the carryover, not the panes.
|
||||
/** @typedef {{ section: string|HTMLElement, body: string|HTMLElement, empty: string, placeholder: string, rows: number, format: (items: string[]) => string, toText: (items: string[]) => string, fromText: (text: string) => string[] }} PaneOpts */
|
||||
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[], staged: ?string[], clearStaged: () => void }} Pane */
|
||||
/** @param {PaneOpts} opts @returns {Pane} */
|
||||
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) {
|
||||
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText }) {
|
||||
const sec = typeof section === 'string' ? $(section) : section;
|
||||
const bodyEl = typeof body === 'string' ? $(body) : body;
|
||||
const editBtn = el('button', null, 'edit');
|
||||
@@ -53,15 +55,22 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
|
||||
area.rows = rows;
|
||||
area.placeholder = placeholder;
|
||||
const actions = el('div', 'pane-editor-actions');
|
||||
const saveBtn = el('button', null, 'save');
|
||||
const saveBtn = el('button', null, 'stage');
|
||||
const cancelBtn = el('button', null, 'cancel');
|
||||
actions.appendChild(saveBtn);
|
||||
actions.appendChild(cancelBtn);
|
||||
editor.appendChild(area);
|
||||
editor.appendChild(actions);
|
||||
bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane)
|
||||
const pending = el('div', 'pane-pending');
|
||||
pending.hidden = true;
|
||||
pending.appendChild(el('span', null, 'edited -- rides your next turn'));
|
||||
const dropBtn = el('button', null, 'discard edit');
|
||||
pending.appendChild(dropBtn);
|
||||
editor.after(pending);
|
||||
|
||||
/** @type {string[]} */ let items = [];
|
||||
/** @type {?string[]} */ let staged = null;
|
||||
let mayEdit = false;
|
||||
let open = false;
|
||||
|
||||
@@ -69,40 +78,35 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
|
||||
bodyEl.hidden = open;
|
||||
editBtn.hidden = open || !mayEdit;
|
||||
editor.hidden = !open;
|
||||
pending.hidden = staged === null;
|
||||
};
|
||||
const renderBody = () => {
|
||||
bodyEl.textContent = items.length ? format(items) : empty;
|
||||
bodyEl.classList.toggle('empty', !items.length);
|
||||
const show = staged ?? items;
|
||||
bodyEl.textContent = show.length ? format(show) : empty;
|
||||
bodyEl.classList.toggle('empty', !show.length);
|
||||
};
|
||||
const openEditor = () => {
|
||||
area.value = toText(items);
|
||||
area.value = toText(staged ?? items);
|
||||
open = true;
|
||||
sync();
|
||||
area.focus();
|
||||
};
|
||||
const cancel = () => { open = false; sync(); };
|
||||
const doSave = async () => {
|
||||
const next = fromText(area.value);
|
||||
try {
|
||||
await save(next);
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
return; // stay in the editor -- nothing was changed
|
||||
}
|
||||
items = next;
|
||||
cancel();
|
||||
render(); // the server's truth re-renders the panes
|
||||
};
|
||||
const doSave = () => { staged = fromText(area.value); cancel(); renderBody(); };
|
||||
const dropStaged = () => { staged = null; sync(); renderBody(); };
|
||||
|
||||
editBtn.addEventListener('click', openEditor);
|
||||
cancelBtn.addEventListener('click', cancel);
|
||||
saveBtn.addEventListener('click', doSave);
|
||||
dropBtn.addEventListener('click', dropStaged);
|
||||
|
||||
return {
|
||||
set(next) { items = next ?? []; renderBody(); },
|
||||
setEditable(ok) { mayEdit = ok; cancel(); },
|
||||
reset() { cancel(); },
|
||||
setEditable(ok) { mayEdit = ok; cancel(); if (!ok) dropStaged(); },
|
||||
reset() { cancel(); dropStaged(); },
|
||||
get items() { return items; },
|
||||
get staged() { return staged; },
|
||||
clearStaged: dropStaged,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user