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:
2026-11-16 22:49:50 +00:00
parent 894737fcf3
commit 5ffecee935
17 changed files with 581 additions and 465 deletions
+5 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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 */