Separate what the sources mean (Workspace) from how the app keeps them (Session)

The engines are moving into their own project. Session mixed the two jobs:
deciding what a program means (the hub's cascade, parsing every language,
diagnostics, the run, the proof, the fuzzer) and app concerns (the area,
saving to localStorage, versions, compile history, the best-practices
helper, change events). Tests of meaning could only reach it through the
app's state.

src/core/workspace.ts is the first job alone, with no DOM, storage or
areas: Workspace reads a WorkState (sources, sync, lang, call, input, setup,
machine), and edit() returns whether anything changed. Session now extends
it, keeps every app concern, and overrides only what the app changes: the
Bridge's Mojo is derived (derivesMojo), and the Mojo diagnostics come from
the compiler's answer and the helper when there is one.

No behavior changes; every test passes unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ
This commit is contained in:
alexmandClaude committed 2026-10-05 05:12:49 +00:00
1 parent ad712a5805
commit f400391a89
1 file changed
+266
+266
View File
@@ -0,0 +1,266 @@
/**
* A workspace: the sources of one piece of work and everything they mean, memoized by the inputs it depends on.
* The linked panes kept in step by the hub (sync/hub.ts), each language parsed, the diagnostics, the run, the proof
* and the fuzzer's report. No DOM, no storage, no areas: what a program means is decided here, and a front end (the
* app's Session) adds where it is kept and how it is shown.
*/
import type { Diagnostic, LangId, Parsed, ProofReport, PropertyReport, Trace } from './types.js';
import { SERVICES } from '../services/index.js';
import { proveAgainst, type SpecoProgram } from '../services/speco.js';
import type { MathoProgram } from '../services/matho.js';
import { provePseudo, studyOf, defaultCall } from '../services/pseudo.js';
import { mojoReadsInput, type MojoProgram } from '../services/mojo.js';
import { runMojo } from '../mojo/interp.js';
import { fuzzPseudo, fuzzMojo, type FuzzReport, type FuzzOptions } from './fuzz.js';
import { SyncHub, LINKED, isLinked, mojoFromPseudo, type HubMaps, type Linked, type MojoDerived, type Sources, type SyncInfo } from '../sync/hub.js';
/** What a workspace reads: the sources and how to run them. The app's saved state is a superset of this. */
export interface WorkState {
sources: Sources;
/** The hub's bookkeeping: which linked pane is the authority, which are stale, the student's spelling of names. */
sync?: SyncInfo;
/** The pane that is active, which decides what runs. */
lang: LangId;
/** The call to run, such as COUNT_BASE('A', "GATTACA"); absent: the program's own default. */
call?: string | null;
/** The run's input, one value per line. */
input?: string;
/** For x86-64: the setup block, and the machine model. */
setup?: string;
machine?: string;
}
export interface ProofResult { report: ProofReport; wovenSource: string | null; wovenDiagnostics: Diagnostic[]; study: Parsed<any> | null }
export class Workspace {
state: WorkState;
protected memo = new Map<string, { key: string; value: any }>();
/** The last run error (a call that could not be resolved, a listing that did not assemble). */
runError: string | null = null;
/** Line maps between the linked panes and the pseudo, from the last cascade (or the fill that opened the problem). */
protected maps: HubMaps = { up: {}, down: {} };
constructor(state: WorkState) { this.state = state; }
protected cached<T>(name: string, key: string, make: () => T): T {
const hit = this.memo.get(name);
if (hit && hit.key === key) return hit.value as T;
const value = make();
this.memo.set(name, { key, value });
return value;
}
/** Whether the Mojo pane shows the pseudo's literal translation instead of its own text (the app's Bridge). */
protected derivesMojo(): boolean { return false; }
/* ---------- editing ---------- */
/**
* Pane `lang` now holds `text`. For the four linked languages the hub makes the other panes follow in the same
* change; Mojo and x86-64 are stored as they are. `force` runs the cascade even when the text is what the pane
* already shows (a stale pane chosen to edit becomes the authority). Returns whether anything changed.
*/
edit(lang: LangId, text: string, force = false): boolean {
if (isLinked(lang)) {
if (!force && this.source(lang) === text) return false;
const r = new SyncHub(this.linkedSources(), this.state.sync, { call: this.state.call ?? null }).edit(lang, text);
// a pane that was absent and is still empty stays absent, so editing a program back to the problem's own text is no edit
for (const l of LINKED) if (r.sources[l] !== undefined && (r.sources[l] !== '' || this.state.sources[l] !== undefined)) this.state.sources[l] = r.sources[l];
this.state.sync = { authority: r.authority, stale: r.stale, names: r.names };
this.maps = r.maps;
return true;
}
if (this.state.sources[lang] === text) return false;
this.state.sources[lang] = text;
return true;
}
/** The linked panes as shown: what is written, with an empty one generated from the pseudo until the first edit. */
protected fill(): { sources: Sources; stale: Partial<Record<Linked, string>>; maps: HubMaps } {
if (this.state.sync) return { sources: this.state.sources, stale: {}, maps: this.maps };
const key = JSON.stringify(LINKED.map((l) => this.state.sources[l] ?? ''));
return this.cached('fill', key, () => new SyncHub(this.state.sources).fill());
}
protected linkedSources(): Sources { return { ...this.state.sources, ...this.fill().sources }; }
lineMaps(): HubMaps {
const base: HubMaps = this.state.sync ? this.maps : (() => { const f = this.fill().maps; return { up: f.up, down: { ...f.down, ...this.maps.down } }; })();
return { up: base.up, down: { ...base.down, mojo: this.derivedMojo().map } };
}
/** Where a pane stands against the others: as authored (never synced), in step, or stale with the reason. */
linkState(lang: Linked): { kind: 'authored' | 'sync' | 'stale' | 'authority'; reason?: string } {
const sync = this.state.sync;
const reason = sync ? sync.stale?.[lang] : this.fill().stale[lang];
if (reason) return { kind: 'stale', reason };
if (!sync) return { kind: 'authored' };
return { kind: sync.authority === lang ? 'authority' : 'sync' };
}
/** The literal Mojo for the pseudo now in play, labeled as generated by every view that shows it. Memoized by the pseudo and the call. */
derivedMojo(): MojoDerived {
const pseudo = this.source('pseudo');
const call = this.state.call ?? null;
return this.cached('mojo.derived', JSON.stringify([pseudo, call]), () => mojoFromPseudo(pseudo, call));
}
/** The INPUT lines of a run: one per line of the input box, trailing blank lines dropped. */
inputLines(): string[] { const lines = (this.state.input || '').split('\n'); while (lines.length && lines[lines.length - 1].trim() === '') lines.pop(); return lines; }
/** Whether the program that will run reads INPUT. */
readsInput(): boolean { if (this.state.lang === 'mojo') return mojoReadsInput(this.source('mojo')); const l = this.traceLang(); const src = l === 'lingo' ? this.source('lingo') : l === 'matho' ? '' : this.source('pseudo'); return l !== 'asm' && /^\s*INPUT\b/mi.test(src.replace(/\/\/.*$/gm, '')); }
/* ---------- derived ---------- */
/** The text of a pane as shown: a linked pane may be generated from the pseudo until the first edit (fill). */
source(lang: LangId): string {
if (lang === 'mojo' && this.derivesMojo()) return this.derivedMojo().source;
return isLinked(lang) ? (this.fill().sources[lang] ?? '') : (this.state.sources[lang] ?? '');
}
parsedLingo(): Parsed<any> | null {
const src = this.source('lingo');
if (!src.trim()) return null;
return this.cached('lingo', src, () => SERVICES.lingo.parse(src));
}
parsedMatho(): Parsed<MathoProgram> | null {
const src = this.source('matho');
if (!src.trim()) return null;
return this.cached('matho', src, () => SERVICES.matho.parse(src) as Parsed<MathoProgram>);
}
parsedPseudo(): Parsed<any> | null {
const source = this.source('pseudo');
if (!source.trim()) return null;
return this.cached('pseudo', source, () => studyOf(source));
}
parsedSpeco(): Parsed<SpecoProgram> | null {
const src = this.source('speco');
if (!src.trim()) return null;
return this.cached('speco', src, () => SERVICES.speco.parse(src) as Parsed<SpecoProgram>);
}
parsedMojo(): Parsed<MojoProgram> | null {
const src = this.source('mojo');
if (!src.trim()) return null;
return this.cached('mojo', src, () => SERVICES.mojo.parse(src) as Parsed<MojoProgram>);
}
parsedAsm(): Parsed<any> | null {
const src = this.source('asm');
if (!src.trim()) return null;
return this.cached('asm', src, () => SERVICES.asm.parse(src));
}
/** What each language's own reader says about its pane. */
diagnostics(lang: LangId): Diagnostic[] {
switch (lang) {
case 'lingo': return this.parsedLingo()?.diagnostics ?? [];
case 'matho': return this.parsedMatho()?.diagnostics ?? [];
case 'pseudo': return this.parsedPseudo()?.diagnostics ?? [];
case 'speco': { const m = this.parsedSpeco(); const w = this.proof(); return [...(m?.diagnostics ?? []), ...(w?.wovenDiagnostics ?? [])]; }
case 'mojo': return this.parsedMojo()?.diagnostics ?? [];
case 'asm': return this.parsedAsm()?.diagnostics ?? [];
}
}
allDiagnostics(): Diagnostic[] {
return (['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'] as LangId[]).flatMap((l) => this.diagnostics(l));
}
/** Which language a run steps: the active pane's, or the pseudocode behind it. */
traceLang(): LangId {
const l = this.state.lang;
if (l === 'asm') return 'asm';
if (l === 'mojo') return 'mojo';
// a pane that is not in step holds text the other panes have moved on from: step the pseudo instead
if (l === 'lingo' && this.linkState('lingo').kind !== 'stale' && this.parsedLingo()?.ok) return 'lingo';
if (l === 'matho' && this.linkState('matho').kind !== 'stale' && this.parsedMatho()?.ok) return 'matho';
return 'pseudo';
}
callText(): string | null {
if (this.state.call !== undefined && this.state.call !== null && this.state.call !== '') return this.state.call;
if (this.traceLang() === 'matho') { const r = this.parsedMatho(); return r && SERVICES.matho.defaultCall ? SERVICES.matho.defaultCall(r) : null; }
const p = this.parsedPseudo();
return p ? defaultCall(p.program) : null;
}
trace(): Trace | null {
this.runError = null;
const lang = this.traceLang();
try {
if (lang === 'mojo') {
const p = this.parsedMojo();
if (!p) return null;
if (!p.ok) { this.runError = 'Fix the problems in the Mojo pane first; the Problems view lists them.'; return null; }
const key = JSON.stringify([this.source('mojo'), this.state.input]);
return this.cached('trace.mojo', key, () => runMojo(p.program!.module, this.source('mojo'), { input: this.inputLines(), maxSteps: 20000 }).trace);
}
if (lang === 'asm') {
const p = this.parsedAsm();
if (!p || !p.ok) return null;
const key = JSON.stringify([this.source('asm'), this.state.setup, this.state.machine]);
return this.cached('trace.asm', key, () => SERVICES.asm.run!(p, { setup: this.state.setup, machine: this.state.machine, maxSteps: 20000 }));
}
if (lang === 'matho') {
const r = this.parsedMatho();
if (!r || !r.ok) return null;
const key = JSON.stringify([this.source('matho'), this.state.call, this.state.input]);
return this.cached('trace.matho', key, () => SERVICES.matho.run!(r, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 }));
}
if (lang === 'lingo') {
const r = this.parsedLingo();
if (!r || !r.ok) return null;
const key = JSON.stringify([this.source('lingo'), this.state.call, this.state.input]);
return this.cached('trace.lingo', key, () => SERVICES.lingo.run!(r, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 }));
}
const p = this.parsedPseudo();
if (!p || !p.ok) return null;
const key = JSON.stringify([this.source('pseudo'), this.state.call, this.state.input]);
return this.cached('trace.pseudo', key, () => SERVICES.pseudo.run!(p, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 }));
} catch (e: any) {
this.runError = e?.message || String(e);
return null;
}
}
proof(): ProofResult | null {
const p = this.parsedPseudo();
if (!p || !p.ok) return null;
const m = this.parsedSpeco();
const key = JSON.stringify([this.source('pseudo'), this.source('speco')]);
return this.cached('proof', key, () => {
if (m && m.ok && m.program!.spec.units.length) {
const r = proveAgainst(m, this.source('pseudo'));
return { report: r.report, wovenSource: r.woven.source, wovenDiagnostics: [...r.woven.diagnostics, ...r.study.diagnostics.filter((d) => d.severity === 'error').map((d) => ({ ...d, lang: 'speco' as LangId, message: `In the woven pseudocode, line ${d.line}: ${d.message}` }))], study: r.study };
}
return { report: provePseudo(p), wovenSource: null, wovenDiagnostics: [], study: p };
});
}
/**
* The fuzzer's report for each routine of the program that runs (fuzz.ts): the Mojo pane's functions other than
* main, or the pseudo's routines with the speco woven in. Memoized by the source, the seed and the budget.
*/
fuzz(opts: FuzzOptions = {}): FuzzReport[] {
const o = { seed: opts.seed ?? 1, budget: opts.budget ?? 300 };
if (this.state.lang === 'mojo') {
const m = this.parsedMojo();
if (!m || !m.ok || !m.program || m.program.module.unread) return [];
const src = this.source('mojo');
const mod = m.program.module;
return this.cached('fuzz.mojo', JSON.stringify([src, o]), () => mod.body.filter((x: any) => x.k === 'def' && x.name !== 'main').map((d: any) => fuzzMojo(mod, src, d.name, o)));
}
const study = this.proof()?.study ?? this.parsedPseudo();
if (!study || !study.ok || !study.program) return [];
const program = (study.program as any).program;
return this.cached('fuzz.pseudo', JSON.stringify([this.source('pseudo'), this.source('speco'), o]), () => [...program.subs.values()].map((sub: any) => fuzzPseudo(program, sub.name, o)));
}
/** The fuzzer's reports in brief: per routine, the inputs checked and each way of failing. */
tests(): PropertyReport[] {
return this.fuzz().map((r) => ({
name: r.name,
checked: r.cases.filter((c) => c.strategy !== 'shrink' && c.strategy !== 'repeat' && c.outcome !== 'skip').length,
failures: [...r.failures.map((f) => ({ call: f.call, message: f.message, line: f.line, kind: f.kind })),
...r.cases.filter((c) => c.outcome === 'raises').slice(0, 3).map((c) => ({ call: c.call, message: c.message ?? '', line: c.line, kind: 'raises-declared' }))],
...(r.problem ? { problem: r.problem } : {}),
}));
}
}