Skip to content

Programmatic model API

Split out of CLAUDE.md to keep that file's per-session load light. Linked from there — read this when you're actually touching this subsystem.

Programmatic model API — src/workbench-api/model-nodes.ts, src/tree-iteration.ts

Moved. src/model-api.ts is now src/workbench-api/model-nodes.ts and the barrel src/api.ts was removed with the workbench API (see docs/architecture/workbench-api.md and the migration guide website/docs/dev/authoring/workbench-api-migration.md). Where this page says src/model-api.ts or src/api.ts below, read the new path; the fluent classes are the node handles workbench.model returns.

A documented, importable surface for language-designer/tooling code to work with a model, language, or concept graph programmatically — deliberately not using another well-known workbench's S-prefixed class names (SNode/SModel/SConcept/...).

  • src/model-api.ts (formerly smodel.js) — the fluent query/manipulation API over the AST: ModelNode (was SNode), NodeList (was SNodeList), Model (was SModel), ProjectSummary (a reduced read-only view of workbench/project.ts's real Project, was SProject — kept as a separate class because the real Project carries full model ASTs and filesystem-handle internals a display-only summary must never dump). Wraps AstNav/src/model.ts rather than reimplementing tree walking. A model holds zero or more root nodes (workbench/project.ts's ProjectModel.roots) — Model._roots: Node[] holds all of them (a live reference to that same array when threaded from a real project, so mutating it is a real, persistent change), roots(concept)/nodes(concept) see/walk every one, and addRoot(concept) always appends a new one rather than ever refusing because one already exists. The Editor itself still only ever displays one root at a time — buildSmodelScope({root, focusNode, lang, editor, project, modelRoots, saveModel}) keeps root/node meaning "the currently open root" (for node.ancestor(...)-style navigation from the live selection) while modelRoots (defaults to [root] when the caller has no project model in scope) feeds Model._roots — the console's model/roots(...)/nodes(...) bindings therefore see every root, not just the open one. saveModel persists a root addRoot() just appended — distinct from the ordinary editor-autosave path, which is tied to the open root changing and never fires for a newly appended one it didn't touch. Consumed by the in-app Model Console panel (src/routes/console-panel.tsx), a projectional REPL — the console's own input editor is the same structural editing engine as the main document, not free-typed text, so this API is one consumer of it, not the only one (see src/api.ts below). The chained operations (roots(...), nodes(...), .ancestor(...), .children(...), .descendants(...), .where(...), .size()) are real concepts (src/console/query-concepts.tsx's QRoots/QAncestor/etc.), not generic obj.method(args) dispatch — composeConsoleLanguage(activeLang) layers them onto the active document language at runtime (via importedLanguages, never persisted/discoverable as a project language) so the console's own editor offers them through the same completion/checking machinery as any other concept, and query results that are AST nodes render via NodeRenderer in the output log instead of flattened text. Postfix chaining (nodes(...).ancestor(...)) works via ordinary typing, not just explicit Ctrl-Space completion: a receiver-shaped concept is any concept whose first slot is named "receiver" (a language-agnostic marker, checked nowhere else in the engine), and refactor-symbol.ts's _transformToCall promotes obj.name( straight to the matching one (found by stripping the leading . and trailing (...)/() off its alias) instead of the generic attrCall, once there's a name to match against — falling through to attrCall unchanged for every other name. User-facing docs: website/docs/model-console.md and the in-app Docs tab's "Model Console & Query Language" page.
  • Referencing another model from the console — model/node/root/project (QModel/etc.) only ever expose env.vars.model, the currently OPEN model. model/<name> (QModelRef, alias otherModel — see docs/architecture/qualified-names.md for the name format) resolves an arbitrary OTHER model in the project by qualified name (accepting the small kebab FQN, the older package-qualified name, or a bare display name) and returns a real Model wrapping it, built against a fresh ModelApiCtx with THAT model's own resolved language (ProjectModelMeta.language) — never the currently active one, since a different model in the project isn't guaranteed to share it. Once you have that Model, no further new concepts were needed: .roots(...)/.nodes(...)/.name/.children()/.descendants()/.ancestor()/.where()/.select()/.foreach()/.size() all already work through the generic target[method](...) dispatch in Core's AttrCall.eval() (plugins/lang-core/languages/concepts-modules.concept.js) — the same mechanism this file's header already documents as the fallback path underneath the query concepts. env.vars.projectModels (the project's real ProjectModel[], threaded by buildSmodelScope from its own project argument, not from ProjectSummary._raw) is what QModelRef.eval() searches; ProjectSummary.models (the console's project.models binding) was extended with an fqn field so what a user can discover there matches what model/<name> actually accepts. Mutating a model reached this way (.addRoot(...)) is fully read-write, not read-only — QModelRef.eval() builds its Model's ModelApiCtx with a real addRootEntry (calling workbench/project.ts's addRootToProjectModel against the resolved foreign ProjectModel) and a real saveModel (saveModelAndSyncMeta against its owning Project, which may be an attached one, not just the active project) — the exact same two functions editor-view-core.ts's getConsoleContext() wires up for the currently-open model. A mutation this way is exactly as real and persisted as mutating the active model directly.
  • model.addRoot(...) and UI feedback — Model.addRoot() (model-api.ts) always durably appends and persists a new root (via ctx.addRootEntry/ctx.saveModel above), but persisting it is not the same as showing it: ctx.refresh only re-renders whichever root is currently open in the editor (editor.fire()), and the Explorer/project-pane tree (ProjectPane, an imperative, non-reactive controller — see CLAUDE.md's UI panes section) never repaints on its own just because model.roots gained an entry. editor-view-core.ts's getConsoleContext().addRootEntry and theia-api-mount.tsx's Theia-native equivalent both now also call the project pane's refresh()/revealModel(model) after appending, so the new root becomes visible in the Explorer immediately — without navigating the user's currently-open editor away from whatever they were looking at (deliberately not the menu-driven "Add Root Node" command's openModel(model, {root: newRootFile}) behavior, which is a fine thing to do from an explicit modal-driven action but a surprising side effect of a console expression that might be mutating a model other than the one currently open).
  • Console result rendering (console-panel.tsx) — a ModelNode/NodeList result renders as a clickable label (click navigates to the node); a Model result (model, or a resolved model/<name>) and a project.models entry ({name, filename, fqn}) now get the same treatment via a click target keyed by fqn instead of node id (ConsoleResultItem's id-vs-fqn split) — resolved back to a real model via query-concepts.tsx's exported resolveModelAcrossProjects and opened with the same openModel() the Explorer itself uses. Previously these fell through to formatValue()'s plain-text/JSON branch with no navigation at all.
  • Typesystem integration for query concepts — every Q* concept in query-concepts.tsx now declares a real typesystem() (infer() for its return type, check() where a wrong literal argument is statically catchable) and, for the four concepts whose one argument is a concept-name filter (QRoots/QNodes/QDescendants/QAncestor), a checks() validating it against the active language's real concepts. Return types use "Model"/"ModelNode"/"NodeList"/"ProjectSummary" as unregistered convention type names (exactly like typesystem.ts's own doc already permits for language-specific types) — no upfront registration needed, since any never-seen name is just an unrelated constructor; two of these are only ever compared for exact equality or "any"-compatibility here, never subtyped against one another. QAncestor's infer() is polymorphic on its receiver's own inferred type (ModelNode in → ModelNode out, NodeList in → NodeList out), matching model-api.ts's real polymorphic .ancestor(). QChildren additionally reports a receiver-shape error (not just a style nit) when its receiver infers as NodeList, since NodeList has no .children() of its own and eval() would otherwise throw at runtime. These diagnostics reach the console's own editor cells via a dedicated signal (console-panel.tsx's consoleCheckResults, computed by runChecks(consoleRoot, consoleLang()) on every edit) fed through NodeRenderer.tsx's new IssuesContext override — deliberately NOT merged into the main document's own checkResults (node ids are globally unique so it technically wouldn't collide, but it would wrongly count the console's own query mistakes in the main document's Problems panel). completion-sections-console-members.ts's consoleReceiverKind stays its own separate, narrower completion-only mechanism rather than being rebuilt on this — see that file's own updated doc comment for why.
  • Structure assertions — ModelNode.assertStructure(pattern) / matchesStructure(pattern) and the console's patterns binding (buildSmodelScope's patterns, a namespace of src/pattern-match.ts's builders) expose the pattern engine's assertStructure (throws StructureMismatchError with a path such as root.body[2].value, root = the receiver node). They need no query concept: like every other ModelNode method they are reached via AttrCall's generic dispatch. See docs/architecture/pattern-language.md's Structure Check section for the sequence/condition vocabulary.
  • src/tree-iteration.ts — lazy traversal utilities filling the specific gap a familiar family of tree/hierarchy iterator classes (DepthFirstConceptIterator, DescendantsTreeIterator, BreadthConceptHierarchyIterator, ImmediateParentConceptIterator, TreeFilterIterator, FilterIterator, UniqueIterator) cover elsewhere — struktJS had no reusable traversal over the concept/language inheritance graph before this, only ad hoc loops inside Language.allEffectiveConcepts()/getConceptOwner(). Two generators instead of one class per traversal shape: walkNodes(root, {order, includeSelf, prune, unique}) (lazy AST walk; prune returning false skips a subtree, covering TreeFilterIterator/skipChildren()) and walkConceptHierarchy(head, lang, {order, maxDepth, includeSelf, unique}) (lazy walk of a concept's extends parent chain + implements_ interfaces; order:"breadth" and maxDepth:1 cover BreadthConceptHierarchyIterator/ImmediateParentConceptIterator as options rather than separate classes). Unlike an AST, an extends/implements_ graph can cycle if a language is malformed (lang-class-inheritance.ts's mergeInheritance throws on this at load time); walkConceptHierarchy instead silently stops descending back into a head already on the current branch's path, since this is a read-only reflection utility and an unrelated caller shouldn't see a load-time-style error. The existing eager walkers (src/model.ts's descendants/ancestors/findFirst, AstNav.descendants) are unchanged and still the right tool for a full array up front; these generators are for lazy/large/short-circuiting traversal. Not migrated onto these: the hand-rolled per-pass walks inside checker.ts, generator.ts, scope.ts, typesystem.ts, dataflow.ts, constraint-runner.ts, link-target.ts — each threads pass-specific state (accumulators, scope envs, boundary short-circuiting) a generic iterator can't express.
  • src/api.ts — removed (it was a re-export barrel with no implementation). Import each symbol from the module that defines it, or call the tool through workbench.*; see the migration guide.

  • src/graph-util.ts — pure, iterative (no recursion, safe on a 100k-node chain) directed-graph helpers over any node type given successors(node): stronglyConnectedComponents (Tarjan), findCycles (components that really are cycles, self-loops included), componentOf, reachableFrom, isConnected(nodes, successors, initial) (directed: does initial reach everything) and a stable topologicalSort that returns {order} or, for a cyclic graph, {order: null, cycles} so a check can report them. Re-exported from api.ts. First consumer is nothing in-tree yet; it exists for checks/generators that need a cycle report (an entity-reference or state-machine cycle) — lang-library.ts's own dependsOn sort is deliberately left alone. Tests: tests/test-graph-util.mjs.

  • src/unique-names.ts — uniqueDisplayNames([{name, fqn}]): the label for each entry, unchanged when its name is unique, else name (shortest-distinguishing-suffix-of-fqn). Consumer: EditorView.tsx's "Add model import…" picker, which used to key a Map by bare model name so two same-named models silently shadowed each other. Not built: an editor hint that shortens/extends reference cells on the canvas (the MPS "Unique Names" hint proper) — no concrete place needs it yet.

Named child access — src/model.ts, src/node-fields.ts

A node's children array is positional storage; outside the AST core (src/ast.ts, src/base-concept.ts, src/model.ts, src/kdl.ts) code reads a child by its slot name, and tests/test-no-positional-children.mjs ratchets x.children[n] reads down. Plan and status: docs/architecture/named-child-access-plan.md. Which accessor to use:

  • node.<field> when node is a concept-class instance: prototype accessors installed by slotLayoutOf (src/base-concept.ts) under the field name (then_, title), not the slot name. The accessor unwraps a Literal-wrapped scalar (every element of a variadic run); Ref/Prop slots are returned as stored. A variadic slot returns the run as an array.
  • slotValue(node, "slot", lang) / slotValues(...) (src/model.ts) for plain-object nodes, generic code and dynamic slot names. They need a Language to find the concept and unwrap exactly like the accessor. slotValues returns the whole run of a variadic slot, a one-element array otherwise.
  • rawSlotValue(...) / rawSlotValues(...) return the child as stored, Literal wrapper kept: use them where the wrapper node itself matters (editing, serializing, mirroring).
  • fieldsOf(node) (src/node-fields.ts) when no Language is in hand: const { a, b } = fieldsOf(node) is the node itself for a concept instance, else a view sharing its children. field/rawField/setRawField read and write one slot by name there; an unknown name throws instead of reading undefined. They need a registered concept factory for the node's head.
  • nameText(node) / setNameText(node, name) (src/model.ts) for the text a name-bearing node (reference, declaration, root) spells.