Scopeflow: the projectional scope()/dataflow() descriptor¶
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.
Track B of the scope()/dataflow() expressiveness-gap plan (.recall/todo.md's "Full GUI-authored scope/dataflow descriptor" entry — read that entry first for the authorization history and exact commit hashes) — a structured, projectionally-editable alternative to the flat ConceptSchema fields (scopeIntroducesSlot/scopeInitSlot/dataflowReadSlots/etc., Track A) that expose a GUI-authored concept's scope()/dataflow() behavior. Mirrors the node pattern language's own architecture almost exactly — read that doc first if you haven't; this one assumes familiarity with it and calls out only what differs. There is no single class tying these pieces together; read the phases below in order, since each depends on the previous one.
Scope, decided deliberately, not an oversight: this covers only the original 4 scope fields (introduces/initSlot/createsAssignBoundary/isAssignTarget) and 4 dataflow fields (isTerminator/readSlots/writeSlots/hoistable) — the 12 dataflow control-flow fields (dataflowIsBranch/isLoop/isTry/marksLive and their sub-fields) are left alone, sitting alongside, not subsumed. They're already name-keyed (no inheritance-hazard bake-in the way pre-fix scopeIntroducesSlot needed) and already tested against schema-only fixtures — nothing about scopeflow's nested-expression ambition applies to them. A projectional surface for those 12 too would be a genuinely separate scope decision.
- Phase 1 — the type family,
src/scopeflow-match.ts. Headless andLanguage-independent, mirroringpattern-match.ts's own split: aNameSourceunion (here/slot(slot, of?)/eachSlot(slot, of?)/combine(sources)) plusextractNames(source, value, lang?), the interpreter that walks aNameSourceagainst a real node and returnsscope.ts's ownNameEntry[](string | {name, node}). This is the real ambition gap Track A'sscopeIntroducesSlotcouldn't close: that field can only name a single flat slot's own bare contents.slot's ownofletsextractNamesreach a name through arbitrary nesting depth (e.g. a wrapper node one level around the real name-holding node);eachSlot/combinelet one node contribute more than oneNameEntry, each still carrying real binder-node identity viascope.ts's existing{name, node}pair — not just a flattened list of strings.
Slot resolution is dual-path by NAME, mirroring dataflow.ts's own _slotChild/_slotChildren exactly: a real BaseConcept instance's named accessor is tried first (works independent of lang availability), falling back to schema-array slotStart resolution only for a genuinely schema-only, GUI-authored node. This is deliberate and load-bearing, not incidental style-matching: it sidesteps the entire inheritance-hazard category scopeIntroducesSlot/scopeInitSlot needed a mergeInheritance re-derivation fix for (see that fix's own doc comment in lang-class-inheritance.ts) — a subtype's own slot keeps its own name no matter where inheritance places it in the merged children array, so introduces compiled from a scopeNode needs zero re-derivation at merge time. (initSlot is the one exception — see Phase 3.)
A slot's own contents can legitimately be a bare string primitive, not a wrapper/reference node — compileConceptScopeStructured's own doc comment calls this "the single most common real case" (e.g. EntityProperty's hand-written scope(), a bare string Prop). extractNames's leaf resolution (hereEntries) checks for this first (typeof v === "string", matching scopeIntroducesSlot's own typeof v === "string" ? v : refName(v) fallback) before falling through to scope.ts's refNameEntry for a real reference-shaped node. Getting this wrong is a real, easy-to-reintroduce bug — the first implementation only accepted reference-shaped nodes and silently produced zero entries for the single most common shape, caught by a real end-to-end test failure, not code review.
- Phase 2 — the projectional language,
plugins/lang-scopeflow/. OneBaseConceptperNameSourcevariant (SHere,SSlot,SEachSlot,SCombine), plus two small "root" concepts holding one concept's own descriptor fields:SScope(introduces?,initSlot_,createsAssignBoundary,isAssignTarget) andSDataflow(isTerminator,hoistable,slotRefs*).scopeflow-compile.ts'scompileNameSource/compileScopeDescriptor/compileDataflowDescriptorare the only place that translates a tree of these nodes into the Phase 1 plain-data shapes — the concepts are an authoring/persistence surface, never a second implementation of extraction semantics, same rulepattern-compile.ts's own file banner states.
SDataflow's readSlots/writeSlots share one variadic slotRefs list, tagged by entry head (SReadSlot/SWriteSlot), rather than two separate variadic ChildSlots on SDataflow itself — a concept can only ever have one trailing variadic slot (two would make the children array's layout ambiguous — where does the first list end and the second begin?). This mirrors PHeadMatch's own tagged-bindings-list precedent exactly. It was a real design bug in the first draft, caught by a test failure (readSlots/writeSlots reading back undefined), not spotted by inspection before writing the test.
An omitted optional (0..1) ChildSlot (e.g. SSlot's of, SScope's introduces) compiles to the __Empty__ placeholder node when a node is constructed via node(...), not to JS-undefined — see ast.ts's data-model note. scopeflow-compile.ts's "is this slot actually filled" checks (filledNode()) need isEmpty() as well as isNode(); checking isNode() alone treats the placeholder as "filled" and recurses into a meaningless node. Another real bug caught by the KDL round-trip test suite, not review — worth remembering for any future compiler in this codebase that reads an optional ChildSlot's own contents.
hidden = true, same posture and same reasoning as plugins/lang-pattern/: excluded from CORE_LANG_NAMES/DEMO_LANG_NAMES/BUILTIN_LANGUAGE_EXTENSIONS, still loadable on demand by explicit name via getBuiltinDef("scopeflow").
- Phase 3 — persistence,
lang-schema.ts+lang-codec-encode.ts/lang-codec-decode.ts+lang-class-inheritance.ts. A concept'sscopeKdl/dataflowKdl(persisted strings) andscopeNode/dataflowNode(their parsed form) round-trip through.lang.kdlthe same way a check rule'spatternKdl/patternNodedo —EvalNodeSchema.optional()inConceptSchema, encoded/decoded viascopeflowKdlProp/scopeflowNodeFields(lang-codec-encode.ts/decode.ts), resolved against a standalone "scopeflow"Languagefromscopeflow-lang-for-codec.ts'sgetScopeflowLangForCodec()— an exact twin ofpattern-lang-for-codec.ts, including the same dynamic-import()-inside-the-function structure (see the false starts below — both of that file's documented hazards reproduced verbatim here and needed the identical fix). UnlikepatternKdl/patternNode(validation-rule-level fields, nested inside a rule object),scopeKdl/scopeNode/dataflowKdl/dataflowNodeare concept-level fields, read straight off a concept's ownraw.props/c— soscopeflowNodeFieldstakes the wholeRawKdlNode, not a nestedv, and there is no equivalent ofvalidationToJs's special-case guard needed inlang-codec-to-js.ts: concept-level fields (likescopeBody/dataflowBody/evalbefore them) already flow through the.lang.jsmodule text via a generic spread, with no per-field fn-splicing logic to interact with.
lang-class-inheritance.ts's compileConceptScopeFromNode/compileConceptDataflowFromNode turn a decoded scopeNode/dataflowNode into the actual runtime scope()/dataflow() descriptor scope.ts/dataflow.ts consume, cloneWithIds()'d first — the exact same Zod .passthrough()-flattening fix compilePatternNodeIfNeeded needs for patternNode (see false start 3 below and that function's own doc comment). Wired into the existing precedence chain one rung below scopeBody/dataflowBody and above the flat structured fields: class method > body string > scopeNode/dataflowNode > flat fields > null. A GUI author who fills in scopeBody explicitly opts out of scopeNode/the flat fields for that concept, same as scopeBody already won over "no scope hook at all" before this existed.
initSlot is the one place introduces's "no re-derivation needed" story (Phase 1) doesn't apply: scope.ts's real runtime consumers (buildSymbolScopeMap and friends) read a descriptor's initIndex as a plain number at several call sites — a contract this plan deliberately doesn't touch, since changing it would touch every hand-written concept in the codebase for an additive, currently-low-consumer feature. So compileConceptScopeFromNode still bakes a numeric initIndex against a concept's own slots array, and gets the exact same mergeInheritance re-derivation scopeInitSlot already needed (recompiled against the merged, post-extends slots array) — a 2-level extends-chain test proves this fires correctly.
Getting the codec side working took the same two false starts pattern-lang-for-codec.ts's own doc comment records — both reproduced verbatim here, confirming they're a property of this codebase's module graph, not something specific to the pattern plugin:
-
A static import of the scopeflow plugin breaks
tsconfig.solid.json— same mechanism as point 1 in pattern-language.md's own Persistence section:lang-codec-encode.ts/lang-codec-decode.tsare reachable from Solid-scoped UI code, so a static import ofplugins/lang-scopeflow/languages/index.js(which importsconcepts.tsx, authored under the root tsconfig's token-JSX pragma) would pull that JSX-bearing file into the Solid JSX program too. Fixed the same way: resolve theLanguageviagetBuiltinDef("scopeflow"), reached throughlang-library.ts's template-literalimport()path, which neither tsconfig's program statically resolves. -
A static import of
lang-library.tscloses a real circular module dependency — same cycle as point 2 there (lang-codec-decode.ts→*-lang-for-codec.ts→lang-library.ts→ its own plugin scan →lang-core→lang-registry.ts→lang-codec.tsagain). Fixed identically:getScopeflowLangForCodec()importslang-library.ts/workbench/lang-class.tswith a dynamicimport()inside the function body, not at module top level. -
Zod flattens a decoded
scopeNode/dataflowNode's class instances into plain objects — sameEvalNodeSchema.passthrough()mechanism as point 3 there.compileScopeDescriptor/compileDataflowDescriptor/compileNameSource(scopeflow-compile.ts) read slot contents through named instance properties (inst.introduces,inst.slot_,inst.sources, ...) —BaseConcept's own non-enumerable prototype accessors, absent on a Zod-reconstructed plain object. Fixed the same way:cloneWithIds(scopeNode)/cloneWithIds(dataflowNode)at the one compile call site that currently exists (lang-class-inheritance.ts'scompileConceptScopeFromNode/compileConceptDataflowFromNode). Any future compile call site — most notably the Language-Pane live-editor mount point below, once it exists — needs the identical call, exactly aschecks-pane.tsx'sloadRulesFromLangneeded it for the pattern precedent.
Verified end-to-end (not just unit-level): a concept's scopeNode/dataflowNode survive a full .lang.kdl and .lang.js save/reload and still compile to a correct, working runtime descriptor — including the nested SSlot→SSlot introduces path and the initSlot inheritance re-derivation (tests/test-scopeflow-persistence.mjs, tests/test-scopeflow-kdl-roundtrip.mjs, tests/test-lang-class-inheritance.mjs).
- Phase 4 — inline authoring,
language-pane-concept-code.ts'srenderScopeflowFieldEditor. A live scopeflow-tree mini-editor sits directly below each of the existing "scope"/"dataflow" sections'scopeBody/dataflowBodytextareas (an alternative authoring surface alongside them, not a replacement —scopeBodystill wins per the Phase 3 precedence chain). Unlike the pattern language's own Phase 4 (src/ui/checks-pane.tsx'sPatternFieldEditor, built with JSX since that file is already Solid-scoped), this file has no JSX at all —renderScopeflowFieldEditoris the plain-DOM-calls equivalent of the identical sequence, matching this file's own imperative style throughout.
The feared cross-tsconfig indirection hazard turned out to already have a generic solution in place: LanguagePane's constructor-injected mountConceptEditor (src/ui/language-pane-concept-source-editor.ts already routes every concept's own sub-editor through it) is reachable here as this.mountConceptEditor, since this file's attachConceptCodeAspects is a mixin applied to the same LanguagePane.prototype. So this is a second call site of an already-injected function, not a new mount mechanism — no new file, no new constructor wiring. cloneWithIds() on the initial node before constructing Editor is still required, for the same Zod-flattening reason patternNode/scopeNode/dataflowNode need it everywhere else (Phase 3's false start 3) — a concept freshly decoded from .lang.kdl/.lang.js has none of SScope/SSlot/etc.'s own BaseConcept accessors.
Persists live/immediately on every edit (onSave, wired from Editor's own onChange) — no Apply button, matching checks-pane.tsx's own pattern-tree convention (only the free-text CodeMirror boxes use Apply) and the structured checkbox fields' "commit immediately, since this is plain data" convention. An absent scopeNode/dataflowNode shows a "+ Add projectional scope/dataflow tree" button (seeds a fresh SScope/SDataflow node via defaultScopeflowNode); a present one shows the live tree plus a "Remove tree" button that clears the field and reverts to "+ Add".
Verified live, not just via jsdom (per CLAUDE.md's own "a vitest/jsdom pass is not proof" rule for this category of change) — both tsconfigs typecheck clean first (confirming the specific failure mode above did not recur), then a full Playwright pass against the real webview (npm run dev): imported a freshly-generated .lang.kdl fixture (the standalone preview's own "Add new concept" isn't wired outside Theia — onConceptAdd has no implementation under src/routes/, only in theia-api.tsx; confirmed by grep before relying on it, not assumed), opened the imported concept's form, clicked both "+ Add projectional scope/dataflow tree" buttons, and confirmed each mounts a real NodeRenderer-rendered tree (correct syntax-highlighted tokens and a clickable + introduces slot-add affordance — not raw/unstyled text), "Remove tree" correctly tears down and restores the Add button, and zero console errors throughout. 61 jsdom tests (tests/test-language-pane-concept-code.mjs) cover the synchronous button-click → lang.setConcept() wiring; the live pass covers what jsdom structurally cannot (the actual mountConceptEditor/NodeRenderer render path).