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
+25 -133
View File
@@ -15,7 +15,7 @@ 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 } from './widgets.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
@@ -46,12 +46,15 @@ const FILE_HINTS = {
+ '@PC, @Package and $VARS expand at start (the authored opening only).',
};
// the editor's working set -- module-local, reset on every enter
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */ let files = {}; // the API surface, empty until enter
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
/** @type {?string} */ let currentFile = null;
/** @type {Record<string, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {};
/** @type {Record<string, string>} */ let repoPrompts = {};
// 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' });
@@ -59,8 +62,6 @@ const models = modelsBox('setup-models', { title: 'models -- the run\'s picks' }
export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters setup with a run id
state.runId = id;
drafts = {};
currentFile = null;
/** @type {RunDetail} */ let detail;
/** @type {FilesResponse} */ let filesResp;
/** @type {PromptsResponse} */ let prompts;
@@ -79,8 +80,7 @@ export async function enter(id, seq) {
if (seq !== state.seq) return;
if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play
files = filesResp.files;
repoPrompts = {
/** @type {Record<string, string>} */ const repoPrompts = {
'system.md': prompts.system ?? '',
'invariants.md': prompts.invariants ?? '',
'reminder.md': prompts.reminder ?? '',
@@ -97,9 +97,9 @@ export async function enter(id, seq) {
$('setup-savepkg').hidden = !detail.draft;
// 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 = {};
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');
varsList.textContent = '';
$('setup-vars').hidden = !vars.length;
@@ -118,27 +118,20 @@ export async function enter(id, seq) {
if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelState, detail.run.providerDefaults, mlist);
const nav = $('setup-files');
nav.textContent = '';
fileSpecs = {};
for (const e of EDIT_LIST) {
const runFile = files[e.name];
const spec = {
...e,
// the API carries the phase's truth: rw only while dormant, and
// a continuation carryover is conversation -- read-only
// 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 ?? ''),
};
fileSpecs[e.name] = spec;
const item = el('button', `file-item${spec.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
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
}));
editor.select('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
}
@@ -177,97 +170,6 @@ async function saveVars() {
$('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
// of the deployment, gm.md included. Saves what the run has saved:
// 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;
$('savepkg-state').textContent = 'saving...';
try {
await saveDirty();
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 = '';
@@ -305,7 +207,7 @@ async function startRun() {
btn.textContent = 'starting...';
try {
await saveVars();
await saveDirty();
await editor.saveDirty();
} catch (e) {
banner(`did not start -- ${e.message}`);
btn.disabled = false;
@@ -353,15 +255,5 @@ $('setup-vars-save').addEventListener('click', async () => {
$('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);
$('savepkg-btn').addEventListener('click', saveAsPackage);