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.
This commit is contained in:
2026-11-19 11:11:23 +00:00
parent 4b8fbd7471
commit 0ddb9a218d
19 changed files with 782 additions and 245 deletions
+18 -6
View File
@@ -111,9 +111,18 @@ e
. .
neither the key nor a clone. neither the key nor a clone.
- **the package** -- a preset: authored content only, no state. - **the package** -- a preset: authored content only, no state.
System packages ship with the repo; user packages are saved runs, System packages ship with the repo; user packages live in
published to the deployment (gm.md included -- saving is the act of `state/packages/` -- saved runs or forks, published to the
publishing). Read exactly once per run, ever -- at create. deployment (gm.md included -- saving is the act of publishing).
Read exactly once per run, ever -- at create. Forkable by anyone
(2026-11-19): the copy is the forker's own user package.
- **scaffold** -- a package's ready-to-run flag (2026-11-19): the
`"scaffold": true` key in settings.json holds a package out of
play -- create refuses it, the listing marks it. The template is
one; the flag rides forks untouched (a scaffold fork stays a
scaffold until its author flips it off -- the flag is the
package's doneness state), so publishing your own scaffold for
others to fork is free.
- **the run** -- one story: the package copied wholesale into - **the run** -- one story: the package copied wholesale into
`runs/<id>/` at create; from then the run directory is the only `runs/<id>/` at create; from then the run directory is the only
truth. The id is anonymous hex and carries no facts; the visible truth. The id is anonymous hex and carries no facts; the visible
@@ -325,9 +334,12 @@ e
story is the one public read, any signed-in user; fork is the way story is the one public read, any signed-in user; fork is the way
in. Ownership is resolved, never maintained: run.json keeps dead in. Ownership is resolved, never maintained: run.json keeps dead
owner ids, the API reads them as absent. owner ids, the API reads them as absent.
- **fork** -- an atomic copy of any run under the forker, window - **fork** -- an atomic copy under the forker. Runs and packages
state honestly carried. No lineage; the only mark is both: a run fork carries window state honestly (no lineage; the
`forked: unixtime` in run.json beside the carried `created`. only mark is `forked: unixtime` in run.json beside the carried
`created`), a package fork is the copy-to-author act (2026-11-19)
-- the copy lands in `state/packages/` owned by the forker, pc
stripped, scaffold flag preserved, `forked:` naming the source.
- **the rewind** -- the GM's take-back (2026-11-17): the send that - **the rewind** -- the GM's take-back (2026-11-17): the send that
carries `rewind` (a log line index naming a GM turn) replaces that carries `rewind` (a log line index naming a GM turn) replaces that
turn, and everything after it leaves the log outright -- physical turn, and everything after it leaves the log outright -- physical
+67
View File
@@ -9,6 +9,73 @@ file is the "where did we leave off" map.
## Where we are ## Where we are
- **The package-authoring round is BUILT and verified (2026-11-19,
developer-designed in conversation): fork is the verb, the scaffold
flag is the ready-to-run gate, and the package editor is the
owner's surface.** The design conversation settled it: a
"create new package" with a base selector is fork under another
name, so one list at /packages carries 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, forked: naming the
source), edit (the owner's own user packages only). The template's
unplayability became machinery: settings.json carries the
"scaffold" flag (the records-bool precedent -- authored content
carries the marker), create refuses a scaffold loudly on both
ends, the listing marks it, the SPA disables its start -- and the
flag RIDES FORKS UNTOUCHED (the developer's ruling over my
clear-the-flag draft): 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
editor (/packages/:name): every file of a user package is
authoring material -- settings included, raw JSON for now (native
UI later, the developer's "ready to run" toggle its eventual
shape) -- with the cheap save lints (memory.json and settings.json
must parse as JSON objects; the carryover passes the authored
lint), the deep checks staying at the start gate. The gates:
system packages are repo-side and refuse ("fork to edit");
ownerless user packages refuse too (the run precedent -- readable,
forkable, never editable), and an ownerless package IS forkable
(the copy is yours). Fork lands in the editor (the developer's
ruling: nobody forks to immediately start). The refactor the
editor forced: the setup view's file-editor machinery (nav,
textarea + highlight overlay, drafts, dirty marks, 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), pkgedit is the
simpler parameterization; the editor CSS generalized from ids to
classes. /new retired to a redirect onto /packages (old muscle
memory lands honest). The source link (the developer's ask) rides
the header: code.fleshless.org/hackmaster/tiny-worlds. 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. Create now prefers the
package's own handbook when it carries one, else the repo's shared
copy; the smoke proves the round-trip. 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 -- renamed (pkgedit-edit-state), the header line renders.
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-lands after the state wipe, /new
redirects with the URL honest, the template card disabled with the
scaffold note, boutique disabled as incomplete, 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, and the debug
server back on the real state. Docs: README's packages passage,
the booting flow, the layout tree; DICTIONARY's package, scaffold,
and fork entries. The developer's operator-queue line ('"create
new package" in SPA') is struck by them in the same round.
- **The debug round is BUILT and verified (2026-11-19, developer-designed - **The debug round is BUILT and verified (2026-11-19, developer-designed
in conversation): server.json is deleted, the bind is code, the in conversation): server.json is deleted, the bind is code, the
debug superuser is token-gated, and the context meter reads the debug superuser is token-gated, and the context meter reads the
+28 -6
View File
@@ -100,7 +100,19 @@ forking makes that cheap -- stories outlive identities by design.
- **Packages are system or user.** System packages ship with the repo; - **Packages are system or user.** System packages ship with the repo;
a user can save their run's craft as a user package under a user can save their run's craft as a user package under
`state/packages/` -- published to everyone, gm.md included (saving is `state/packages/` -- published to everyone, gm.md included (saving is
the act of publishing), the pc never riding. the act of publishing), the pc never riding. Any package is
forkable (developer, 2026-11-19): the copy lands in `state/packages/`
owned by the forker -- the copy-to-author act, one list at
`/packages` with start / fork / edit per card, the editor the
owner's alone (system packages are repo-side and refuse; an
ownerless package is readable, forkable, never editable). A
package's `settings.json` carries the ready-to-run flag:
`"scaffold": true` holds the package out of play (create refuses
it, the listing shows it) -- fork the template to author, flip the
flag off in the editor when the package is done; the flag rides
forks untouched (a scaffold fork stays a scaffold until its author
flips it), so publishing your own scaffold for others to fork is
free. The settings editor is raw JSON for now (native UI later).
- **Models are per-run picks of full specs.** A pick is - **Models are per-run picks of full specs.** A pick is
{provider, model, effort} -- there is no unset effort (it {provider, model, effort} -- there is no unset effort (it
substantially changes inference quality, so it is a property of the substantially changes inference quality, so it is a property of the
@@ -148,15 +160,19 @@ awaiting its design round; the table above is the design intent for it.
## Booting a run ## Booting a run
Through the CLI below, or through the SPA: home -> new run -> pick a Through the CLI below, or through the SPA: home -> new run -> the
package -> edit the copied prompts (project prompts inspectable package list (`/packages`, start / fork / edit per card) -> start ->
edit the copied prompts (project prompts inspectable
read-only alongside) -> **start** -- which takes dormant session one read-only alongside) -> **start** -- which takes dormant session one
live: the carryover is linted, the bundle freezes, the opening live: the carryover is linted, the bundle freezes, the opening
consumes into the log, in one action. The steps below walk every hat consumes into the log, in one action. The steps below walk every hat
on one head -- the package author's files (1-4), the deployment-side on one head -- the package author's files (1-4), the deployment-side
create (5), the GM's start (6); on a real deployment they split: a create (5), the GM's start (6); on a real deployment they split: a
user drafts and creates through the SPA, and the package files are user drafts and creates through the SPA, and the package files are
the author's, wherever they sit. the author's, wherever they sit -- authored in the repo, or forked
and edited in the SPA's package editor (every file of a user package
is authoring material; the handbook a package carries beats the
repo's shared copy at create).
1. **Backdrop** -- write `packages/<story>/backdrop.md`: the world as everyone 1. **Backdrop** -- write `packages/<story>/backdrop.md`: the world as everyone
in it knows it. Public knowledge, general setting. Neither memory nor in it knows it. Public knowledge, general setting. Neither memory nor
@@ -748,7 +764,8 @@ tsconfig.json tsc as a no-emit checker over the JSDoc annotations
names-female.txt the name dictionary -- one name per line; the new-run names-female.txt the name dictionary -- one name per line; the new-run
form rolls an unused one for the main character form rolls an unused one for the main character
tool/ tool/
memory.mjs the clerk: packages, runs, create, save-package, init, memory.mjs the clerk: packages, runs, create, save-package,
fork-package, init,
render, apply, insert, delete, revive, file, render, apply, insert, delete, revive, file,
amend, discard, search, unarchive, pick, dump, amend, discard, search, unarchive, pick, dump,
restore, report (her status and agenda never lived restore, report (her status and agenda never lived
@@ -865,9 +882,14 @@ web/ the SPA -- no build, vanilla ES modules, path-routed;
source verbatim -- the workbench renders no faces source verbatim -- the workbench renders no faces
(the book does: the story view carries its own (the book does: the story view carries its own
renderer) renderer)
view-*.mjs one module per view -- claim, home, new, setup, play view-*.mjs one module per view -- claim, home, packages (the
launchpad: start / fork / edit per card), pkgedit
(the package editor), setup, play
(the table), story (the whole deliverable, read-only) (the table), story (the whole deliverable, read-only)
-- each owning its elements, its state, and its wiring -- each owning its elements, its state, and its wiring
widgets.mjs the shared factories -- armedButton, paneEditor,
modelsBox, fileEditor (the editor surface setup and
pkgedit share)
style.css dark, quiet, fiction-first style.css dark, quiet, fiction-first
test/ the mock smoke, kept next to the code test/ the mock smoke, kept next to the code
smoke.mjs the multiuser/lifecycle/agenda/reminder/variant/ smoke.mjs the multiuser/lifecycle/agenda/reminder/variant/
-1
View File
@@ -6,7 +6,6 @@ be worked through one by one; statuses in caps, decisions dated.
## Developer's queue (don't edit, don't work on) ## Developer's queue (don't edit, don't work on)
- "create new package" in SPA
- calibration package: classic dungeon (pve, minimal npcs) - calibration package: classic dungeon (pve, minimal npcs)
- external sec review - external sec review
- refactor to add first-class GM agent - refactor to add first-class GM agent
+2 -1
View File
@@ -1,6 +1,7 @@
{ {
"comment": "`records` bool governs whether the storage db is available to the player; `pc` is the name you ship, very overridable", "comment": "`records` bool governs whether the storage db is available to the player; `pc` is the name you ship, very overridable; `scaffold` true holds the package out of play -- fork to author, flip it off when ready",
"records": false, "records": false,
"scaffold": true,
"name": "Template", "name": "Template",
"pc": "Facey McFaceface" "pc": "Facey McFaceface"
} }
+116
View File
@@ -667,6 +667,122 @@ route('POST', '/api/packages', async ({ body, user }) => {
return { package: JSON.parse(r.out) }; return { package: JSON.parse(r.out) };
}); });
// fork a package: the copy-to-author act (developer, 2026-11-19).
// Any package, system or user, forkable by anyone -- the copy lands
// in state/packages owned by the forker, scaffold flag preserved.
route('POST', '/api/packages/fork', async ({ body, user }) => {
const from = String(body.from ?? '').trim();
const name = String(body.name ?? '').trim();
if (!from) throw new HttpError(400, 'from (a package name) is required');
if (!name) throw new HttpError(400, 'name (the new package\'s display name) is required');
requireUser(user);
const r = clerkRaw('--quiet', '--json', '--owner', user.id, 'fork-package', from, name);
if (r.code !== 0) throw new HttpError(400, r.err || r.out || 'fork failed');
return { package: JSON.parse(r.out) };
});
// --- the package editor ---------------------------------------------------------
//
// The owner's authoring surface over a user package: the same fixed
// whitelist shape as the run files API, every file rw (a package is
// pre-run -- all of it is authoring material, settings included).
// System packages are repo-side and refuse; ownerless user packages
// are the departed's and refuse (the run precedent: an ownerless
// thing is readable and forkable, never editable). Save-time gates
// are the cheap cousins of the start gate's: memory.json and
// settings.json must parse as JSON objects, the carryover must pass
// the authored lint -- the deep checks still run at run creation.
/** One file of the package editor surface. */
/** @typedef {{ mode: 'rw', path: string }} PkgFileSpec */
/** @param {string} name @returns {?string} */
function packageDirOf(name) {
if (!/^[a-z0-9-]+$/.test(name)) return null;
const sys = path.join(ROOT, 'packages', name);
if (fs.existsSync(sys)) return sys;
const usr = path.join(ROOT, 'state', 'packages', name);
if (fs.existsSync(usr)) return usr;
return null;
}
/** The editor's gate: resolves the package dir for its owner, or
* refuses -- system (repo-side) and ownerless packages are not
* editable by anyone.
* @param {?UserRow} user @param {string} name @returns {string} */
function requirePackageOwner(user, name) {
const dir = packageDirOf(name);
if (!dir) throw new HttpError(404, `no such package: ${name}`);
if (!fs.existsSync(path.join(dir, 'package.json'))) {
throw new HttpError(403, 'system packages are repo-side and read-only -- fork to edit');
}
try {
const meta = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
if (meta.owner && user && meta.owner === user.id) return dir;
} catch { /* unreadable meta -- not editable */ }
throw new HttpError(403, 'this package is not yours to edit');
}
/** @param {string} dir @returns {Record<string, PkgFileSpec>} */
function packageFileSurface(dir) {
/** @type {Record<string, PkgFileSpec>} */
const spec = {};
for (const f of ['handbook.md', 'backdrop.md', 'character.md', 'memory.json', 'carryover.jsonl', 'settings.json', 'gm.md']) {
spec[f] = { mode: 'rw', path: path.join(dir, f) };
}
return spec;
}
route('GET', '/api/packages/:name/files', async ({ params, user }) => {
const dir = requirePackageOwner(user, params.name);
const spec = packageFileSurface(dir);
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */
const files = {};
for (const [f, s] of Object.entries(spec)) {
files[f] = fs.existsSync(s.path)
? { mode: s.mode, exists: true, content: fs.readFileSync(s.path, 'utf8') }
: { mode: s.mode, exists: false };
}
const settingsFile = files['settings.json'];
const settings = settingsFile?.exists ? JSON.parse(/** @type {string} */ (settingsFile.content)) : {};
return { display: settings.name ?? params.name, scaffold: settings.scaffold === true, files };
});
route('PUT', '/api/packages/:name/files/:path', async ({ params, body, user }) => {
const dir = requirePackageOwner(user, params.name);
const spec = packageFileSurface(dir)[params.path];
if (!spec) throw new HttpError(404, `no such package file in the API surface: ${params.path}`);
if (typeof body.content !== 'string' || !body.content.trim()) throw new HttpError(400, 'content (a non-empty string) is required');
if (params.path === 'memory.json' || params.path === 'settings.json') {
// the save-time gate is syntax only: JSON objects, the same cheap
// cousin as the run surface's -- the start gate judges the rest
try {
const o = JSON.parse(body.content);
if (typeof o !== 'object' || o === null || Array.isArray(o)) throw new Error();
} catch {
throw new HttpError(400, `${params.path} must be a JSON object`);
}
}
if (params.path === 'carryover.jsonl') {
// only clean openings land: the authored lint, the run surface's
// exact save-time gate
const lines = [];
const raw = body.content.split('\n');
for (let i = 0; i < raw.length; i++) {
if (!raw[i].trim()) continue;
try {
lines.push(JSON.parse(raw[i]));
} catch {
throw new HttpError(400, `not valid JSONL: line ${i + 1} does not parse`);
}
}
const errors = session.lintCarryover(lines, { authored: true });
if (errors.length) throw new HttpError(400, `the carryover did not pass the lint: ${errors.join('; ')}`);
}
fs.writeFileSync(spec.path, body.content);
return { ok: true, file: params.path, bytes: Buffer.byteLength(body.content) };
});
// the repo-fed prompts, read-only: per-project opening + guards, // the repo-fed prompts, read-only: per-project opening + guards,
// substrate invariants, and the per-turn reminder -- never copied into // substrate invariants, and the per-turn reminder -- never copied into
// a run, so the editor shows them as context, not as something to edit // a run, so the editor shows them as context, not as something to edit
+1 -1
View File
@@ -148,7 +148,7 @@ export {};
/** settings.json: identity (pc/name are the @ sigils), declared vars, /** settings.json: identity (pc/name are the @ sigils), declared vars,
* the records flag. */ * the records flag. */
/** @typedef {{ pc?: string, name?: string, records?: boolean, vars?: Record<string, string> }} RunSettings */ /** @typedef {{ pc?: string, name?: string, records?: boolean, scaffold?: boolean, vars?: Record<string, string> }} RunSettings */
/** A housekeeping manifest -- the housekeeper's whole write surface. */ /** A housekeeping manifest -- the housekeeper's whole write surface. */
/** @typedef {{ ring: 'a'|'b', type: string, label: string, detail?: string, reason: string }} InsertOp */ /** @typedef {{ ring: 'a'|'b', type: string, label: string, detail?: string, reason: string }} InsertOp */
+67 -1
View File
@@ -637,6 +637,68 @@ r = await call('/runs', { method: 'POST', token: op, body: { package: pkgId, pc:
ok('create from user package', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id); ok('create from user package', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const secondId = r.data.run?.id; const secondId = r.data.run?.id;
// 14b. the package fork battery (developer, 2026-11-19): fork is the
// copy-to-author act -- any package, the scaffold flag preserved
// (the flag is the package's doneness state: a scaffold fork stays a
// scaffold until the editor flips it off), the editor is the owner's
// alone, and create refuses a scaffold on both ends
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'template', name: 'My Scaffold' } });
ok('fork the template', r.status === 200 && r.data.package?.forked === 'template' && !!r.data.package?.id, JSON.stringify(r.data.package ?? r.data.error));
const tplFork = r.data.package?.id;
r = await call('/packages', { token: op });
const tplForkEntry = r.data.find((p) => p.name === tplFork);
ok('the fork is a user package, owner-stamped, scaffold preserved, pc stripped',
!!tplForkEntry && tplForkEntry.origin === 'user' && tplForkEntry.ownerName === 'Op' && tplForkEntry.scaffold === true
&& tplForkEntry.display === 'My Scaffold' && tplForkEntry.pc === null,
JSON.stringify(tplForkEntry ?? null));
r = await call('/runs', { method: 'POST', token: op, body: { package: 'template', pc: 'Nobody', name: 'x' } });
ok('create from a scaffold refuses', r.status === 400 && /scaffold/.test(r.data.error), r.data.error ?? '');
r = await call('/runs', { method: 'POST', token: op, body: { package: tplFork, pc: 'Nobody', name: 'x' } });
ok('create from the scaffold fork refuses too (the flag rides)', r.status === 400 && /scaffold/.test(r.data.error), r.data.error ?? '');
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'la-caramba', name: 'Caramba Variant' } });
ok('fork a playable package', r.status === 200 && r.data.package?.forked === 'la-caramba', JSON.stringify(r.data.package ?? r.data.error));
const carambaFork = r.data.package?.id;
r = await call('/packages', { token: op });
ok('a fork of a playable package carries no scaffold', r.data.find((p) => p.name === carambaFork)?.scaffold === false,
JSON.stringify(r.data.find((p) => p.name === carambaFork) ?? null));
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'template' } });
ok('fork needs a display name', r.status === 400, r.data.error ?? '');
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: 'nope', name: 'x' } });
ok('fork of an unknown package refuses', r.status === 400 && /no such package/.test(r.data.error), r.data.error ?? '');
// 14c. the package editor: the owner's authoring surface, every file
// rw (settings included -- raw JSON for now), the cheap save lints,
// and the ready-to-run flip
r = await call(`/packages/${tplFork}/files`, { token: op });
ok('the owner reads the editor surface',
r.status === 200 && r.data.files['settings.json']?.exists === true && r.data.scaffold === true && r.data.display === 'My Scaffold',
JSON.stringify(r.data.files ? { display: r.data.display, scaffold: r.data.scaffold } : r.data));
r = await call(`/packages/${tplFork}/files`, { token: ash });
ok("the editor is the owner's", r.status === 403, r.data.error ?? '');
r = await call('/packages/la-caramba/files', { token: op });
ok('system packages refuse the editor (repo-side)', r.status === 403 && /repo-side/.test(r.data.error), r.data.error ?? '');
r = await call('/packages/nope/files', { token: op });
ok('an unknown package 404s', r.status === 404, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/settings.json`, { method: 'PUT', token: op, body: { content: '{ not json' } });
ok('settings must parse (the raw JSON editor)', r.status === 400 && /JSON object/.test(r.data.error), r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/carryover.jsonl`, { method: 'PUT', token: op, body: { content: 'nope' } });
ok('the carryover save lint holds on the package editor', r.status === 400, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/backdrop.md`, { method: 'PUT', token: op, body: { content: '# My forked backdrop\n\nA new island.\n' } });
ok('the owner writes a file', r.status === 200, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/handbook.md`, { method: 'PUT', token: op, body: { content: "# The fork's own handbook\n\nCraft marker: unique-to-the-fork.\n" } });
ok('the handbook is authorable on the package', r.status === 200, r.data.error ?? '');
r = await call(`/packages/${tplFork}/files/settings.json`, { method: 'PUT', token: op, body: { content: JSON.stringify({ records: false, scaffold: false, name: 'My Scaffold' }, null, 2) + '\n' } });
ok('the ready-to-run flip (scaffold off)', r.status === 200, r.data.error ?? '');
r = await call('/packages', { token: op });
ok('the listing reflects the flip', r.data.find((p) => p.name === tplFork)?.scaffold === false, '');
r = await call('/runs', { method: 'POST', token: op, body: { package: tplFork, pc: 'Forkina', name: 'Fork Story' } });
ok('create from the flipped fork', r.status === 200 && !!r.data.run?.id, r.data.error ?? r.data.run?.id);
const forkRunId = r.data.run?.id;
r = await call(`/runs/${forkRunId}/files`, { token: op });
ok("the handbook round-trips (the package's own beats the repo default)",
r.data.files['handbook.md']?.content?.includes('unique-to-the-fork') === true,
JSON.stringify((r.data.files['handbook.md']?.content ?? '').slice(0, 60)));
// 15. op revokes ash -- identity destroyed, data stays // 15. op revokes ash -- identity destroyed, data stays
r = await call(`/users/${ashId}/revoke`, { method: 'POST', token: op, body: {} }); r = await call(`/users/${ashId}/revoke`, { method: 'POST', token: op, body: {} });
ok('revoke ash', r.status === 200, r.data.error ?? ''); ok('revoke ash', r.status === 200, r.data.error ?? '');
@@ -652,6 +714,10 @@ r = await call('/packages', { token: op });
const saved2 = r.data.find((p) => p.name === pkgId); const saved2 = r.data.find((p) => p.name === pkgId);
ok('user package survives, ownerless', !!saved2 && saved2.owner === null && saved2.ownerName === null && saved2.display === 'Ash Pack', ok('user package survives, ownerless', !!saved2 && saved2.owner === null && saved2.ownerName === null && saved2.display === 'Ash Pack',
JSON.stringify(saved2)); JSON.stringify(saved2));
r = await call(`/packages/${pkgId}/files`, { token: op });
ok('an ownerless package refuses the editor (readable, forkable, never editable)', r.status === 403 && /not yours/.test(r.data.error), r.data.error ?? '');
r = await call('/packages/fork', { method: 'POST', token: op, body: { from: pkgId, name: 'Ash Pack Continued' } });
ok('an ownerless package is forkable (the copy is yours)', r.status === 200 && r.data.package?.forked === pkgId, JSON.stringify(r.data.package ?? r.data.error));
r = await call(`/runs/${forkId}/fork`, { method: 'POST', token: op, body: {} }); r = await call(`/runs/${forkId}/fork`, { method: 'POST', token: op, body: {} });
ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run); ok('op forks the ownerless run', r.status === 200 && !!r.data.run, r.data.error ?? r.data.run);
const reforkId = r.data.run; const reforkId = r.data.run;
@@ -1087,7 +1153,7 @@ ok('the sheet crossed the boundary (the note feeds the new session\'s scan)', JS
} }
ok('the restored world refined', jobR?.state === 'applied', JSON.stringify(jobR ?? null)); ok('the restored world refined', jobR?.state === 'applied', JSON.stringify(jobR ?? null));
} }
console.log(`\nrun ids: source=${runId} draft=${draftId} fork=${forkId} second=${secondId} refork=${reforkId}`); console.log(`\nrun ids: source=${runId} draft=${draftId} fork=${forkId} second=${secondId} refork=${reforkId} fork-story=${forkRunId}`);
writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`); writeFileSync(TOKEN_FILE, `${op} ${reforkId} ${secondId}`);
console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS'); console.log(failures ? `\n${failures} FAILURES` : '\nALL PASS');
process.exit(failures ? 1 : 0); process.exit(failures ? 1 : 0);
+68 -5
View File
@@ -21,6 +21,10 @@
// save-package "display name" save a DRAFT's craft as a new user // save-package "display name" save a DRAFT's craft as a new user
// package (state/packages/, published to // package (state/packages/, published to
// all; pc never rides; --owner stamps) // all; pc never rides; --owner stamps)
// fork-package <pkg> "display" copy any package into state/packages
// as a user package (owner stamped, pc
// never rides, scaffold flag preserved
// -- the copy-to-author act)
// init build session one of a fresh run // init build session one of a fresh run
// (the low-level primitive under create) // (the low-level primitive under create)
// render write canon/ring-a.md, ring-b.md // render write canon/ring-a.md, ring-b.md
@@ -74,7 +78,7 @@
/** @typedef {{ phase?: string, ready?: boolean, [k: string]: unknown }} SessionMeta */ /** @typedef {{ phase?: string, ready?: boolean, [k: string]: unknown }} SessionMeta */
/** One package as `packages` lists it. */ /** One package as `packages` lists it. */
/** @typedef {{ name: string, origin: 'system'|'user', owner?: ?string, display: string, pc: ?string, records: boolean, carryover: boolean, memory: boolean, complete: boolean }} PackageListed */ /** @typedef {{ name: string, origin: 'system'|'user', owner?: ?string, display: string, pc: ?string, records: boolean, scaffold: boolean, carryover: boolean, memory: boolean, complete: boolean }} PackageListed */
/** One run as `runs` lists it (fill is present exactly when initialized). */ /** One run as `runs` lists it (fill is present exactly when initialized). */
/** @typedef {{ id: string, package: string, models: ?{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, owner: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number } }} RunListed */ /** @typedef {{ id: string, package: string, models: ?{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }, owner: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number } }} RunListed */
@@ -159,7 +163,7 @@ const [cmd, ...args] = argv;
// a run is an instance under runs/, created from a package by `create`; // a run is an instance under runs/, created from a package by `create`;
// state is per-deployment -- a fresh clone has zero runs // state is per-deployment -- a fresh clone has zero runs
const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick']); const NO_RUN_NEEDED = new Set(['runs', 'packages', 'create', 'pick', 'fork-package']);
const RUN = NO_RUN_NEEDED.has(cmd ?? '') ? null : runOverride; const RUN = NO_RUN_NEEDED.has(cmd ?? '') ? null : runOverride;
if (!NO_RUN_NEEDED.has(cmd ?? '') && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) { if (!NO_RUN_NEEDED.has(cmd ?? '') && (!RUN || !/^[a-z0-9-]+$/.test(RUN))) {
fail('no run specified -- use --run <id> (see: runs); runs are created with: create <package> <pc-name>'); fail('no run specified -- use --run <id> (see: runs); runs are created with: create <package> <pc-name>');
@@ -837,6 +841,11 @@ function packageEntry(name, dir, origin) {
display: settings.name ?? name, display: settings.name ?? name,
pc: settings.pc ?? null, pc: settings.pc ?? null,
records: settings.records === true, records: settings.records === true,
// the ready-to-run flag (developer, 2026-11-19): a scaffold is
// authoring material, not a story -- create refuses it, fork
// copies it, the editor's settings flip it off when the package
// is ready
scaffold: settings.scaffold === true,
carryover: has('carryover.jsonl'), memory: has('memory.json'), carryover: has('carryover.jsonl'), memory: has('memory.json'),
complete: has('backdrop.md') && has('character.md'), complete: has('backdrop.md') && has('character.md'),
}; };
@@ -858,7 +867,7 @@ function cmdPackages() {
if (AS_JSON) { console.log(JSON.stringify(list)); return; } if (AS_JSON) { console.log(JSON.stringify(list)); return; }
if (!list.length) { console.log('(no packages)'); return; } if (!list.length) { console.log('(no packages)'); return; }
for (const x of list) { for (const x of list) {
console.log(`${x.name}: ${x.display} [${x.origin}] -- records ${x.records ? 'on' : 'off'} \u00b7 carryover ${x.carryover ? 'yes' : 'no'} \u00b7 memory ${x.memory ? 'yes' : 'no'} \u00b7 backdrop+card ${x.complete ? 'ok' : 'MISSING'}`); console.log(`${x.name}: ${x.display} [${x.origin}] -- records ${x.records ? 'on' : 'off'}${x.scaffold ? ' \u00b7 SCAFFOLD (fork to author)' : ''} \u00b7 carryover ${x.carryover ? 'yes' : 'no'} \u00b7 memory ${x.memory ? 'yes' : 'no'} \u00b7 backdrop+card ${x.complete ? 'ok' : 'MISSING'}`);
} }
} }
@@ -889,6 +898,12 @@ function cmdCreate(pkgName, pc, displayName) {
} }
const pkgDir = packageDir(pkgName); const pkgDir = packageDir(pkgName);
if (!pkgDir) fail(`no such package: ${pkgName} -- see: packages`); if (!pkgDir) fail(`no such package: ${pkgName} -- see: packages`);
// a scaffold is authoring material, never a story (developer,
// 2026-11-19): the fork copies it, the editor's settings flip it
// off when the package is ready to run
if (readRunSettings(pkgDir).scaffold === true) {
fail(`'${pkgName}' is a scaffold -- fork it to author, then flip "scaffold" off in the editor`);
}
pc = String(pc).trim(); pc = String(pc).trim();
// different runs of the same package require different pc names // different runs of the same package require different pc names
if (fs.existsSync(RUNS_DIR)) { if (fs.existsSync(RUNS_DIR)) {
@@ -919,7 +934,13 @@ function cmdCreate(pkgName, pc, displayName) {
fs.mkdirSync(path.dirname(dst), { recursive: true }); fs.mkdirSync(path.dirname(dst), { recursive: true });
fs.copyFileSync(src, dst); fs.copyFileSync(src, dst);
} }
const hb = path.join(ROOT, 'handbook.md'); // the handbook: the package's own when it carries one (the
// save-package round-trip -- an authored or edited handbook is
// craft, and losing it on re-create was a bug), else the repo's
// shared copy
const hb = fs.existsSync(path.join(pkgDir, 'handbook.md'))
? path.join(pkgDir, 'handbook.md')
: path.join(ROOT, 'handbook.md');
if (fs.existsSync(hb)) { if (fs.existsSync(hb)) {
fs.mkdirSync(path.join(s1, 'bundle'), { recursive: true }); fs.mkdirSync(path.join(s1, 'bundle'), { recursive: true });
fs.copyFileSync(hb, path.join(s1, 'bundle', 'handbook.md')); fs.copyFileSync(hb, path.join(s1, 'bundle', 'handbook.md'));
@@ -1051,6 +1072,47 @@ function cmdSavePackage(displayName) {
console.log(`saved package '${id}' -- ${name}: ${rel(dst)}`); console.log(`saved package '${id}' -- ${name}: ${rel(dst)}`);
} }
// fork a package: the copy-to-author act (developer, 2026-11-19).
// Everything rides -- gm.md included, the save-package publishing
// precedent -- into state/packages as a user package owned by the
// forker. The display name is the fork's one decision; the pc never
// rides (the next create asks for one); the scaffold flag rides
// untouched (a scaffold fork stays a scaffold until the author flips
// it off -- the flag is the package's doneness state, and publishing
// your own scaffold for others to fork is free).
/** @param {?string} fromName @param {?string} displayName */
function cmdForkPackage(fromName, displayName) {
const name = String(displayName ?? '').trim();
if (!fromName || !name) fail('usage: fork-package <package> "display name"');
const src = packageDir(fromName);
if (!src) fail(`no such package: ${fromName} -- see: packages`);
/** @type {string} */ let id;
for (;;) {
id = randomBytes(4).toString('hex');
if (!fs.existsSync(path.join(STATE_PACKAGES_DIR, id)) && !fs.existsSync(path.join(PACKAGES_DIR, id))) break;
}
const dst = path.join(STATE_PACKAGES_DIR, id);
fs.mkdirSync(dst, { recursive: true });
for (const f of fs.readdirSync(src)) {
const p = path.join(src, f);
if (fs.statSync(p).isFile()) fs.copyFileSync(p, path.join(dst, f));
}
const settingsPath = path.join(dst, 'settings.json');
/** @type {RunSettings} */ let settings = {};
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch {}
settings.name = name;
delete settings.pc; // per-run identity never rides a package
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
fs.writeFileSync(path.join(dst, 'package.json'), JSON.stringify({
owner: ownerOverride, created: today(), forked: fromName,
}, null, 2) + '\n');
if (AS_JSON) {
console.log(JSON.stringify({ id, name, origin: 'user', owner: ownerOverride, forked: fromName }));
return;
}
console.log(`forked package '${id}' -- ${name} (from ${fromName}): ${rel(dst)}`);
}
/** @param {string} ring @param {string} type @param {string} label @param {?string} [detail] */ /** @param {string} ring @param {string} type @param {string} label @param {?string} [detail] */
function gmOp(ring, type, label, detail) { function gmOp(ring, type, label, detail) {
const db = openDb(); const db = openDb();
@@ -1271,6 +1333,7 @@ switch (cmd) {
case 'runs': cmdRuns(); break; case 'runs': cmdRuns(); break;
case 'create': cmdCreate(args[0], args[1], args[2]); break; case 'create': cmdCreate(args[0], args[1], args[2]); break;
case 'save-package': cmdSavePackage(args[0]); break; case 'save-package': cmdSavePackage(args[0]); break;
case 'fork-package': cmdForkPackage(args[0], args[1]); break;
case 'init': cmdInit(); break; case 'init': cmdInit(); break;
case 'render': renderAll(openDb()); break; case 'render': renderAll(openDb()); break;
case 'apply': args[0] ? cmdApply(args[0]) : fail('usage: apply <manifest.json>'); break; case 'apply': args[0] ? cmdApply(args[0]) : fail('usage: apply <manifest.json>'); break;
@@ -1288,6 +1351,6 @@ switch (cmd) {
case 'dump': cmdDump(); break; case 'dump': cmdDump(); break;
case 'restore': cmdRestore(FORCE); break; case 'restore': cmdRestore(FORCE); break;
default: 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|pick|dump|restore|report>'); console.error('usage: node tool/memory.mjs <packages|runs|create|save-package|fork-package|init|render|apply|reapply|insert|delete|revive|file|amend|discard|search|unarchive|pick|dump|restore|report>');
process.exit(1); process.exit(1);
} }
+9 -6
View File
@@ -1,10 +1,11 @@
// web/app.mjs -- the SPA entry: view registration and boot. // web/app.mjs -- the SPA entry: view registration and boot.
// //
// The SPA is strictly a client of the REST API. Path-routed views // The SPA is strictly a client of the REST API. Path-routed views
// (router.mjs): / (home: runs to pick up), /new (package picker), // (router.mjs): / (home: runs to pick up), /packages (the package
// /runs/<id>/setup (the dormancy editor; start freezes the bundle and // launchpad -- start a run, fork to author, edit your own),
// consumes the carryover), // /packages/<name> (the package editor), /runs/<id>/setup (the
// /runs/<id> (play). The server serves the shell for any // dormancy editor; start freezes the bundle and consumes the
// carryover), /runs/<id> (play). The server serves the shell for any
// extensionless path. // extensionless path.
import { $ } from './dom.mjs'; import { $ } from './dom.mjs';
@@ -13,7 +14,8 @@ import { state } from './state.mjs';
import { navigate, registerViews, render } from './router.mjs'; import { navigate, registerViews, render } from './router.mjs';
import * as claim from './view-claim.mjs'; import * as claim from './view-claim.mjs';
import * as home from './view-home.mjs'; import * as home from './view-home.mjs';
import * as newRun from './view-new.mjs'; import * as packages from './view-packages.mjs';
import * as pkgedit from './view-pkgedit.mjs';
import * as setup from './view-setup.mjs'; import * as setup from './view-setup.mjs';
import * as play from './view-play.mjs'; import * as play from './view-play.mjs';
import * as story from './view-story.mjs'; import * as story from './view-story.mjs';
@@ -23,7 +25,8 @@ $('home-link').addEventListener('click', (e) => { e.preventDefault(); navigate('
registerViews({ registerViews({
claim: { el: 'view-claim', enter: claim.enter }, claim: { el: 'view-claim', enter: claim.enter },
home: { el: 'view-home', enter: home.enter }, home: { el: 'view-home', enter: home.enter },
new: { el: 'view-new', enter: newRun.enter }, packages: { el: 'view-packages', enter: packages.enter },
pkgedit: { el: 'view-pkgedit', enter: pkgedit.enter },
setup: { el: 'view-setup', enter: setup.enter }, setup: { el: 'view-setup', enter: setup.enter },
play: { el: 'view-play', enter: play.enter, leave: play.leave }, play: { el: 'view-play', enter: play.enter, leave: play.leave },
story: { el: 'view-story', enter: story.enter }, story: { el: 'view-story', enter: story.enter },
+34 -11
View File
@@ -16,6 +16,7 @@
<span id="context-label"></span> <span id="context-label"></span>
</div> </div>
<button id="diag-btn" title="diagnostics log">log</button> <button id="diag-btn" title="diagnostics log">log</button>
<a id="source-link" href="https://code.fleshless.org/hackmaster/tiny-worlds" target="_blank" rel="noreferrer">source</a>
</header> </header>
<main> <main>
@@ -70,10 +71,10 @@
</section> </section>
</section> </section>
<section id="view-new" hidden> <section id="view-packages" hidden>
<h1>new run</h1> <h1>packages</h1>
<div id="package-pick"> <div id="package-pick">
<p class="hint">a run is a copy of the package -- everything stays editable until the session opens</p> <p class="hint">a run is a copy of the package -- everything stays editable until the session opens. Fork copies any package to author; scaffolds refuse to start.</p>
<div id="package-list"></div> <div id="package-list"></div>
</div> </div>
<form id="create-form" hidden> <form id="create-form" hidden>
@@ -87,6 +88,28 @@
</form> </form>
</section> </section>
<section id="view-pkgedit" hidden>
<div class="setup-head">
<h1 id="pkgedit-title"></h1>
<span id="pkgedit-state"></span>
<button id="pkgedit-back">back to packages</button>
</div>
<div class="setup-body">
<nav id="pkgedit-files" class="files-nav"></nav>
<div class="edit-col">
<div class="edit-stack">
<pre id="pkgedit-hl" class="edit-hl" aria-hidden="true"></pre>
<textarea id="pkgedit-edit" class="edit-area" spellcheck="false"></textarea>
</div>
<div id="pkgedit-hint" class="edit-hint" hidden></div>
<div class="edit-bar">
<button id="pkgedit-save">save</button>
<span id="pkgedit-edit-state" class="edit-state"></span>
</div>
</div>
</div>
</section>
<section id="view-setup" hidden> <section id="view-setup" hidden>
<div class="setup-head"> <div class="setup-head">
<h1 id="setup-title"></h1> <h1 id="setup-title"></h1>
@@ -109,16 +132,16 @@
<span id="savepkg-state"></span> <span id="savepkg-state"></span>
</div> </div>
<div class="setup-body"> <div class="setup-body">
<nav id="setup-files"></nav> <nav id="setup-files" class="files-nav"></nav>
<div id="setup-editor"> <div id="setup-editor" class="edit-col">
<div id="edit-stack"> <div id="edit-stack" class="edit-stack">
<pre id="edit-hl" aria-hidden="true"></pre> <pre id="edit-hl" class="edit-hl" aria-hidden="true"></pre>
<textarea id="setup-edit" spellcheck="false"></textarea> <textarea id="setup-edit" class="edit-area" spellcheck="false"></textarea>
</div> </div>
<div id="edit-hint" hidden></div> <div id="edit-hint" class="edit-hint" hidden></div>
<div id="setup-edit-bar"> <div id="setup-edit-bar" class="edit-bar">
<button id="setup-save">save</button> <button id="setup-save">save</button>
<span id="setup-edit-state"></span> <span id="setup-edit-state" class="edit-state"></span>
</div> </div>
</div> </div>
</div> </div>
+5 -1
View File
@@ -33,6 +33,9 @@ window.addEventListener('popstate', () => render());
export async function render() { export async function render() {
const seq = ++state.seq; const seq = ++state.seq;
hideBanner(); hideBanner();
// the package list moved to /packages (2026-11-19): old muscle
// memory lands there, the URL honest
if (location.pathname === '/new') history.replaceState({}, '', '/packages');
const p = location.pathname; const p = location.pathname;
/** @type {?string} */ /** @type {?string} */
let name = null; let name = null;
@@ -40,7 +43,8 @@ export async function render() {
let arg = null; let arg = null;
let m; let m;
if (p === '/') name = 'home'; if (p === '/') name = 'home';
else if (p === '/new') name = 'new'; else if (p === '/packages') name = 'packages';
else if ((m = p.match(/^\/packages\/([a-z0-9-]+)$/))) { name = 'pkgedit'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/setup$/))) { name = 'setup'; arg = m[1]; } else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/setup$/))) { name = 'setup'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/story$/))) { name = 'story'; arg = m[1]; } else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/story$/))) { name = 'story'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; } else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; }
+14 -10
View File
@@ -226,7 +226,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; color: var(--dim); font-weight: nor
height: calc(100vh - 130px); height: calc(100vh - 130px);
} }
#setup-files { overflow-y: auto; } .files-nav { overflow-y: auto; }
.file-item { .file-item {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@@ -245,11 +245,11 @@ h1 { font-size: 15px; letter-spacing: 0.1em; color: var(--dim); font-weight: nor
.file-item.ro { color: var(--dim); } .file-item.ro { color: var(--dim); }
.file-item.dirty .file-dirty { color: var(--accent); } .file-item.dirty .file-dirty { color: var(--accent); }
#setup-editor { display: flex; flex-direction: column; min-width: 0; } .edit-col { display: flex; flex-direction: column; min-width: 0; }
#edit-stack { position: relative; flex: 1; min-height: 0; } .edit-stack { position: relative; flex: 1; min-height: 0; }
/* the highlight overlay: a pre behind a transparent-text textarea, /* the highlight overlay: a pre behind a transparent-text textarea,
identical metrics, scroll-synced -- sigils and vars light up in place */ identical metrics, scroll-synced -- sigils and vars light up in place */
#edit-hl, #setup-edit { .edit-hl, .edit-area {
position: absolute; position: absolute;
inset: 0; inset: 0;
margin: 0; margin: 0;
@@ -260,20 +260,24 @@ h1 { font-size: 15px; letter-spacing: 0.1em; color: var(--dim); font-weight: nor
border: 1px solid var(--line); border: 1px solid var(--line);
border-radius: 4px; border-radius: 4px;
} }
#edit-hl { pointer-events: none; overflow: hidden; color: var(--text); border-color: transparent; } .edit-hl { pointer-events: none; overflow: hidden; color: var(--text); border-color: transparent; }
#setup-edit { .edit-area {
background: transparent; background: transparent;
color: transparent; color: transparent;
caret-color: var(--text); caret-color: var(--text);
resize: none; resize: none;
overflow-y: auto; overflow-y: auto;
} }
#setup-edit::selection { background: rgba(201, 162, 109, 0.3); } .edit-area::selection { background: rgba(201, 162, 109, 0.3); }
.tok-sigil { color: var(--accent); } .tok-sigil { color: var(--accent); }
.tok-var { color: var(--ok); } .tok-var { color: var(--ok); }
#setup-edit-bar { display: flex; align-items: center; gap: 10px; margin-top: 8px; } .edit-bar { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
#setup-edit-state { color: var(--dim); font-size: 12px; } .edit-state { color: var(--dim); font-size: 12px; }
#edit-hint { color: var(--dim); font-size: 12px; margin-top: 8px; } .edit-hint { color: var(--dim); font-size: 12px; margin-top: 8px; }
.pkg-actions { margin-top: 6px; }
.pkg-fork-form { display: flex; gap: 8px; margin-top: 8px; }
.pkg-fork-form input { flex: 1; }
#source-link { font-size: 11px; color: var(--dim); }
/* --- transcript (play) --- */ /* --- transcript (play) --- */
+1 -1
View File
@@ -416,7 +416,7 @@ $('provider-add-go').addEventListener('click', async () => {
dropModelCache(); dropModelCache();
render(); render();
}); });
$('new-run-btn').addEventListener('click', () => navigate('/new')); $('new-run-btn').addEventListener('click', () => navigate('/packages'));
$('invite-mint').addEventListener('click', async () => { $('invite-mint').addEventListener('click', async () => {
try { try {
const r = await api('/invites', { method: 'POST', body: {} }); const r = await api('/invites', { method: 'POST', body: {} });
-62
View File
@@ -1,62 +0,0 @@
// web/view-new.mjs -- new run: the package picker, then the naming
// form -- the package display name plus the main character's name,
// rolled from the dictionary, unused by any run. Runs of the same
// package need distinct pc names.
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate } from './router.mjs';
/** @type {?{ display: string, name: string }} */ let pkg = null; // the picked package -- the view owns it
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
$('package-pick').hidden = false;
$('create-form').hidden = true;
const pkgs = await api('/packages');
if (seq !== state.seq) return;
const list = $('package-list');
list.textContent = '';
for (const p of pkgs) {
const card = el('button', 'card package-card');
card.appendChild(el('span', 'card-name', p.display));
const origin = p.origin === 'user' ? `user${p.ownerName ? `, by ${p.ownerName}` : ''}` : 'system';
card.appendChild(el('span', 'card-meta', `${p.name} \u00b7 ${origin} \u00b7 records ${p.records ? 'on' : 'off'} \u00b7 carryover ${p.carryover ? 'yes' : 'no'} \u00b7 memory ${p.memory ? 'yes' : 'no'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete -- missing backdrop or character'));
card.addEventListener('click', () => pickPackage(p));
list.appendChild(card);
}
}
/** @param {{ display: string, name: string }} p */
async function pickPackage(p) {
pkg = p;
$('package-pick').hidden = true;
$('create-form').hidden = false;
$('create-title').textContent = `start -- ${p.display}`;
/** @type {HTMLInputElement} */ ($('create-name')).value = p.display;
const pcInp = /** @type {HTMLInputElement} */ ($('create-pc'));
pcInp.value = '';
pcInp.placeholder = 'rolling a name...';
pcInp.focus();
const roll = await api('/names').catch(() => null);
if (state.view !== 'new' || $('create-form').hidden) return;
if (pcInp.value === '' && roll?.name) pcInp.value = roll.name;
}
$('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; });
$('create-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = /** @type {HTMLInputElement} */ ($('create-name')).value.trim();
const pc = /** @type {HTMLInputElement} */ ($('create-pc')).value.trim();
if (!name) return banner('the package needs a display name');
if (!pc) return banner('the main character needs a name');
try {
const r = await api('/runs', { method: 'POST', body: { package: pkg?.name, pc, name } });
navigate(`/runs/${r.run.id}/setup`);
} catch (err) {
banner(err.message);
}
});
+111
View File
@@ -0,0 +1,111 @@
// web/view-packages.mjs -- the packages list: every package of the
// deployment, system and user, with its acts -- start (create a run:
// the naming form), fork (the copy-to-author act; the copy lands in
// the editor), edit (the owner's own user packages). The list is the
// launchpad (list -> action, developer 2026-11-19); a scaffold is
// authoring material, not a story -- its start refuses.
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate } from './router.mjs';
/** @type {?{ display: string, name: string }} */ let pkg = null; // the picked package -- the view owns it
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
$('package-pick').hidden = false;
$('create-form').hidden = true;
const pkgs = await api('/packages');
if (seq !== state.seq) return;
const list = $('package-list');
list.textContent = '';
for (const p of pkgs) {
const card = el('div', 'card package-card');
card.appendChild(el('span', 'card-name', p.display));
const origin = p.origin === 'user' ? `user${p.ownerName ? `, by ${p.ownerName}` : ''}` : 'system';
card.appendChild(el('span', 'card-meta', `${p.name} \u00b7 ${origin} \u00b7 records ${p.records ? 'on' : 'off'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete -- missing backdrop or character'));
if (p.scaffold) card.appendChild(el('span', 'card-state attention', 'scaffold -- fork it to author, then flip "scaffold" off in the editor'));
const actions = el('div', 'form-actions pkg-actions');
const start = /** @type {HTMLButtonElement} */ (el('button', 'primary', 'start'));
start.disabled = p.scaffold || !p.complete;
start.addEventListener('click', () => pickPackage(p));
actions.appendChild(start);
const fork = /** @type {HTMLButtonElement} */ (el('button', null, 'fork'));
fork.addEventListener('click', () => openForkForm(card, p));
actions.appendChild(fork);
if (p.origin === 'user' && p.owner === state.me?.id) {
const edit = /** @type {HTMLButtonElement} */ (el('button', null, 'edit'));
edit.addEventListener('click', () => navigate(`/packages/${p.name}`));
actions.appendChild(edit);
}
card.appendChild(actions);
list.appendChild(card);
}
}
/** @param {{ display: string, name: string }} p */
async function pickPackage(p) {
pkg = p;
$('package-pick').hidden = true;
$('create-form').hidden = false;
$('create-title').textContent = `start -- ${p.display}`;
/** @type {HTMLInputElement} */ ($('create-name')).value = p.display;
const pcInp = /** @type {HTMLInputElement} */ ($('create-pc'));
pcInp.value = '';
pcInp.placeholder = 'rolling a name...';
pcInp.focus();
const roll = await api('/names').catch(() => null);
if (state.view !== 'packages' || $('create-form').hidden) return;
if (pcInp.value === '' && roll?.name) pcInp.value = roll.name;
}
// the fork form: revealed in the card, one decision -- the new
// package's display name. The fork lands in the editor (the
// copy-to-author act, developer 2026-11-19).
/** @param {HTMLElement} card @param {{ display: string, name: string }} p */
function openForkForm(card, p) {
const old = card.querySelector('.pkg-fork-form');
if (old) { old.remove(); return; } // a second click closes it
const form = el('form', 'pkg-fork-form');
const inp = /** @type {HTMLInputElement} */ (el('input'));
inp.placeholder = 'the new package\'s display name';
inp.autocomplete = 'off';
inp.value = `${p.display} fork`;
const go = /** @type {HTMLButtonElement} */ (el('button', 'primary', 'fork it'));
go.type = 'submit';
form.appendChild(inp);
form.appendChild(go);
form.addEventListener('submit', async (e) => {
e.preventDefault();
const name = inp.value.trim();
if (!name) return banner('the fork needs a display name');
go.disabled = true;
try {
const r = await api('/packages/fork', { method: 'POST', body: { from: p.name, name } });
navigate(`/packages/${r.package.id}`);
} catch (err) {
banner(err.message);
go.disabled = false;
}
});
card.appendChild(form);
inp.focus();
}
$('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; });
$('create-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = /** @type {HTMLInputElement} */ ($('create-name')).value.trim();
const pc = /** @type {HTMLInputElement} */ ($('create-pc')).value.trim();
if (!name) return banner('the package needs a display name');
if (!pc) return banner('the main character needs a name');
try {
const r = await api('/runs', { method: 'POST', body: { package: pkg?.name, pc, name } });
navigate(`/runs/${r.run.id}/setup`);
} catch (err) {
banner(err.message);
}
});
+66
View File
@@ -0,0 +1,66 @@
// web/view-pkgedit.mjs -- the package editor: the owner's authoring
// surface over one user package. Every file is authoring material
// (pre-run, settings included -- raw JSON for now, native UI later,
// developer 2026-11-19); the save lints are the cheap ones, the start
// gate judges the whole package when a run is created.
import { $ } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate } from './router.mjs';
import { fileEditor } from './widgets.mjs';
// the package's own files, in authoring order -- settings first: the
// ready-to-run flag ("scaffold") is the first thing a fork's author
// needs to see
const EDIT_LIST = ['settings.json', 'backdrop.md', 'character.md', 'handbook.md', 'memory.json', 'carryover.jsonl', 'gm.md'];
/** @type {Record<string, string>} */
const FILE_HINTS = {
'settings.json':
'raw JSON for now (native UI later). The keys: "name" (display), "records" (the storage db on/off), '
+ '"scaffold" (true holds the package out of play -- flip it off when the package is ready to run), '
+ '"pc" (optional default; a run\'s create always asks).',
'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. @PC, @Package and $VARS expand at start.',
'gm.md': 'the package author\'s notes -- seeded into every run as the GM\'s notepad, never sent to the model.',
};
/** @type {?string} */ let pkgName = null; // the addressed package -- the view owns it
const editor = fileEditor(
{ nav: 'pkgedit-files', edit: 'pkgedit-edit', hl: 'pkgedit-hl', save: 'pkgedit-save', state: 'pkgedit-edit-state', hint: 'pkgedit-hint' },
{
put: (f, content) => api(`/packages/${pkgName}/files/${f}`, { method: 'PUT', body: { content } }),
hints: FILE_HINTS,
},
);
/** @param {?string} name @param {number} seq @returns {Promise<void>} */
export async function enter(name, seq) {
if (name == null) return navigate('/packages'); // unreachable: the router only enters with a name
let resp;
try {
resp = await api(`/packages/${name}/files`);
} catch (e) {
if (e.status === 403 || e.status === 404) {
navigate('/packages');
banner(e.status === 403 ? 'that package is not yours to edit' : `no such package: ${name}`);
return;
}
return banner(`could not reach the server: ${e.message}`); // stay put -- transient
}
if (seq !== state.seq) return;
pkgName = name;
$('pkgedit-title').textContent = resp.display;
$('pkgedit-state').textContent = `${name}${resp.scaffold ? ' -- scaffold: not startable until "scaffold" is off' : ' -- ready to run'}`;
editor.load(EDIT_LIST.map((f) => ({
name: f,
mode: resp.files[f]?.mode ?? 'rw',
exists: !!resp.files[f]?.exists,
content: resp.files[f]?.content ?? '',
})));
editor.select('settings.json');
}
+25 -133
View File
@@ -15,7 +15,7 @@ import { state } from './state.mjs';
import { banner } from './chrome.mjs'; import { banner } from './chrome.mjs';
import { navigate, runGone } from './router.mjs'; import { navigate, runGone } from './router.mjs';
import { logEvent } from './log.mjs'; import { logEvent } from './log.mjs';
import { armedButton, modelList, modelsBox } from './widgets.mjs'; import { armedButton, modelList, modelsBox, fileEditor } from './widgets.mjs';
// one list, in bundle-assembly order: the repo-fed system message // one list, in bundle-assembly order: the repo-fed system message
// parts (read-only -- the user should understand how the model is // parts (read-only -- the user should understand how the model is
@@ -46,12 +46,15 @@ const FILE_HINTS = {
+ '@PC, @Package and $VARS expand at start (the authored opening only).', + '@PC, @Package and $VARS expand at start (the authored opening only).',
}; };
// the editor's working set -- module-local, reset on every enter // the shared editor widget over the run's file surface -- extracted
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */ let files = {}; // the API surface, empty until enter // when the package editor needed the same machinery (2026-11-19)
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name const editor = fileEditor(
/** @type {?string} */ let currentFile = null; { nav: 'setup-files', edit: 'setup-edit', hl: 'edit-hl', save: 'setup-save', state: 'setup-edit-state', hint: 'edit-hint' },
/** @type {Record<string, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {}; {
/** @type {Record<string, string>} */ let repoPrompts = {}; 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' }); const models = modelsBox('setup-models', { title: 'models -- the run\'s picks' });
@@ -59,8 +62,6 @@ const models = modelsBox('setup-models', { title: 'models -- the run\'s picks' }
export async function enter(id, seq) { export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters setup with a run id if (id == null) return; // unreachable: the router only enters setup with a run id
state.runId = id; state.runId = id;
drafts = {};
currentFile = null;
/** @type {RunDetail} */ let detail; /** @type {RunDetail} */ let detail;
/** @type {FilesResponse} */ let filesResp; /** @type {FilesResponse} */ let filesResp;
/** @type {PromptsResponse} */ let prompts; /** @type {PromptsResponse} */ let prompts;
@@ -79,8 +80,7 @@ export async function enter(id, seq) {
if (seq !== state.seq) return; if (seq !== state.seq) return;
if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play
files = filesResp.files; /** @type {Record<string, string>} */ const repoPrompts = {
repoPrompts = {
'system.md': prompts.system ?? '', 'system.md': prompts.system ?? '',
'invariants.md': prompts.invariants ?? '', 'invariants.md': prompts.invariants ?? '',
'reminder.md': prompts.reminder ?? '', 'reminder.md': prompts.reminder ?? '',
@@ -97,9 +97,9 @@ export async function enter(id, seq) {
$('setup-savepkg').hidden = !detail.draft; $('setup-savepkg').hidden = !detail.draft;
// prompt vars: the $TOKENS the prompts declare, filled per run // prompt vars: the $TOKENS the prompts declare, filled per run
const vars = scanVars(prompts, files); const vars = scanVars(prompts, filesResp.files);
/** @type {Record<string, string>} */ let currentVars = {}; /** @type {Record<string, string>} */ let currentVars = {};
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings -- empty vars */ } try { currentVars = JSON.parse(filesResp.files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings -- empty vars */ }
const varsList = $('setup-vars-list'); const varsList = $('setup-vars-list');
varsList.textContent = ''; varsList.textContent = '';
$('setup-vars').hidden = !vars.length; $('setup-vars').hidden = !vars.length;
@@ -118,27 +118,20 @@ export async function enter(id, seq) {
if (seq !== state.seq) return; if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist); models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist);
const nav = $('setup-files'); // the editor surface, composed in bundle order: the repo-fed prompts
nav.textContent = ''; // merged with the run's files, the API carrying the phase's truth
fileSpecs = {}; editor.load(EDIT_LIST.map((e) => {
for (const e of EDIT_LIST) { const runFile = filesResp.files[e.name];
const runFile = files[e.name]; return {
const spec = { name: e.name,
...e, // rw only while dormant, and a continuation carryover is
// the API carries the phase's truth: rw only while dormant, and // conversation -- read-only
// a continuation carryover is conversation -- read-only
mode: e.source === 'repo' ? 'ro' : (runFile?.mode ?? e.mode), mode: e.source === 'repo' ? 'ro' : (runFile?.mode ?? e.mode),
exists: e.source === 'repo' ? true : !!runFile?.exists, exists: e.source === 'repo' ? true : !!runFile?.exists,
content: e.source === 'repo' ? repoPrompts[e.name] : (runFile?.content ?? ''), content: e.source === 'repo' ? repoPrompts[e.name] : (runFile?.content ?? ''),
}; };
fileSpecs[e.name] = spec; }));
const item = el('button', `file-item${spec.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`); editor.select('system.md'); // how the model is prompted, first thing
item.appendChild(el('span', 'file-name', e.name + (spec.exists ? '' : ' (new)')));
item.appendChild(el('span', 'file-dirty', ''));
item.addEventListener('click', () => selectFile(e.name));
nav.appendChild(item);
}
selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = ''; $('savepkg-state').textContent = '';
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = ''; /** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
} }
@@ -177,97 +170,6 @@ async function saveVars() {
$('setup-vars-state').textContent = 'saved'; $('setup-vars-state').textContent = 'saved';
} }
/** @param {string} f */
function selectFile(f) {
const prev = currentFile;
if (prev === f) return;
if (prev && fileSpecs[prev]?.mode === 'rw') stashDraft(prev);
currentFile = f;
const spec = fileSpecs[f] ?? { mode: 'rw', source: 'run', exists: false };
const content = spec.source === 'repo'
? (repoPrompts[f] ?? '')
: (drafts[f] ?? spec.content ?? '');
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).value = content;
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
$('setup-save').hidden = spec.mode !== 'rw';
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
const hint = FILE_HINTS[f] ?? '';
$('edit-hint').textContent = hint;
$('edit-hint').hidden = !hint;
renderHighlight();
markNav();
}
// the highlight overlay: known sigils (gold) and every $VAR (green)
// light up in place; unknown @-words are the author's own text and
// stay plain -- @ syntax is not owned here
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() {
const ta = /** @type {HTMLTextAreaElement} */ ($('setup-edit'));
const hl = $('edit-hl');
const esc = ta.value.replace(/[&<>]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
hl.innerHTML = esc
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
+ '\n\u200b'; // keep the trailing empty line's height honest
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
}
/** @param {string} f */
function stashDraft(f) {
if (fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts
const v = /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value;
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
drafts[f] = v;
markNav();
}
function markNav() {
const items = $('setup-files').children;
for (const item of items) {
const name = (/** @type {HTMLElement} */ (item.querySelector('.file-name'))).textContent.replace(' (new)', '');
const dirty = drafts[name] !== undefined;
item.classList.toggle('dirty', dirty);
// the dirty marker is authored text, never css-generated -- the
// rendered text must match the source (house rule, 2026-11-15)
(/** @type {HTMLElement} */ (item.querySelector('.file-dirty'))).textContent = dirty ? '*' : '';
item.classList.toggle('current', name === currentFile);
}
}
/** @returns {Promise<void>} */
async function saveFile() {
const f = currentFile;
if (!f) return;
/** @type {HTMLButtonElement} */ ($('setup-save')).disabled = true;
try {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value } });
files[f].content = /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value;
files[f].exists = true;
delete drafts[f];
$('setup-edit-state').textContent = 'saved';
markNav();
} catch (e) {
banner(e.message);
$('setup-edit-state').textContent = 'not saved';
}
/** @type {HTMLButtonElement} */ ($('setup-save')).disabled = false;
}
/** @returns {Promise<void>} */
async function saveDirty() {
if (currentFile != null) stashDraft(currentFile); // unreachable guard: enter always selects a file first
for (const [f, content] of Object.entries({ ...drafts })) {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } });
files[f].content = content;
files[f].exists = true;
delete drafts[f];
}
markNav();
}
// save the run's craft as a new user package -- published to every user // 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: // of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision. // drafts flush first. The display name is the save's one decision.
@@ -278,7 +180,7 @@ async function saveAsPackage() {
/** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = true; /** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = true;
$('savepkg-state').textContent = 'saving...'; $('savepkg-state').textContent = 'saving...';
try { try {
await saveDirty(); await editor.saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } }); const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved -- ${r.package.id}`; $('savepkg-state').textContent = `saved -- ${r.package.id}`;
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = ''; /** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
@@ -305,7 +207,7 @@ async function startRun() {
btn.textContent = 'starting...'; btn.textContent = 'starting...';
try { try {
await saveVars(); await saveVars();
await saveDirty(); await editor.saveDirty();
} catch (e) { } catch (e) {
banner(`did not start -- ${e.message}`); banner(`did not start -- ${e.message}`);
btn.disabled = false; btn.disabled = false;
@@ -353,15 +255,5 @@ $('setup-vars-save').addEventListener('click', async () => {
$('setup-vars-state').textContent = 'not saved'; $('setup-vars-state').textContent = 'not saved';
} }
}); });
$('setup-save').addEventListener('click', saveFile);
$('setup-edit').addEventListener('input', () => {
if (currentFile) stashDraft(currentFile);
$('setup-edit-state').textContent = 'unsaved';
renderHighlight();
});
$('setup-edit').addEventListener('scroll', () => {
$('edit-hl').scrollTop = $('setup-edit').scrollTop;
$('edit-hl').scrollLeft = $('setup-edit').scrollLeft;
});
$('setup-start').addEventListener('click', startRun); $('setup-start').addEventListener('click', startRun);
$('savepkg-btn').addEventListener('click', saveAsPackage); $('savepkg-btn').addEventListener('click', saveAsPackage);
+150
View File
@@ -397,3 +397,153 @@ export function modelsBox(mount, { title }) {
}, },
}; };
} }
// --- the file editor ------------------------------------------------------------
//
// The shared editor surface: a file nav, a textarea with the sigil/var
// highlight overlay, per-file hints, a save bar. Extracted from the
// setup view (2026-11-19) when the package editor needed the same
// machinery -- the host supplies the DOM ids, the ordered file specs,
// and the PUT call; drafts, dirty marks, the highlight, and the save
// flow live here. The deep validation stays server-side (the
// save-time lints refuse at the PUT).
/** One file as the editor sees it.
* @typedef {{ name: string, mode: string, exists: boolean, content: string }} EditorFile */
/** @typedef {{ load: (specs: EditorFile[]) => void, select: (name: string) => void, saveCurrent: () => Promise<void>, saveDirty: () => Promise<void>, isDirty: () => boolean, current: () => ?string }} FileEditor */
/** @param {{ nav: string, edit: string, hl: string, save: string, state: string, hint: string }} ids
* @param {{ put: (file: string, content: string) => Promise<unknown>, hints?: Record<string, string> }} opts
* @returns {FileEditor} */
export function fileEditor(ids, { put, hints = {} }) {
const nav = $(ids.nav);
const ta = /** @type {HTMLTextAreaElement} */ ($(ids.edit));
const hl = $(ids.hl);
const saveBtn = /** @type {HTMLButtonElement} */ ($(ids.save));
const stateEl = $(ids.state);
const hintEl = $(ids.hint);
/** @type {Record<string, EditorFile>} */ let files = {};
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
/** @type {?string} */ let current = null;
// the highlight overlay: known sigils (gold) and every $VAR (green)
// light up in place; unknown @-words are the author's own text and
// stay plain -- @ syntax is not owned here
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() {
const esc = ta.value.replace(/[&<>]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
hl.innerHTML = esc
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
+ '\n\u200b'; // keep the trailing empty line's height honest
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
}
/** @param {string} f */
function stashDraft(f) {
if (files[f]?.mode !== 'rw') return; // read-only files never become drafts
const v = ta.value;
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
drafts[f] = v;
markNav();
}
function markNav() {
for (const item of /** @type {HTMLElement[]} */ (Array.from(nav.children))) {
const name = (/** @type {HTMLElement} */ (item.querySelector('.file-name'))).textContent.replace(' (new)', '');
const dirty = drafts[name] !== undefined;
item.classList.toggle('dirty', dirty);
// the dirty marker is authored text, never css-generated -- the
// rendered text must match the source (house rule, 2026-11-15)
(/** @type {HTMLElement} */ (item.querySelector('.file-dirty'))).textContent = dirty ? '*' : '';
item.classList.toggle('current', name === current);
}
}
/** @param {string} f */
function select(f) {
const prev = current;
if (prev === f) return;
if (prev && files[prev]?.mode === 'rw') stashDraft(prev);
current = f;
const spec = files[f] ?? { name: f, mode: 'rw', exists: false, content: '' };
ta.value = drafts[f] ?? spec.content ?? '';
ta.disabled = spec.mode !== 'rw';
saveBtn.hidden = spec.mode !== 'rw';
stateEl.textContent = spec.mode === 'rw' ? '' : 'read-only';
const hint = hints[f] ?? '';
hintEl.textContent = hint;
hintEl.hidden = !hint;
renderHighlight();
markNav();
}
/** @param {EditorFile[]} specs */
function load(specs) {
drafts = {};
current = null;
files = {};
nav.textContent = '';
for (const spec of specs) {
files[spec.name] = spec;
const item = el('button', `file-item${spec.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
item.appendChild(el('span', 'file-name', spec.name + (spec.exists ? '' : ' (new)')));
item.appendChild(el('span', 'file-dirty', ''));
item.addEventListener('click', () => select(spec.name));
nav.appendChild(item);
}
}
/** @returns {Promise<void>} */
async function saveCurrent() {
const f = current;
if (!f) return;
saveBtn.disabled = true;
try {
await put(f, ta.value);
files[f].content = ta.value;
files[f].exists = true;
delete drafts[f];
stateEl.textContent = 'saved';
markNav();
} catch (e) {
banner(/** @type {Error} */ (e).message);
stateEl.textContent = 'not saved';
}
saveBtn.disabled = false;
}
// flush every draft (start and publish flows): a refusal stops the
// flow -- the caller decides what to tell the author
/** @returns {Promise<void>} */
async function saveDirty() {
if (current != null) stashDraft(current);
for (const [f, content] of Object.entries({ ...drafts })) {
await put(f, content);
files[f].content = content;
files[f].exists = true;
delete drafts[f];
}
markNav();
}
saveBtn.addEventListener('click', saveCurrent);
ta.addEventListener('input', () => {
if (current) stashDraft(current);
stateEl.textContent = 'unsaved';
renderHighlight();
});
ta.addEventListener('scroll', () => {
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
});
return {
load,
select,
saveCurrent,
saveDirty,
isDirty: () => Object.keys(drafts).length > 0,
current: () => current,
};
}