Skip to content

Workbench API: calling everything in the workbench programmatically

Design for one in-process, versioned API through which a language author (a custom action, intention, check, generator, event listener) or a workbench extender (a plugin, a project script, the Model Console) can reach everything the workbench can do: the editor, models and projects, languages, checks, the generator, the evaluator and debugger, tests, parsing and printing, Git, collaboration, preferences, commands and the UI.

Status: phases 1-4, 6 and 7 done in Theia; phase 5 keeps the catalog as the source of static menus (sections 16 and 17 say exactly what is and is not drawn) (written 2026-10-31 from an 80-question interview with the maintainer; section 13 says exactly what phase 1 delivered and what it left out). Section 11 lists the points that still need a decision before the later phases.

1. Goals and non-goals

Goals

  • Completeness first. Anything reachable by an internal tool, pane or language is reachable through the API. A gap fails a ratchet test (section 10), it is not a roadmap item.
  • One mental model. The UI, the Model Console, hooks in concept files, project scripts and plugins all call the same workbench object. The UI is migrated onto it ("dogfooding", section 9).
  • Language-agnostic. The API names no concept, extension or default language (see docs/architecture/language-agnostic-core.md). A language's own concepts reach scripts through generated typings.
  • Designed for a proxy boundary (feat/worker-sandbox): handles are ids, nothing live leaks out, so the same surface can later run over a worker or RPC boundary. Not built now.
  • Designed for agents (the chat agent's tools in theia-extension/src/browser/ai/, strukts mcp): every method has a typed schema and every edit carries an origin, so a tool wrapper is mechanical. Not built now.

Non-goals (this effort)

  • A remote transport (JSON-RPC, HTTP, MCP with writes) against a running IDE. The API stays transport-agnostic.
  • Live verification in VS Code. The VS Code host gets an adapter stub and contract tests only.
  • Byte-for-byte compatibility with the old src/api.ts / src/model-api.ts surface. They are removed (section 9).

2. What exists today (inventory)

Surface Where Fate
Re-export barrel (AST, slot accessors, AstNav, traversal, graph utils, ModelNode/NodeList/Model, patterns, kit) src/api.ts Removed in the last phase.
Fluent query/edit API (ModelNode, NodeList, Model, ProjectSummary, buildSmodelScope) src/model-api.ts, docs/architecture/model-api.md Re-homed as workbench.model; file removed.
Lazy traversal src/tree-iteration.ts Kept, used internally by workbench.model.
Theia page integration bus (window.StruktJS, .authoring, .contribute, .mount, .get) src/theia-api*.ts(x) Becomes an adapter over the workbench object; the Theia widgets migrate to it.
Kit (window.StruktJS.authoring.kit) src/kit/ Stays; exposed as workbench.kit. Its KIT_API_VERSION mechanism is the template for workbench.version.
Hook context objects src/hook-contexts.ts, docs/architecture/concept-api-v2-plan.md Unchanged; every context gains ctx.workbench.
Concept listeners() aspect src/model-listeners.ts, docs/architecture/model-listeners.md Kept; the new event bus is the general mechanism, listeners() stays the per-concept declarative form.
Host capability map (host.hasNativeFindUsages(), ...) src/host.ts Extended into workbench.capabilities.
Embed (mountEditor handle) embed/, docs/architecture/embedding.md Returns a scoped workbench (section 8).
CLI verbs and read-only MCP server tools/strukts-cli/, docs/architecture/cli.md Stay read-only by default; gain strukts script (section 7).
AI agent tools theia-extension/src/browser/ai/ Untouched now; later wrapped over the API.
Command catalog theia-extension/src/shared/command-catalog*.ts Replaced by a command registry in a late phase (section 9).

Importers of src/api.ts / src/model-api.ts today include src/theia-api-plugins.ts, src/evaluator.ts, src/generator.ts, src/base-concept.ts, src/meta/eval-vm.ts, src/workbench/project.ts, src/routes/console-panel.tsx, src/console/query-concepts.tsx, src/editor/completion-sections-console-members.ts and four test files (test-model-api.mjs, test-pattern-sequence.mjs, test-console-query-concepts.mjs, test-sample-console-structure-checks.mjs). This list comes from a grep (from "…api"/model-api); re-run it at the start of the migration, it is not authoritative.

3. Decisions

Audience and entry point

  • Primary callers: in-process language authors and workbench extenders, one shared API.
  • workbench is injected as ctx.workbench into every hook context and importable by plugins.
  • Semver-versioned core plus an unstable.* namespace for internals. workbench.version and workbench.capabilities expose version and what this host can do (feature-detect, do not guess).
  • Naming: plain verbs and nouns, no prefixes; documented get/find/list/ensure conventions.
  • Priority order when they conflict: completeness, then stability, then ergonomics.

Reading, writing, hosts

  • Fully writable, including headless. Headless writes are in-memory and reach disk only through an explicit save(). The existing CLI verbs (check|generate|test|...) and strukts mcp stay read-only by default; the CLI and MCP gain write verbs only behind an opt-in flag (section 11, point 4, lists the guardrails that must change with it).
  • Edits go through Editor operations (undoable, fire()-normalized, collab-safe) when an editor exists; a headless Model also accepts model-only edits with its own undo stack built on the same normalizers.
  • Calls target the active editor/model/project by default; workbench.editors.get(id) / projects.get(id) address others. Inside a hook the API is already bound to the hook's model.
  • Mutation in a live Live Model Session takes the same path as user edits (replicates, respects host/read-only).
  • Host differences: UI calls are capability-checked. A call to something the host lacks throws UnavailableError (typed), never silently no-ops.
  • Hosts: Theia, standalone webview, embed, headless; VS Code gets an adapter stub with contract tests.
  • Customer white-label builds see an identical API; a pruned plugin's area is Unavailable.

Sync and async

  • Sync wherever the answer is in memory. Host-backed work (files, processes, Git, tasks) is Promise- or Task-returning and the name/type shows it. A lint rule and a table in the guide flag misuse.
  • Long-running work (run, generate, tests, Git) returns a Task handle: result, cancel(), onProgress, built on the EvalVM cancellation that already shipped.

Edits, transactions, history

  • workbench.transaction(fn): one undo step, one change notification; rolls back all edits if fn throws; may span several models/roots (one grouped undo via a shared group id).
  • workbench.history: undo, redo, mark(name) / restore(name) snapshots, revision number. Per-client undo scoping is respected.
  • Every edit and command carries an origin (user, action:<id>, script:<file>, listener:<owner>). Origins show in undo labels and collab presence. workbench.audit is an in-memory ring buffer plus an event stream (optionally mirrored to an Output channel); it is not persisted.

Events

  • workbench.on(event, handler) returns a disposable. v1 event groups: model/AST changes (before/after edit, transaction committed, node created/removed, root changed), editor/UI (selection, focus, pane opened/closed, tab switched, completion opened), workflow (checks, generator, run, tests, save/load, project open), collaboration/Git (peer joined/left, remote edit, branch changed, merge conflict).
  • Re-entrancy: an edit made inside a change listener is queued and applied after the current event as a follow-up transaction. A depth limit raises a clear error to stop loops.
  • Isolation: a throwing or slow listener or action is caught, reported with its owner (Problems/Output), and cancelled after a time budget. The others still run.
  • Errors elsewhere are typed classes that throw: NotFoundError, UnavailableError, InvalidEditError, CancelledError (all extend WorkbenchError).

Lifecycle

  • Everything a language, plugin or script registers (listeners, commands, menu items, panes, contributions) is owner-scoped and auto-disposed when the owner unloads or reloads. A leak-detection test enforces it. This builds on the existing per-project registry owner ids (projectRegistryOwnerId, releaseProjectRegistryOwners).

Registration on the language

  • Actions, menu/context-menu entries, event listeners and new commands are declared on the Language/concept, like intentions, persisted with the language and active only while that language is active.
  • A .lang.js records the API major it targets (apiVersion); on a mismatch the workbench warns and names the language.
  • Deprecation: warn for one minor with the replacement named, remove at the next major (before 1.0, per docs/architecture/stability-policy.md: a CHANGELOG Removed entry plus the api-surface snapshot update).

Languages and typing

  • workbench.languages is fully writable: create languages, alter concepts, slots, checks, generators, persist them.
  • A language's running hook may not modify the language it executes under (InvalidEditError); project scripts and other languages may.
  • When a language changes, open models are re-validated live and orphaned nodes/slots surface as problems; nothing is deleted silently.
  • Per-language .d.ts typings are virtual (generated in memory, served to editors, never written to disk). They give script and concept editors completion and type checking for node.slots.condition, model.byConcept(...). CI generates them for the shipped languages to catch drift.
  • The API itself stays language-agnostic. The cookbook and contract tests also run against tests/fixtures/kit-language/.

Parsing and queries

  • workbench.surface.parse|print|format per grammar (including grammars registered via the grammar registry). The raw tree-sitter tree is not exposed.
  • Queries: fluent filters (concept, slot, text), the pattern language as a query primitive, and scope/references/usages/ dataflow/type of a node. Structural-path addressing is not part of the query API (deep links keep their own codec).

System access, scripts, prompts, run internals

  • workbench.fs (project-relative files) and workbench.shell (process/terminal) go through host adapters: Node in headless, Theia services in Theia, Unavailable in embed.
  • Prompts/dialogs in headless runs are answered from supplied defaults (flags/config), otherwise throw UnavailableError; they never block.
  • workbench.run.debug / trace: stepping, breakpoints, environments, type traces and coverage.
  • Scripts live in language files, project scripts (*.script.js), startup/activation scripts and the Model Console. They run from the Explorer/command palette, strukts script <file>, Language.tasks/Theia tasks, and triggers declared in project.json (on open, on save).

UI access

In scope: panes/tabs open-close-focus, selection and cursor, messages/prompts/pickers, and contributing menus, panes and status-bar entries. Contributions must supply labels/descriptions and use the shared accessible components; the a11y audits cover them (see docs/architecture/accessibility.md). The Model Console and an API explorer pane show registered contributions per owner and the host's capability matrix.

4. Shape of the API

interface Workbench {
  readonly version: string;                    // semver of the API contract
  readonly capabilities: CapabilityMap;        // what THIS host provides; extends src/host.ts
  readonly unstable: Record<string, unknown>;  // outside the semver core

  // data
  model: ModelApi;        // Model / ModelNode / NodeList handles; query + edit; headless-capable
  editor: EditorApi;      // active editor: selection, cursor, completion, intentions, notation
  editors: EditorRegistry;// address other editors/tabs
  project: ProjectApi;    // open/close/list projects, roots, imports, save()
  languages: LanguageApi; // read + write languages, concepts, checks, generators
  surface: SurfaceApi;    // parse / print / format per grammar

  // tools
  checks: ChecksApi;
  generator: GeneratorApi;     // text, multi-file plan, pipelines; Task handles
  run: RunApi;                 // run, debug, trace, coverage; Task handles
  tests: TestsApi;
  types: TypeSystemApi;
  patterns: PatternApi;
  scope: ScopeApi;             // references, usages, dataflow

  // environment
  fs: FsApi; shell: ShellApi;  // async, host-backed
  git: GitApi; collab: CollabApi;
  prefs: PrefsApi;
  commands: CommandApi;        // execute(id, args) typed; later phase: registry replaces the catalog
  ui: UiApi;                   // panes, tabs, prompts, messages, contributions

  // cross-cutting
  transaction<T>(fn: () => T, opts?: { label?: string }): T;
  history: HistoryApi;
  on<E extends EventName>(e: E, h: Handler<E>): Disposable;
  audit: AuditApi;
  kit: Kit;
}

Method names above are illustrative; the exact signatures are decided per namespace in phase 1 and recorded in the generated reference. Conventions: handles are lazy and resolve by node id; results never expose live mutable AST objects (use handle.snapshot() for a plain copy); anything that can outlive a call returns a Disposable or Task.

Host adapters

One workbench package, one adapter per host. An adapter supplies the host-backed namespaces (fs, shell, git, ui, commands, parts of project) and fills capabilities. Headless: Node fs, no ui. Theia: Theia services over the existing bridge. Standalone webview: today's buildMenuBar() world. Embed: model, editor, tools; the rest Unavailable (but see 11.2). VS Code: stub + contract tests.

5. Headless model with edits

Model gains an in-memory editable form with its own undo stack. To avoid two implementations of "what is a valid edit": the headless path calls the same normalizers the editor runs in fire() (normalizeExpressionStatements, normalizeReferenceQualifiers, ...). Anything normalizing only inside the Editor class must first be pulled out into a shared function (plain TS, no Solid, no Editor import) so both paths use it. A property test compares a random edit sequence applied through Editor and through the headless model: same resulting tree.

6. Registration points on Language/concept

New aspects (shape finalized in phase 2, following the Concept API v2 conventions):

One concept aspect, contributes() (not four: actions() already means the editor's DOM-event map, and a single table keeps the code-only plumbing in one place), returning { actions?, commands?, events? }:

  • actions: { id, label, description?, menus?, isApplicable?, run }. menus is palette | context | edit (menus are declared on the action; drawing them in the IDE is phase 4). Registry id: <concept head>.<id>.
  • commands: { id, label?, description?, run(args, ctx) }, globally unique ids.
  • events: a handler (or list) per workbench event, (payload, { lang, workbench }).

All are owner-scoped (language:<name>), live only while the language is activated (workbench.languages.activate), code-only (not saved in .lang.js; re-attached by applyJsOverlays) and inherited by subconcepts (a same-id action/command replaces the parent's; events concatenate). A subconcept registers only what it declares itself, and for a node the most specific concept's action wins. The per-concept listeners() aspect is unchanged. A11y checks (label and description required for UI-drawn entries) arrive with the UI namespaces in phase 4; today label is required, description is not.

7. Scripts and the CLI

*.script.js files receive workbench bound to the project. strukts script <file> [--save] runs one headless with the in-memory writable host; nothing is written unless the script (or --save) saves. Prompts need --answer key=value or fail. project.json triggers (on: "open" | "save") and Language.tasks run the same files. The existing trust rule still applies (project *.lang.js and now project scripts are refused without --trust-project-code, and the IDE's trust prompt).

8. Embed and VS Code

mountEditor returns a scoped workbench handle. The decision for "full workbench in embed" conflicts with an earlier recorded scope decision; see 11.2. VS Code: adapter stub implementing the capability map (unsupported = Unavailable) plus the shared contract tests; live verification deferred.

9. Migration and removal

  1. Build the new surface next to the old one (the old files stay until the last step).
  2. Migrate the Model Console to evaluate against workbench (it becomes the live REPL for the whole API).
  3. Rewrite tests that import api.ts/model-api.ts against the new API with the same assertions (proves parity).
  4. Migrate the UI (menus, panes, commands) onto the API, with a ratchet counting UI code that still calls internals directly.
  5. Replace the command catalog with a command registry; menus, tooltips, keybinding sync and test-command-catalog.mjs move onto it (the Theia and webview menu bars are both rebuilt on it; see CLAUDE.md "Menus").
  6. Delete src/api.ts and src/model-api.ts in one commit; update tests/fixtures/api-surface.json (SURFACES in scripts/api-surface.mjs now lists the new entry point), typedoc.json entry points, window.StruktJS.authoring.
  7. CHANGELOG Removed entry, a migration guide for plugin authors (old call to new call), release note.

10. Documentation, typings and tests

Docs (updated in the same commit as the behaviour, per the repo rule): this architecture page (kept as the single source for the developer site), a "Scripting the workbench" user guide in website/docs, a CLAUDE.md section with the gotchas, generated TypeDoc reference, a plugin-author migration guide, and a changelog entry. Namespace tables in the guide are generated from the TypeScript source of truth and checked in CI.

Tests

  • Coverage ratchet: fails when an editor operation, pane, or command (command-catalog until replaced) has no API entry and no documented exclusion.
  • Contract tests per host: the same API suite runs against headless, embed, webview and Theia and asserts Unavailable exactly where the capability map says so.
  • Live Theia/Playwright for UI-facing calls (panes, selection, prompts, contributions). jsdom is not proof (CLAUDE.md).
  • Cookbook as test: the sample project's actions run in vitest and under strukts test.
  • Headless vs Editor edit-parity property test (section 5); leak test for owner disposal; re-entrancy depth-limit test; a per-method performance budget for hot-hook reads (reads are cached by astRevision; no tracked read of the whole AST store); language-agnostic ratchet applies to the new files (tests/test-no-language-literals.mjs).
  • Accessibility ratchet: contributed UI without label/description fails.

Cookbook sample (first version): a custom action with a context-menu entry that edits inside a transaction; a generator + run pipeline with progress and cancel; an event listener that shows a message/status entry and opens a pane; a headless batch script run by the CLI that loads, edits in memory and saves.

11. Open points that need a decision before code

  1. "Migrate all UI in the initial effort" versus "phase 1 = core + models + tools". These can only both hold if phase 1 is the first of several phases of one effort. The plan below keeps phase 1 small and puts the UI migration and catalog replacement later in the same effort. Confirm that the effort is not "done" until phase 7.
  2. "Full workbench in embed" versus the recorded embed decision (debugger and collaboration are out of scope for the embeddable editor, docs/architecture/embedding.md). Proposal: all namespaces exist in embed, but run.debug, collab, git, shell, ui.panes report Unavailable there; model, editor, tools, languages and surface work. Confirm.
  3. Language self-modification guard vs hooks that legitimately regenerate parts of a language (for example a "generate concepts from a schema" action). Such code should be a project script, not a hook of the language it changes. Confirm.
  4. Headless write verbs on the CLI and MCP. Decided by the maintainer: headless writes are in-memory with an explicit save(), and the CLI and MCP gain write verbs behind an opt-in flag (the flag name is open; whether MCP gets writes is not). Four existing guardrails each currently forbid this and must change in the same commit as the first write verb:
  5. CLAUDE.md's CLI section ("don't add a write path under it") and docs/architecture/cli.md (the headless host "stays read-only").
  6. setHeadlessHost in src/vscode-bridge.ts, which allows only three read commands.
  7. strukts mcp "read-only by design" (CLAUDE.md, cli.md, lib/mcp.mjs), and run_program stubbing input().
  8. The MCP row in docs/architecture/stability-policy.md ("Read-only"), plus tests/test-strukts-cli*.mjs and tests/test-cli-shapes.mjs snapshots.
  9. How workbench.languages writes persist. Languages are moving to class files (*.concept.js; the Explorer's concept Delete/Duplicate act on the class file, src/routes/explorer-concept-actions.ts), and src/workbench/languages.ts (saveLanguageAsync) is the Language Pane's save path. Decide whether API edits (a) reuse that write path, so the Language Pane, Explorer and API stay one writer, or (b) generate concept source text and write the class file. Recommendation: (a), with the API calling the same functions the Explorer actions call, so there is one implementation of "edit a language on disk". This decides how phase 2 is built.
  10. Trust: project scripts are new executable project code; the existing trust flag covers them, but project.json triggers that run scripts automatically on open must require the trust decision first. Confirm no trigger runs before trust.
  11. unstable versus the stability policy tiers: proposal: the semver core is Provisional until 1.0 (per the policy table), unstable.* is Internal. Add the row to docs/architecture/stability-policy.md.
  12. Catalog replacement scope: the command registry must cover keybinding sync with Theia (theia-extension/src/browser/struktjs-keybinding-contribution.ts) and menu hover descriptions (test-command-catalog.mjs). Size this in phase 5 before committing to the date.

12. Phase plan

Each phase ends with its tests green and its docs updated in the same commits. No phase deletes the old API except the last.

Phase Content Gate
0 This document, reviewed. Maintainer sign-off on section 11.
1 Workbench object, owners/disposables, errors, capability map, events, audit, transaction, history; namespaces model (headless-writable), editor, project (load/save), languages (read), checks, generator, run, tests, types, patterns, scope, surface; ctx.workbench; Model Console on the new API; minimal cookbook; virtual typings; coverage ratchet v1. The four phase-1 criteria: cookbook passes in jsdom and live Theia, ratchet green, console migrated, docs/typings generated in CI.
2 Writable languages, Language registration aspects (actions, menus, listeners, commands), apiVersion, self-modification guard, live re-validation. Registration/leak/guard tests; language-agnostic fixture run.
3 Scripts (*.script.js, strukts script, Language.tasks, triggers), fs, shell, prompts-with-defaults. CLI shape snapshot updated; trust-before-trigger test.
4 ui, prefs, git, collab; embed and VS Code adapters; API explorer pane and console help(). Contract tests on all hosts; live Playwright for UI calls; a11y audit.
5 Command registry replaces the catalog. Menu bars, tooltips, keybinding sync, test-command-catalog equivalents green on both menu bars.
6 UI migrated onto the API; direct-internal-call ratchet. Ratchet green; no behavior regression in the existing Playwright suites.
7 Delete src/api.ts, src/model-api.ts; API-surface snapshot, typedoc, window.StruktJS.authoring; CHANGELOG, migration guide, release note; CLAUDE.md section. breaking-changelog CI job satisfied; full npm test.

13. Phase 1 status (2026-10-31)

Delivered in src/workbench-api/ (commits eb90636c8, 9a8e9b366, 3ba9e5d49, 3f568f3a0, 0ff3c9e55 and the documentation commit that follows):

  • Services: typed errors, owner-scoped disposables, event bus (handler isolation, time budget, deferred re-entrant edits with a depth limit), audit ring buffer, capability map, Task handles on EvalCancellation, TransactionEngine (atomic with rollback, grouped headless undo, named snapshots), createWorkbench, getWorkbench/setActiveContextProvider.
  • Namespaces: model, editor, project (read), languages (read, plus virtual typings), checks, generator, run, tests, types, patterns, scope, surface, history, audit, owner.
  • ctx.workbench in the placement, intention, constraint, type-rule, check and generate contexts.
  • The Model Console binds workbench; its active model follows the console's own context while mounted, and capabilities follow what is open (editor/project turn on when the active context has them).
  • Decorated roots (@check, @constraint, @infer, @intention, @when) get ctx.workbench through hookOf; the refactoring context too.
  • Ratchets and gates: test-workbench-api-coverage.mjs, the API-surface snapshot (workbench-api entry), the cookbook test over the guide, a real-Editor jsdom test.
  • Docs: the user guide scripting-the-workbench.md, the stability-policy row, TypeDoc entry, a CLAUDE.md section, a CHANGELOG line.

Not done, deliberately, and where it lands:

Item Phase
ctx.workbench in the evaluator's EvalContext (done in phase 2) 2
Console completion and help() for workbench.* (members are not in the console's consoleMembers tables) 4
Live verification in the desktop (Electron) app. Verified live in the standalone webview (tests/test-ui-console.spec.js) and the Theia browser host (tests/test-theia-workbench-api-console.spec.js, run on a private backend with a rebuilt webview) 4
The per-method performance budget test for hot-hook reads (design section 10); reads are cheap by construction but nothing measures them 4
ctx.workbench in the refactoring context is attached but not listed in a member table; there is no table for it 2
Wiring the editor view's own active-context provider (setActiveContextProvider) outside the console; getWorkbench() has no active model unless the console is mounted or a host registers one 4
The coverage ratchet's command half: all 258 catalog commands are in the pending baseline 5
Moving ModelNode/NodeList/Model out of src/model-api.ts (the namespaces still build on them) 7
Rollback keeps the root object but replaces the nodes below it, so a ModelNode taken before a rolled-back transaction on an Editor may point at a detached node; re-fetch after a failure known limit
Edits to a headless model outside a transaction are not undoable by design (section 5)

14. Phase 2 status (2026-10-31)

Delivered: contributes() aspect (src/workbench-api/contributions.ts; plumbing in base-concept.ts, lang-class-inheritance.ts, lang-library.ts applyJsOverlays), ContributionRegistry (registry.ts), workbench.actions / workbench.commands / workbench.languages.activate|deactivate|active, writable workbench.languages (languages-api.ts: create, setConcept, deleteConcept, setEnum, deleteEnum, save, remove, orphans), live reporting of orphaned nodes (language.changed event, orphans count), the self-modification guard (workbench.forLanguage(lang): ctx.workbench is scoped to ctx.lang in every hook context and in EvalContext), Language.apiVersion (persisted in the language.json sidecar) with a warning on a major mismatch, and ctx.workbench in EvalContext.

Decisions taken while building (open point 3 and 5 of section 11):

  • The guard is by language, enforced on the scoped view: it covers hooks, actions, commands and EvalContext. A script that holds the unscoped workbench is unrestricted.
  • Language writes call the Language Pane's own methods and saveLanguageAsync. For a project language stored as class files (*.concepts/), deleteConcept changes the in-memory language only; removing the class file goes through deleteProjectConcept (project-concept-ops.ts, async, with dependents) and is not exposed yet.

Not done: writing concept class-file source from the API (the class-file path above); drawing action menus in the IDE and keybindings (phase 4); contributes() has no Language Pane editor (it is class-only like listeners()); an apiVersion field in the Language Editor UI; re-validation is reported (orphans, language.changed) but the host does not yet re-run checks on the open editor by itself (the editor view subscribes in phase 4).

15. Phase 3 status (2026-10-31)

Delivered: workbench.fs (fs.ts: path rules in the core, adapter per host, fs/fs.write capabilities), workbench.shell (shell.ts, argv only), workbench.prompts (prompts.ts: provider or answersProvider; no answer = UnavailableError, never blocks), workbench.scripts (scripts.ts: run, list, runFile fail-closed through adapter.scriptTrust, triggers, fire), workbench.project.models/model/save, host services turning their capability on (HostAdapter.fs/shell/prompts/scriptTrust; editor/project capabilities derive from the active context in the core), and the CLI side: strukts script (tools/strukts-cli/lib/script.mjs; flags --write, --shell, --answer, --args, --model; exit code 7), task step verb: "script", and strukts mcp --write adding strukts_run_script.

Decisions taken (open point 4 of section 11): the headless host is unchanged and read-only. CLI and MCP "writes" are node:fs in the tool, under --project-dir, the way migrate --write already worked, behind --write (and --shell separately; no workbench.shell over MCP). These flags gate the API's own paths only; they are not a sandbox. A script is JavaScript in the CLI/MCP process, so --trust-project-code is the boundary and strukts mcp --write is consent to code execution as the user (a native import("node:child_process") works, verified). The four guardrails named in point 4 were updated in the same change (CLAUDE.md CLI paragraph, docs/architecture/cli.md, the MCP row of the stability policy, the user CLI page).

Fixed on the way (found by the CLI tests): the fluent ModelNode mutators (set, setReference, replaceWith, insertBefore/After, rename, delete) refused without an editor, which contradicted "headless model edits". They now edit in place when the model is headless (ModelApiCtx.headless, set by workbench.model.* when there is no editor); workbench.transaction is the undo unit and its commit canonicalizes headless roots like the editor's fire() (normalizeExpressionStatements). insertBefore/After, replaceWith and delete on a statement shown without its invisible ExpressionStatement wrapper now act on the wrapper (they used to splice inside it, also in the console). New ModelNode#append(slot, node).

Review fixes (same phase): scripts are not sandboxed (verified: a trusted script that does await import("node:child_process") runs a program and writes outside the project with no --write/--shell), so every doc now says --trust-project-code is the boundary and the flags gate the API's own paths; unsaved is computed per model against what is on disk (loaded or last saved by the script); project.model(name) is editable headless and project.target(name) names it for workbench.transaction(fn, { also }).

Not done: running a script from the Explorer / command palette and firing project.json triggers on open/save in the IDE (needs the UI namespaces and editor-view events: phase 4); a Language.tasks step is a CLI verb, so a script task runs through strukts task, not as an in-IDE script; the trust hook for the IDE (code-trust.ts prompt) is not wired to scriptTrust yet (phase 4), so in the IDE runFile/fire refuse; shell over a Theia/VS Code host.

16. Phase 4 status (2026-10-31)

Delivered: workbench.ui (ui.ts: messages, selection, panes, validated contributions: a status entry, menu entry or pane needs an id, a label and a description, owner-scoped, ui.contributions.changed event), workbench.prefs (prefs.ts), workbench.git (git.ts; git and git.write capabilities; the IDE adapter is src/theia-git-api.ts, the facade the Source Control views use), workbench.collab (collab.ts, read-only), workbench.describe() / help() (describe.ts; hand-written namespace summaries kept complete by a ratchet), the application host adapter (app-adapter.ts, webview only: per-document context registered by each EditorView, preferences, Messages panel, cursor, standalone bottom tool windows, editor dialogs as prompts, collab state, Git, host file commands, code-trust for scripts), embedAdapter and EmbeddedEditor#workbench, a VS Code stub adapter (createAppAdapter({ kind: "vscode" }): files read-only, Git off, reasons in the map), the host contract test (every capability is exactly as available as the map says, for five hosts), "Run Workbench Script…" (catalog tools.runWorkbenchScript, Tools menu) and project.json triggers (script-actions.ts), and the performance budget.

Decisions taken (open point 6 of section 11 and the performance item):

  • Triggers need a person's prior approval of the exact script text (isExplicitlyTrusted), whatever the trust policy says; a script a person chose to run is confirmed once and remembered per exact text. The IDE's default policy is allow-all, so the stricter bar is specific to automatic runs. Triggers are guarded against their own echo (a trigger that edits the model makes the app save, firing save again).
  • transaction() snapshots with the editor's structural-sharing snapshots (editor/history-share.ts) instead of clone + hash: about one comparison walk per transaction, 66 ms for ~80k nodes warm (was 340 ms). Still linear in model size: batch edits, do not transact per node. The budget test pins it.
  • The editor's root is the live truth. The project model's root list can hold a stale object after undo/redo (the editor swaps its root object); activeContextFromEditorView substitutes the live root by id. Found by the live browser test, not by jsdom.

Found by live testing in a real browser (standalone) and in Theia: stale root after undo (fixed, above); .size() on a plain array in the console is the query-collection method and returns 0 (use len()); the console truncates long multi-line results; clicking a bottom-tool button toggles it. Live specs: tests/test-ui-workbench-api.spec.js (standalone), tests/test-theia-workbench-api-host.spec.js and tests/test-theia-workbench-api-console.spec.js (Theia, private backend).

Not done, and why:

Item Why / where
~~Drawing contributed status/menu/pane entries in the IDE~~ Done in Theia (section 17, theia-drawer.ts). Not done: the standalone webview's own menu bar and VS Code. (Author actions ARE in the editor's context menu, see 16a.) Built after this table was written.
The new palette command Run Workbench Script… in the Theia palette Its catalog row and tests are in; registering it in Theia needs the frontend bundle rebuilt, which was not done (it rewrites shared build output). Verified: the function itself (jsdom, standalone), the webview bundle in Theia.
~~A visual API explorer pane~~ Built after the review (16b): a modal over describe(), palette command tools.workbenchExplorer. It is a window, not a docked Theia view.
ui.panes in Theia The tool windows are Theia widgets revealed through the extension; not reachable from the webview. Off, with a reason.
Starting, joining or leaving a collaboration session from the API; Git outside what the facade offers Need key exchange and consent / were not wired.
The VS Code adapter verified live Stub by design until the extension host is run.
Desktop (Electron) live check Not run; Theia browser host verified.
Save/open triggers verified live in an IDE with a project folder The trigger logic is covered in jsdom; a live project folder with scripts was not set up.

16a. Phase 4 review fixes (same day)

  • Restricted Mode. VS Code's Restricted Mode sets the trust policy to deny-all; both script paths (the command and the triggers) now refuse under it, whatever was approved before (the command path had passed trust: () => true). tests/test-workbench-api-scripts-ide.mjs proves neither executes.
  • contributes() is reachable in the IDE. Phase 2 built activation, but nothing outside tests called it, so contributed actions, commands and event handlers were never live. Now syncLanguageActivation (app-adapter.ts, driven by an effect in EditorView.tsx) activates the active document's language and the languages it imports, and withdraws them on a language change. The editor's context menu (src/editor/context-menu.ts) lists an Actions submenu from workbench.actions.list({ node, menu: "context" }), only in the editor that is the active document's. tests/test-workbench-api-contributions-ide.mjs drives the real Editor, its context menu and the contribute.concept.js fixture.
  • The IDE file adapter, checked against the real command implementation. Command and argument names (writeFileAtPath {path, content}, createDirectory, deleteFileAtPath) were right; two semantics were not: listDirEntries of a missing folder returns [] (it never throws), so exists reported every missing path as present; and deleteFileAtPath removes a file or an EMPTY folder only. exists now reads the parent's listing and remove uses deletePathRecursive for a folder. tests/test-workbench-api-ide-fs.mjs runs the adapter through runFileCommand over an in-memory port.

16b. API explorer (same day, after the review)

src/components/modals/WorkbenchExplorerModal.tsx (mounted in EditorView.tsx, opened by the catalog command tools.workbenchExplorer (Tools > Workbench API Explorer)) draws workbench.describe(): every namespace with its summary and, when off, why; the owners with what they registered; actions, commands and UI contributions. It reads a fresh description on open and on Refresh. It takes keyboard focus when it opens and returns it on close (opened from the palette, focus would otherwise stay in the editor cell, where the editor's own Escape takes the key). It is a modal window, not a docked Theia view: a docked view would live in the extension's frontend and need the Theia build. Tests: tests/test-workbench-api-explorer.jsx (render, focus), tests/test-ui-workbench-api.spec.js (live). Console completion after workbench. is built: consoleReceiverKind treats the console's workbench variable as kind workbench, a namespace member as workbench.<ns>, and memberTableFor reads the members from the live object (membersAt in describe.ts), so a new namespace is completable with no table to maintain. A few calls map to the console's own kinds (workbench.model.active() is a model). Checked in jsdom and in the real console (tests/test-ui-workbench-api.spec.js).

17. Phase 5 status (2026-10-31)

Delivered: the API half. Not delivered: replacing the catalog as the source for menus, keybindings and tooltips.

  • workbench.commands now lists and runs the application's whole command catalog beside registered commands (catalog.ts: catalogHost, CommandHost; HostAdapter.commands). Rows carry source (registry|host), category, binding and runnable; execute(id, args) runs the active document's COMMAND_ACTIONS handler (registered per document by EditorView through registerCommandRunner); a command the document cannot run is UnavailableError, an unknown one NotFoundError; register refuses an application command's id.
  • The coverage ratchet's command half is now fully green with an empty pending list: every catalog command is exposed, and the test fails for one that is not. The ratchet is checked against the real catalog attached to a headless adapter.
  • Direction chosen: the registry reads the catalog; the catalog stays the single source of labels, menu placement, keybindings (and Theia's keybinding sync), tooltips and the test-command-catalog consistency gates. The design's alternative, rebuilding both menu bars and the keybinding sync on a new registry, was not done: it has to land in the Theia frontend (struktjs-menu-contribution.ts, struktjs-keybinding-contribution.ts, struktjs-command-contribution-*.ts), needs a full npm run build, and the shell controller / widget files the other session still has uncommitted are on the same path. Nothing about the API half depends on it; if it is done later, CommandHost is the seam (a registry would become the host's list()/run()).
  • Not done: typed argument and return schemas on catalog rows (CommandSpec has none; handlers take no arguments today, args is passed through for the ones that read one).
  • Added later (2026-11-01): registered commands are drawn in Theia. src/workbench-api/theia-drawer.ts mirrors workbench.commands (registry source) and the UI contributions onto the existing webview-to-Theia bridge window.__STRUKTJS_CONTRIBUTE__ (struktjs-contribution-bridge.ts), reconciling after every commands.changed / ui.contributions.changed. Because the webview and the Theia frontend are separate bundles, the webview's workbench is the single source; there is no second registry. The bridge registers the Theia command, a menu item (menu on the CommandDef, Tools by default), a key binding (refused when it collides with a Default- or User-scope binding), a tooltip (runtimeCommandDescriptions, read by struktjs-menu-tooltips.ts after the catalog), a status-bar entry and a tool pane (openOnRegister: false: the toggle command and Tools entry exist, the pane is not forced open); every register call returns what removes it. ui.drawsContributions is true in Theia when the bridge exists. Checked live (tests/test-theia-workbench-api-host.spec.js): menu item, tooltip, click, key binding, palette, status entry, dispose; and in jsdom against a fake bridge (tests/test-workbench-api-theia-drawer.mjs).
  • Runtime rows share the catalog (2026-11-01). command-catalog.ts now holds runtime rows beside the static ones (registerRuntimeCommand, runtimeCommands): labelForTheiaCommand and descriptionForTheiaCommand answer for both, so the menu tooltips need no second map, and the catalog's rules apply to a runtime row (label and a one-sentence description required, no repeated id, no key binding already used by a catalogued or earlier runtime row; Theia's own bindings are checked on top by the bridge). Re-registering an id replaces the earlier registration. The static menus, theiaKeybindings() and the Settings shortcut page still read the static rows: they are built once at startup from the catalog, which stays their source on purpose (rebuilding them from a mutable registry would change nothing a person can see and risks tooltips, translations and the catalog gates). The standalone webview's menu bar lists registered commands under Tools > Registered Commands (rebuilt on commands.changed; checked live in tests/test-ui-workbench-api.spec.js); VS Code draws nothing; a macOS native Electron menu gets no tooltip for a runtime command (the main process cannot see the renderer); contributed context menu entries stay the editor's own Actions submenu.

18. Phase 6 status (2026-10-31, completed 2026-11-01)

Delivered: all UI reaches the engine tools through workbench.*, and a ratchet keeps it so. The first cut left nine files with direct imports (25 of them); you chose "migrate everything", so they are moved.

  • The hot paths that made a direct import tempting get quiet, raw variants on the API itself: checks.results({ root, lang, ctx, manualOnly }) (the per-node result map, the caller's own incremental/model options, no audit entry and no event), types.analyze/types.infer, surface.parseRaw/parseChecked (the engine call exactly as the paste and surface view make it), generator.plan({ resolveLang }), run.createEvaluator(lang, options) (the caller drives the debugger, coverage and output sinks itself). The audited, evented methods (checks.run, run.run, ...) stay the way scripts and people do things; the quiet ones are for the editor's own plumbing.
  • types.describe(nodeId) is the read an editor's selection strip wants: the node's source text, its type in plain words, the type problems on it with their plain-words explain (see embedding.md, "Showing the selection's type"). One type pass per call.
  • Migrated: the live check loop and type passes (editor-view-core), find usages and surface import (EditorView), copy/export surface (clipboard, command-actions, theia-commands), the Run Generator tab, the console (checks, printing, evaluator), and the Language Editor's concept-source check. print/infer tolerate a document with no language yet, as the editor always did.
  • tests/test-workbench-api-ui-direct-calls.mjs fails when a UI file under src/routes, src/ui or src/components imports an engine tool directly (type imports included; use src/workbench-api). The baseline tests/fixtures/workbench-api-ui-direct-calls.json is empty; an entry needs a reason.
  • Checked: typecheck, the full suite, and the real-browser specs for the console, checks, Run and the API. Three specs fail identically on the committed baseline (two ALEF debugger specs that need a sample this dev build does not offer, and the language-gating "Add Root Node" spec); they are not caused by this change.

19. Phase 7 status (2026-10-31)

Done, as one breaking change with no deprecation period (pre-1.0 policy, CHANGELOG Removed):

  • src/api.ts (the re-export barrel) is deleted. src/model-api.ts is now src/workbench-api/model-nodes.ts (git mv, history kept); ModelNode, NodeList, Model, ProjectSummary, ConceptRef, buildSmodelScope and formatValue are re-exported by src/workbench-api/index.ts. Every other symbol the barrel carried is imported from its defining module, or reached through workbench.* (the migration guide has the table: website/docs/dev/authoring/workbench-api-migration.md).
  • window.StruktJS.authoring (buildAuthoringApi) imports from the real modules, keeps every key, and gains workbench.
  • The pinned surface (scripts/api-surface.mjs) lost its model-api entry (the node handles are part of the workbench-api entry now); typedoc.json, scripts/risk-baseline.json, the stability policy, docs/architecture/model-api.md, lionweb.md, node-data.md and CLAUDE.md follow. Remaining mentions of model-api.ts in source comments are historical and were left alone.

Checked: typecheck, the full suite (21,418 tests), the standalone CLI bundle build, the webview bundle build, and the live standalone specs.

What this plan did not do, in one place: rebuild the static menus/keybindings/tooltips on a registry instead of the catalog (section 17: deliberate); draw status entries and panes in the standalone webview or anything in VS Code; Theia live checks of the Actions submenu with two tabs on different languages, the Language Editor concept-source badges, a real project folder with triggers, a real Git repository and the desktop app (the surface export ends in a native save dialog).

19a. Review fix: language activation is per document

syncLanguageActivation first kept one global activated set, so a second Theia tab with another language withdrew the first tab's contributions, and closing any tab withdrew all of them. It is now syncLanguageActivation(documentKey, lang): each EditorView reports only its own document, and the live set is the union of every open document's language and its imports. tests/test-workbench-api-contributions-ide.mjs opens several documents (different languages, and two on the same language) and checks that each stays live and that closing one leaves the others.

19b. Sample project (2026-11-01)

samples/workbench-scripts/ is the runnable sample: a small Core program, tools/report.script.js, tools/add-statement.script.js (a transaction with args, saving only when fs.write is on) and tools/on-open.script.js (an open trigger that adapts to a host without a screen), project.json with scripts and triggers, and a README with the CLI commands and the IDE steps. In Theia the sample is seeded onto disk like any other (ensureSampleScripts in editor-view-samples-menu.ts: the *.script.js files bundled by samples.ts, and its scripts/triggers merged into the seeded project.json, additively: an existing script file is never overwritten, so the person's edits survive, and a folder seeded before this gets them on its next open); only the standalone webview's in-memory fallback has no folder. saveProjectMeta keeps the fields of project.json it does not model, so a rename no longer drops scripts/triggers. tests/test-sample-workbench-scripts.mjs runs all three through the real launcher against a copy, including the --write save.

20. Tests as code (2026-11-13)

workbench.tests.run(opts) takes three options beyond the roots (docs/architecture/js-tests-plan.md): trust (a CodeTrust hook: may the test language RUN project code, called with the exact text that would run), timeoutMs (per test, for providers that run code) and only (a node id: run just the suite, test or statement it names). trust defaults to the adapter's scriptTrust, so a script that runs tests inherits the decision it was run under (strukts script needs --trust-project-code; the IDE applies its trust policy); with neither, a provider that runs code (JS tests) reports the root as not run, never as passing. A JS test is itself code that calls this API: it gets a private headless workbench per test over a clone of the model's other roots (workbench.editor mounts a private real Editor on first use when a DOM exists), see plugins/lang-jstest/.