Programmatic model API¶
Split out of
CLAUDE.mdto 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.tsis nowsrc/workbench-api/model-nodes.tsand the barrelsrc/api.tswas removed with the workbench API (seedocs/architecture/workbench-api.mdand the migration guidewebsite/docs/dev/authoring/workbench-api-migration.md). Where this page sayssrc/model-api.tsorsrc/api.tsbelow, read the new path; the fluent classes are the node handlesworkbench.modelreturns.
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(formerlysmodel.js) — the fluent query/manipulation API over the AST:ModelNode(wasSNode),NodeList(wasSNodeList),Model(wasSModel),ProjectSummary(a reduced read-only view ofworkbench/project.ts's realProject, wasSProject— kept as a separate class because the realProjectcarries full model ASTs and filesystem-handle internals a display-only summary must never dump). WrapsAstNav/src/model.tsrather than reimplementing tree walking. A model holds zero or more root nodes (workbench/project.ts'sProjectModel.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, andaddRoot(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})keepsroot/nodemeaning "the currently open root" (fornode.ancestor(...)-style navigation from the live selection) whilemodelRoots(defaults to[root]when the caller has no project model in scope) feedsModel._roots— the console'smodel/roots(...)/nodes(...)bindings therefore see every root, not just the open one.saveModelpersists a rootaddRoot()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 (seesrc/api.tsbelow). The chained operations (roots(...),nodes(...),.ancestor(...),.children(...),.descendants(...),.where(...),.size()) are real concepts (src/console/query-concepts.tsx'sQRoots/QAncestor/etc.), not genericobj.method(args)dispatch —composeConsoleLanguage(activeLang)layers them onto the active document language at runtime (viaimportedLanguages, 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 viaNodeRendererin 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), andrefactor-symbol.ts's_transformToCallpromotesobj.name(straight to the matching one (found by stripping the leading.and trailing(...)/()off itsalias) instead of the genericattrCall, once there's a name to match against — falling through toattrCallunchanged for every other name. User-facing docs:website/docs/model-console.mdand 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 exposeenv.vars.model, the currently OPEN model.model/<name>(QModelRef, aliasotherModel— 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 realModelwrapping it, built against a freshModelApiCtxwith 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 thatModel, no further new concepts were needed:.roots(...)/.nodes(...)/.name/.children()/.descendants()/.ancestor()/.where()/.select()/.foreach()/.size()all already work through the generictarget[method](...)dispatch in Core'sAttrCall.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 realProjectModel[], threaded bybuildSmodelScopefrom its ownprojectargument, not fromProjectSummary._raw) is whatQModelRef.eval()searches;ProjectSummary.models(the console'sproject.modelsbinding) was extended with anfqnfield so what a user can discover there matches whatmodel/<name>actually accepts. Mutating a model reached this way (.addRoot(...)) is fully read-write, not read-only —QModelRef.eval()builds itsModel'sModelApiCtxwith a realaddRootEntry(callingworkbench/project.ts'saddRootToProjectModelagainst the resolved foreignProjectModel) and a realsaveModel(saveModelAndSyncMetaagainst its owningProject, which may be an attached one, not just the active project) — the exact same two functionseditor-view-core.ts'sgetConsoleContext()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 (viactx.addRootEntry/ctx.saveModelabove), but persisting it is not the same as showing it:ctx.refreshonly 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 becausemodel.rootsgained an entry.editor-view-core.ts'sgetConsoleContext().addRootEntryandtheia-api-mount.tsx's Theia-native equivalent both now also call the project pane'srefresh()/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'sopenModel(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) — aModelNode/NodeListresult renders as a clickable label (click navigates to the node); aModelresult (model, or a resolvedmodel/<name>) and aproject.modelsentry ({name, filename, fqn}) now get the same treatment via a click target keyed byfqninstead of node id (ConsoleResultItem'sid-vs-fqnsplit) — resolved back to a real model viaquery-concepts.tsx's exportedresolveModelAcrossProjectsand opened with the sameopenModel()the Explorer itself uses. Previously these fell through toformatValue()'s plain-text/JSON branch with no navigation at all. - Typesystem integration for query concepts — every
Q*concept inquery-concepts.tsxnow declares a realtypesystem()(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), achecks()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'sinfer()is polymorphic on its receiver's own inferred type (ModelNodein →ModelNodeout,NodeListin →NodeListout), matchingmodel-api.ts's real polymorphic.ancestor().QChildrenadditionally reports a receiver-shape error (not just a style nit) when its receiver infers asNodeList, sinceNodeListhas no.children()of its own andeval()would otherwise throw at runtime. These diagnostics reach the console's own editor cells via a dedicated signal (console-panel.tsx'sconsoleCheckResults, computed byrunChecks(consoleRoot, consoleLang())on every edit) fed throughNodeRenderer.tsx's newIssuesContextoverride — deliberately NOT merged into the main document's owncheckResults(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'sconsoleReceiverKindstays 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'spatternsbinding (buildSmodelScope'spatterns, a namespace ofsrc/pattern-match.ts's builders) expose the pattern engine'sassertStructure(throwsStructureMismatchErrorwith a path such asroot.body[2].value,root= the receiver node). They need no query concept: like every otherModelNodemethod they are reached viaAttrCall's generic dispatch. Seedocs/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 insideLanguage.allEffectiveConcepts()/getConceptOwner(). Two generators instead of one class per traversal shape:walkNodes(root, {order, includeSelf, prune, unique})(lazy AST walk;prunereturningfalseskips a subtree, coveringTreeFilterIterator/skipChildren()) andwalkConceptHierarchy(head, lang, {order, maxDepth, includeSelf, unique})(lazy walk of a concept'sextendsparent chain +implements_interfaces;order:"breadth"andmaxDepth:1coverBreadthConceptHierarchyIterator/ImmediateParentConceptIteratoras options rather than separate classes). Unlike an AST, anextends/implements_graph can cycle if a language is malformed (lang-class-inheritance.ts'smergeInheritancethrows on this at load time);walkConceptHierarchyinstead 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'sdescendants/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 insidechecker.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 throughworkbench.*; 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 givensuccessors(node):stronglyConnectedComponents(Tarjan),findCycles(components that really are cycles, self-loops included),componentOf,reachableFrom,isConnected(nodes, successors, initial)(directed: doesinitialreach everything) and a stabletopologicalSortthat returns{order}or, for a cyclic graph,{order: null, cycles}so a check can report them. Re-exported fromapi.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 owndependsOnsort 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, elsename (shortest-distinguishing-suffix-of-fqn). Consumer:EditorView.tsx's "Add model import…" picker, which used to key aMapby 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>whennodeis a concept-class instance: prototype accessors installed byslotLayoutOf(src/base-concept.ts) under the field name (then_,title), not the slot name. The accessor unwraps aLiteral-wrapped scalar (every element of a variadic run);Ref/Propslots 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 aLanguageto find the concept and unwrap exactly like the accessor.slotValuesreturns the whole run of a variadic slot, a one-element array otherwise.rawSlotValue(...)/rawSlotValues(...)return the child as stored,Literalwrapper kept: use them where the wrapper node itself matters (editing, serializing, mirroring).fieldsOf(node)(src/node-fields.ts) when noLanguageis in hand:const { a, b } = fieldsOf(node)is the node itself for a concept instance, else a view sharing itschildren.field/rawField/setRawFieldread and write one slot by name there; an unknown name throws instead of readingundefined. 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.