Files
tiny-worlds/web/view-setup.mjs
mute 0ddb9a218d the package-authoring round: fork is the verb, the scaffold flag is the ready-to-run gate, the package editor is the owner's surface, and /packages is the launchpad
The design conversation settled the verb question (developer, 2026-11-19): a "create new package" with a base selector is fork under another name, so the SPA gains one list at /packages with three acts per card -- start (the run-create flow, unchanged), fork (any package, system or user, by anyone: the copy lands in state/packages owned by the forker, pc stripped, display name asked inline, the fork landing straight in the editor -- nobody forks to immediately start), and edit (the owner's own user packages only). /new retires to a redirect onto /packages; the source link (code.fleshless.org/hackmaster/tiny-worlds) rides the header.

The template's unplayability became machinery instead of a naming special-case: settings.json carries the "scaffold" flag (the records-bool precedent -- authored content carries the marker, machinery reads it). Create refuses a scaffold loudly on both ends ("fork it to author, then flip scaffold off in the editor"), the listing marks it, the SPA disables its start. The developer's ruling over my clear-the-flag draft: the flag RIDES FORKS UNTOUCHED -- a scaffold fork stays a scaffold until its author flips it off, so the flag is the package's doneness state, and publishing your own scaffold for others to fork is free. The settings editor is raw JSON for now (native UI later, the developer's "ready to run" toggle its eventual shape), with a hint teaching the keys.

The package editor (/packages/:name): every file of a user package is authoring material -- settings included -- with the cheap save lints (memory.json and settings.json must parse as JSON objects; the carryover passes the authored lint, the run surface's exact gate), the deep checks staying at the start gate where they already lived. The gates mirror the run precedent: system packages are repo-side and refuse ("fork to edit"); an ownerless user package is readable, forkable, never editable -- and an ownerless package IS forkable, the copy is yours.

The refactor the editor forced: the setup view's file-editor machinery (nav, textarea + the sigil/var highlight overlay, drafts, dirty marks, the save flow) extracted into widgets.mjs's fileEditor factory, parameterized over DOM ids and a PUT call -- setup keeps its run-side couplings (the phase-gated rw, the addressed session), the package editor is the simpler parameterization, and the editor CSS generalized from id selectors to classes so both surfaces share it.

En-route bug found and fixed: cmdCreate always copied the REPO's handbook.md into the run, so a user package's handbook -- which save-package faithfully copies out -- was silently ignored on re-create; the author's craft edit died in the round-trip. Create now prefers the package's own handbook when it carries one, else the repo's shared copy. The smoke proves the round-trip: a handbook marker authored through the package editor surfaces in the created run's files.

Browser-pass find: the pkgedit header state span and the editor's save-state span shared the id pkgedit-state, so the widget's select() wiped the header line -- the editor's span renamed (pkgedit-edit-state), verified rendering.

Verified: typecheck green both programs; smoke ALL PASS (+20 -- the fork battery: the template fork owner-stamped scaffold-preserved pc-stripped, create refusing the scaffold on both ends, the playable fork carrying no scaffold, fork validation, the editor gates owner-200/non-owner-403/system-repo-side-403/unknown-404, the raw-JSON and carryover save lints, the ready-to-run flip, create from the flipped fork, the handbook round-trip; and the ownerless pair: the editor refuses, the fork succeeds); restart + reminder checks green (6 runs); a browser pass on --mock --debug end to end -- the paste token re-landing after the state wipe, /new redirecting with the URL honest, the template card disabled with the scaffold note, boutique disabled as incomplete, the fork form prefill and submit landing in the editor, the scaffold state line, the settings flip and save making the card startable, the start-form flow intact, zero console errors; check-repo clean; the debug server back on the real state. Docs: README's packages passage (fork, scaffold, the editor, the gates), the booting flow, the layout tree (the clerk's fork-package verb, the view list, widgets.mjs); DICTIONARY's package, scaffold, and fork entries. The developer's queue line ('"create new package" in SPA') is struck by them in the same round. packages/detention stays untracked WIP, untouched.
2026-11-19 11:11:23 +00:00

260 lines
11 KiB
JavaScript

// web/view-setup.mjs -- the dormancy editor: the full assembly in
// bundle order (the repo-fed prompts read-only, the session's craft
// editable while dormant), the prompt-declared $TOKEN inputs, per-run
// models, and the exits -- save as package (a draft act, publishes
// it) or start (the dormant session goes live; a carryover ending on
// a GM turn sends automatically as her cue).
/** @typedef {import('./shapes.mjs').RunDetail} RunDetail */
/** @typedef {import('./shapes.mjs').FilesResponse} FilesResponse */
/** @typedef {import('./shapes.mjs').PromptsResponse} PromptsResponse */
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate, runGone } from './router.mjs';
import { logEvent } from './log.mjs';
import { armedButton, modelList, modelsBox, fileEditor } from './widgets.mjs';
// one list, in bundle-assembly order: the repo-fed system message
// parts (read-only -- the user should understand how the model is
// prompted), the craft tail and GM messages (editable while the
// session is dormant), then the opening material, then run config
// (read-only). Everything the session sends, nothing it doesn't.
const EDIT_LIST = [
{ name: 'system.md', mode: 'ro', source: 'repo' },
{ name: 'invariants.md', mode: 'ro', source: 'repo' },
{ name: 'reminder.md', mode: 'ro', source: 'repo' }, // rides every turn as its own system chunk
{ name: 'handbook.md', mode: 'rw', source: 'run' },
{ name: 'backdrop.md', mode: 'rw', source: 'run' },
{ name: 'character.md', mode: 'rw', source: 'run' },
{ name: 'memory.json', mode: 'ro', source: 'run' }, // her starting memories -- authored while the run is a draft; the start gate applies them
{ name: 'carryover.jsonl', mode: 'rw', source: 'run' }, // the opening log -- raw events, linted on save
{ name: 'settings.json', mode: 'ro', source: 'run' },
{ name: 'run.json', mode: 'ro', source: 'run' },
];
// per-file authoring hints: the formats the raw editor would otherwise
// ask the author to know by heart -- the save lint names violations,
// the hint teaches the shape up front
/** @type {Record<string, string>} */
const FILE_HINTS = {
'carryover.jsonl':
'one JSON object per line. A turn is {"t": "msg", "m": {"role": "assistant" or "user", "content": "..."}}. '
+ 'Her turn carries the <status> and <agenda> blocks; the sheet rides a GM turn as its "sheet" field, never as a tag. '
+ '@PC, @Package and $VARS expand at start (the authored opening only).',
};
// the shared editor widget over the run's file surface -- extracted
// when the package editor needed the same machinery (2026-11-19)
const editor = fileEditor(
{ nav: 'setup-files', edit: 'setup-edit', hl: 'edit-hl', save: 'setup-save', state: 'setup-edit-state', hint: 'edit-hint' },
{
put: (f, content) => api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } }),
hints: FILE_HINTS,
},
);
const models = modelsBox('setup-models', { title: 'models -- the run\'s picks' });
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters setup with a run id
state.runId = id;
/** @type {RunDetail} */ let detail;
/** @type {FilesResponse} */ let filesResp;
/** @type {PromptsResponse} */ let prompts;
try {
[detail, filesResp, prompts] = await Promise.all([
api(`/runs/${id}`),
api(`/runs/${id}/files`),
api('/prompts'),
]);
} catch (e) {
if (e.status === 404) return runGone(id, location.pathname);
// the editor is the owner's: everyone else reads the story
if (e.status === 403) return navigate(`/runs/${id}/story`);
return banner(`could not reach the server: ${e.message}`); // stay put -- transient
}
if (seq !== state.seq) return;
if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play
/** @type {Record<string, string>} */ const repoPrompts = {
'system.md': prompts.system ?? '',
'invariants.md': prompts.invariants ?? '',
'reminder.md': prompts.reminder ?? '',
};
$('setup-title').textContent = detail.display;
$('setup-state').textContent = detail.draft
? `${detail.run.package} \u00b7 ${id} -- draft; edits land when the session starts`
: `${detail.run.package} \u00b7 ${id} -- session ${detail.sessions} dormant, the review window`;
/** @type {HTMLButtonElement} */ ($('setup-start')).disabled = false;
$('setup-start').textContent = `start session ${detail.sessions}`;
// draft-only affordances: deletion and save-as-package (a package is
// a starting point, never a snapshot)
$('setup-delete').hidden = !detail.draft;
$('setup-savepkg').hidden = !detail.draft;
// prompt vars: the $TOKENS the prompts declare, filled per run
const vars = scanVars(prompts, filesResp.files);
/** @type {Record<string, string>} */ let currentVars = {};
try { currentVars = JSON.parse(filesResp.files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings -- empty vars */ }
const varsList = $('setup-vars-list');
varsList.textContent = '';
$('setup-vars').hidden = !vars.length;
$('setup-vars-state').textContent = '';
for (const tok of vars) {
const row = el('label', 'field', `$${tok}`);
const inp = /** @type {HTMLInputElement} */ (el('input'));
inp.dataset.token = tok;
inp.value = currentVars[tok] ?? '';
row.appendChild(inp);
varsList.appendChild(row);
}
// models: per-run overrides, selected from the registry
const mlist = await modelList();
if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist);
// the editor surface, composed in bundle order: the repo-fed prompts
// merged with the run's files, the API carrying the phase's truth
editor.load(EDIT_LIST.map((e) => {
const runFile = filesResp.files[e.name];
return {
name: e.name,
// rw only while dormant, and a continuation carryover is
// conversation -- read-only
mode: e.source === 'repo' ? 'ro' : (runFile?.mode ?? e.mode),
exists: e.source === 'repo' ? true : !!runFile?.exists,
content: e.source === 'repo' ? repoPrompts[e.name] : (runFile?.content ?? ''),
};
}));
editor.select('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
}
// the prompts declare their own inputs: every $TOKEN in any prompt
// file (repo-fed or the session's own, the carryover included -- it
// expands at start like every authored surface) becomes a fillable
// input in setup
/** @param {PromptsResponse} prompts @param {Record<string, { content?: string }>} files @returns {string[]} */
function scanVars(prompts, files) {
const texts = [
prompts.system, prompts.invariants, prompts.reminder,
files['handbook.md']?.content,
files['backdrop.md']?.content, files['character.md']?.content, files['carryover.jsonl']?.content,
];
const found = new Set();
for (const t of texts) {
if (!t) continue;
for (const m of t.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)) found.add(m[1]);
}
return [...found].sort();
}
/** @returns {Record<string, string>} */
function collectVars() {
/** @type {Record<string, string>} */ const vars = {};
for (const inp of /** @type {NodeListOf<HTMLInputElement>} */ ($('setup-vars-list').querySelectorAll('input'))) vars[/** @type {string} */ (inp.dataset.token)] = inp.value.trim();
return vars;
}
/** @returns {Promise<void>} */
async function saveVars() {
const vars = collectVars();
if (!Object.keys(vars).length) return;
await api(`/runs/${state.runId}/vars`, { method: 'POST', body: { vars } });
$('setup-vars-state').textContent = 'saved';
}
// save the run's craft as a new user package -- published to every user
// of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision.
/** @returns {Promise<void>} */
async function saveAsPackage() {
const name = /** @type {HTMLInputElement} */ ($('savepkg-name')).value.trim();
if (!name) return banner('the package needs a display name');
/** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = true;
$('savepkg-state').textContent = 'saving...';
try {
await editor.saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved -- ${r.package.id}`;
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
} catch (e) {
banner(e.message);
$('savepkg-state').textContent = 'not saved';
}
/** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = false;
}
/** @returns {Promise<void>} */
async function startRun() {
const id = state.runId;
const btn = /** @type {HTMLButtonElement} */ ($('setup-start'));
// the prompts' own inputs must be filled -- the guard at start is
// the backstop, not the first line of defense
for (const [tok, v] of Object.entries(collectVars())) {
if (!v) {
banner(`$${tok} is unfilled -- a prompt declares it, the run needs it`);
return;
}
}
btn.disabled = true;
btn.textContent = 'starting...';
try {
await saveVars();
await editor.saveDirty();
} catch (e) {
banner(`did not start -- ${e.message}`);
btn.disabled = false;
btn.textContent = 'start';
return;
}
try {
const r = await api(`/runs/${id}/sessions`, { method: 'POST', body: {} });
if (r.autoSend) logEvent('nav', 'the carryover ended on a GM turn -- sent automatically as her cue');
} catch (e) {
if (e.status === 422 && e.detail?.errors) {
banner(`the start refused:\n${e.detail.errors.join('\n')}`);
} else {
banner(e.message);
}
btn.disabled = false;
btn.textContent = 'start';
return;
}
navigate(`/runs/${id}`);
}
// --- wiring ---
// delete this draft: two-click armed (destructive), then home.
// A played run refuses server-side -- stories are deleted by hand.
armedButton($('setup-delete'), {
label: 'delete draft',
confirm: 'sure? click again to delete',
fire: async () => {
try {
await api(`/runs/${state.runId}`, { method: 'DELETE' });
navigate('/');
} catch (e) {
banner(e.message);
}
},
});
$('setup-vars-save').addEventListener('click', async () => {
try {
await saveVars();
} catch (e) {
banner(e.message);
$('setup-vars-state').textContent = 'not saved';
}
});
$('setup-start').addEventListener('click', startRun);
$('savepkg-btn').addEventListener('click', saveAsPackage);