@telorun/analyzer 0.68.0 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/analysis-registry.d.ts +12 -0
  2. package/dist/analysis-registry.d.ts.map +1 -1
  3. package/dist/analysis-registry.js +26 -0
  4. package/dist/call-graph.d.ts +80 -1
  5. package/dist/call-graph.d.ts.map +1 -1
  6. package/dist/call-graph.js +145 -12
  7. package/dist/canonical-json.d.ts +18 -0
  8. package/dist/canonical-json.d.ts.map +1 -0
  9. package/dist/canonical-json.js +26 -0
  10. package/dist/cel-access-chains.d.ts +14 -0
  11. package/dist/cel-access-chains.d.ts.map +1 -0
  12. package/dist/cel-access-chains.js +45 -0
  13. package/dist/import-resolution-diagnostics.d.ts.map +1 -1
  14. package/dist/import-resolution-diagnostics.js +22 -8
  15. package/dist/index.d.ts +7 -5
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +5 -4
  18. package/dist/loaded-types.d.ts +4 -4
  19. package/dist/loaded-types.d.ts.map +1 -1
  20. package/dist/manifest-analysis.d.ts +19 -0
  21. package/dist/manifest-analysis.d.ts.map +1 -1
  22. package/dist/manifest-analysis.js +27 -0
  23. package/dist/manifest-diff.d.ts +111 -0
  24. package/dist/manifest-diff.d.ts.map +1 -0
  25. package/dist/manifest-diff.js +130 -0
  26. package/dist/manifest-loader.d.ts +3 -4
  27. package/dist/manifest-loader.d.ts.map +1 -1
  28. package/dist/manifest-loader.js +4 -5
  29. package/dist/manifest-schemas.d.ts +2 -0
  30. package/dist/manifest-schemas.d.ts.map +1 -1
  31. package/dist/manifest-schemas.js +4 -0
  32. package/dist/module-graph.d.ts +500 -0
  33. package/dist/module-graph.d.ts.map +1 -0
  34. package/dist/module-graph.js +1389 -0
  35. package/dist/reconcile-module-versions.d.ts.map +1 -1
  36. package/dist/reconcile-module-versions.js +10 -11
  37. package/dist/release/release-plan.d.ts +1 -1
  38. package/dist/resolve-zone-containment.d.ts +9 -1
  39. package/dist/resolve-zone-containment.d.ts.map +1 -1
  40. package/dist/resolve-zone-containment.js +34 -6
  41. package/dist/resolve-zone-requirements.d.ts.map +1 -1
  42. package/dist/resolve-zone-requirements.js +4 -2
  43. package/dist/sources/default-sources.d.ts +6 -6
  44. package/dist/sources/default-sources.d.ts.map +1 -1
  45. package/dist/sources/default-sources.js +7 -8
  46. package/dist/sources/integrity.d.ts +3 -2
  47. package/dist/sources/integrity.d.ts.map +1 -1
  48. package/dist/sources/integrity.js +26 -3
  49. package/dist/sources/versioned-ref.d.ts +17 -12
  50. package/dist/sources/versioned-ref.d.ts.map +1 -1
  51. package/dist/sources/versioned-ref.js +22 -24
  52. package/dist/telo-version.d.ts +1 -1
  53. package/dist/telo-version.js +1 -1
  54. package/package.json +2 -2
  55. package/src/analysis-registry.ts +37 -0
  56. package/src/call-graph.ts +207 -14
  57. package/src/canonical-json.ts +24 -0
  58. package/src/cel-access-chains.ts +47 -0
  59. package/src/import-resolution-diagnostics.ts +24 -7
  60. package/src/index.ts +46 -5
  61. package/src/loaded-types.ts +4 -4
  62. package/src/manifest-analysis.ts +39 -0
  63. package/src/manifest-diff.ts +219 -0
  64. package/src/manifest-loader.ts +4 -5
  65. package/src/manifest-schemas.ts +4 -0
  66. package/src/module-graph.ts +1983 -0
  67. package/src/reconcile-module-versions.ts +10 -11
  68. package/src/release/release-plan.ts +1 -1
  69. package/src/resolve-zone-containment.ts +49 -9
  70. package/src/resolve-zone-requirements.ts +7 -2
  71. package/src/sources/default-sources.ts +7 -8
  72. package/src/sources/integrity.ts +28 -3
  73. package/src/sources/versioned-ref.ts +26 -28
  74. package/src/telo-version.ts +1 -1
  75. package/dist/sources/module-ref.d.ts +0 -21
  76. package/dist/sources/module-ref.d.ts.map +0 -1
  77. package/dist/sources/module-ref.js +0 -36
  78. package/dist/sources/registry-source.d.ts +0 -14
  79. package/dist/sources/registry-source.d.ts.map +0 -1
  80. package/dist/sources/registry-source.js +0 -45
  81. package/src/sources/module-ref.ts +0 -49
  82. package/src/sources/registry-source.ts +0 -52
@@ -0,0 +1,1983 @@
1
+ /**
2
+ * The module graph — what a module IS, as boxes, rows and classed edges.
3
+ *
4
+ * One fold over the call graph, the reference field map and each kind's own
5
+ * schema, producing the three primitives an editor draws:
6
+ *
7
+ * - **Box** — a declaration and what it owns. Every resource is a node whatever
8
+ * declaration form it arrived in (named, inline, `with:`-scoped, imported,
9
+ * injected), plus the module root, which is not a resource but owns `targets`.
10
+ * - **Row** — one ORDERED entry inside a box: a step, an entry-list item (a
11
+ * route, a mount), a boot target. Order is manifest data, so it is carried
12
+ * rather than re-derived; a row is where reordering is expressible at all.
13
+ * - **Edge** — a reference leaving a PORT, classed by what the slot's `use`
14
+ * says happens at it.
15
+ *
16
+ * **Ports are declared, not discovered.** A port exists because the kind's
17
+ * schema declares a ref slot, so an EMPTY slot is a port with an empty
18
+ * occupancy — the fact that `notFoundHandler` is unset is as much a property of
19
+ * the application as the fact that `mounts` has two entries, and it is the only
20
+ * thing an editor can offer to fill.
21
+ *
22
+ * **Three edge classes, not six uses.** What a reader must distinguish is
23
+ * whether control transfers, not which of four ways it does:
24
+ * `call` / `detached` / `trigger.inbound` / `trigger.consumer` are **flow**,
25
+ * `dependency` is **holds**, `schema` is **shape** — a type annotation rather
26
+ * than a runtime relation. The six-value `use` stays on the edge for consumers
27
+ * that need the distinction; the class is what a view draws.
28
+ *
29
+ * **Identity is anchored on names, never on indices.** A row addressed by array
30
+ * index shifts when a sibling is inserted above it, so selection and sticky
31
+ * expansion would detach precisely while the user is editing — the primary use
32
+ * case. Where the grammar offers a name (a step's `name:`, a resource's
33
+ * `metadata.name`) the name is the identity; where it does not (an unnamed
34
+ * route, an unnamed step) the identity is the nearest named ancestor plus a
35
+ * content-derived key. The same reason the migration driver refuses indexed
36
+ * matches into a resized array: a stale key resolves to nothing, a stale index
37
+ * silently names a different element.
38
+ *
39
+ * **What is deliberately NOT here: view policy.** Bands, labels, layout and
40
+ * expansion are the editor's, so nothing in this file reads a schema `title` or
41
+ * decides where a node is drawn. What it emits is the fact each of those
42
+ * decisions is taken from — capability, ownership, edge class, `boot` — so two
43
+ * hosts drawing the same module cannot disagree about what it contains.
44
+ *
45
+ * Browser-safe: no Node built-ins.
46
+ */
47
+ import type { ResourceDefinition, ResourceManifest } from "@telorun/sdk";
48
+ import {
49
+ buildCelEnvironment,
50
+ extractAccessChains,
51
+ isRefSentinel,
52
+ walkCelExpressions,
53
+ } from "@telorun/templating";
54
+ import {
55
+ nodeIdFor,
56
+ resolveScopedName,
57
+ resourceId,
58
+ type CallGraph,
59
+ type CallGraphEdge,
60
+ type ResourceGraphNode,
61
+ type StepGraphNode,
62
+ } from "./call-graph.js";
63
+ import { propertySchemas, resolveLocalRef } from "./manifest-navigation.js";
64
+ import { isStepSlot } from "./step-slot.js";
65
+ import { isInlineResource, resolveFieldEntries } from "./reference-field-map.js";
66
+ import { findZoneProviders } from "./resolve-zone-containment.js";
67
+ import { possibleUses, readRefSlot, type RefUse } from "./ref-slot.js";
68
+ import { canonicalJson } from "./canonical-json.js";
69
+ import { accessChains } from "./cel-access-chains.js";
70
+
71
+ /** How a node's declaration reached the module, which is what decides where a
72
+ * view may draw it — an inline child exists nowhere but its parent's YAML, so
73
+ * it is never a peer of the resource holding it. */
74
+ export type NodeOwnership = "root" | "named" | "inline" | "scoped" | "imported" | "injected";
75
+
76
+ /**
77
+ * What happens at a site, reduced to what a view draws.
78
+ *
79
+ * The first three classify a REFERENCE by its `use`; `data` is not a reference
80
+ * at all — it is one resource reading another's published state in CEL
81
+ * (`resources.<name>.status.<field>`), which is a real dependency the reference
82
+ * graph does not carry and which no slot declares.
83
+ */
84
+ export type EdgeClass = "flow" | "holds" | "shape" | "data";
85
+
86
+ /**
87
+ * What a line of a body is.
88
+ *
89
+ * The first three are ORDERED entries of an array — a step, an entry-list item,
90
+ * a boot target — and reordering one is the point of drawing them. The last two
91
+ * are not positions at all: a slot may hold a DECLARATION rather than a name
92
+ * (`invoke: { kind: …, …config }`), and that declaration exists nowhere but the
93
+ * site, so it has no array to sit in and no sibling to be moved past. It is a
94
+ * line of the body because it is a thing the author wrote and has to be able to
95
+ * reach; see {@link isOrderedRow}.
96
+ */
97
+ export type RowKind = "step" | "entry" | "target" | "inline" | "reference";
98
+
99
+ /**
100
+ * Rows that are ordered entries of their array.
101
+ *
102
+ * A consumer offering reorder, removal or an index must ask — a declaration
103
+ * written at a dispatch site carries an `index` of 0 and an `array` it shares
104
+ * with its host, both of which are borrowed so it groups into the right branch,
105
+ * and neither of which means what it means on a step.
106
+ */
107
+ export function isOrderedRow(row: GraphRow): boolean {
108
+ return row.kind === "step" || row.kind === "entry" || row.kind === "target";
109
+ }
110
+
111
+ /** One occupancy of a port: the concrete site, and the name it holds. */
112
+ export interface PortSlot {
113
+ /** Concrete path of this site (`mounts[1].mount`), the write target. */
114
+ path: string;
115
+ /** Referenced resource name, absent for an empty slot. */
116
+ target?: string;
117
+ /** Node id the name resolves to, absent when it resolves to nothing. */
118
+ targetNode?: string;
119
+ /** The site holds an inline declaration rather than a reference; `targetNode`
120
+ * is the extracted child. */
121
+ inline?: boolean;
122
+ }
123
+
124
+ /** A reference slot the kind declares, filled or not. */
125
+ export interface GraphPort {
126
+ /** Field-map path with `[]` / `{}` markers — the port's identity on its node. */
127
+ slot: string;
128
+ /** Accepted `x-telo-ref` constraints, canonicalized. */
129
+ refs: string[];
130
+ /** Capabilities a target may satisfy — what validates a wire. */
131
+ capabilities: string[];
132
+ /** The slot traverses at least one array, so it takes many targets. */
133
+ array: boolean;
134
+ class: EdgeClass;
135
+ slots: PortSlot[];
136
+ /** Concrete path a new array item would be written at. Array ports only. */
137
+ addPath?: string;
138
+ /** This slot's occupancy is drawn as ROWS rather than as port slots — the
139
+ * slot sits inside a step body or an entry list, where order is semantic and
140
+ * the row is the thing a reader manipulates. */
141
+ rowOwned?: boolean;
142
+ }
143
+
144
+ /** One ordered entry inside a box. */
145
+ export interface GraphRow {
146
+ /** Name-anchored identity, stable across insertion of a sibling. */
147
+ id: string;
148
+ kind: RowKind;
149
+ /** What the manifest calls this line: a step's `name:`, or — for a
150
+ * `reference` row — the field holding it. Absent where the grammar offers
151
+ * neither (an unnamed route, an `inline` row, which is named by its kind). */
152
+ name?: string;
153
+ /** Concrete path of the row (`steps[0].do[1]`, `routes[2]`) — the write
154
+ * target, and what a position index is keyed by. */
155
+ path: string;
156
+ /** Concrete path of the array holding it, the reorder domain. */
157
+ array: string;
158
+ /** Lexical index within that array. */
159
+ index: number;
160
+ /** Nesting depth: 0 at the body's top level, +1 inside each branch. */
161
+ depth: number;
162
+ /** Row id of the enclosing row, when this one nests inside a branch. */
163
+ parent?: string;
164
+ /** Referenced name this row dispatches to, when it dispatches. */
165
+ target?: string;
166
+ /** Node id of that target, when it resolves. */
167
+ targetNode?: string;
168
+ /** JSON Pointer to this call's argument map, when the slot declares one. */
169
+ inputs?: string;
170
+ /** The values a matcher-role field holds (`{path: "/orders", method: "POST"}`)
171
+ * — what identifies an entry to a reader, and what its content key is
172
+ * derived from. Entry rows only. */
173
+ match?: Record<string, unknown>;
174
+ /**
175
+ * What this row IS, in the grammar's own words — `invoke`, `if/then/else`,
176
+ * `while/do`, `switch/cases/default`, `try/catch/finally`, `throw`, `value`.
177
+ *
178
+ * Without it every statement in a body reads alike: a loop and a dispatch are
179
+ * both a name and an arrow, so a reader has to open the source to find out
180
+ * which is which. Read off the branch the step matches, so a kind declaring a
181
+ * body of its own is described in the words its author chose.
182
+ */
183
+ variant?: string;
184
+ /** The branch's title as its author wrote it — a label to render, never to
185
+ * parse. See `StepGraphNode.variantLabel`. */
186
+ variantLabel?: string;
187
+ /**
188
+ * The expression deciding whether or how this row runs, as written — an
189
+ * `if:`, a `while:`, a `switch:`, or a dispatch's `when:` guard.
190
+ *
191
+ * A step drawn without it says it is conditional and not on what, which for a
192
+ * loop is the whole behaviour.
193
+ */
194
+ predicate?: string;
195
+ /** This row declares an error branch — a field the kind annotated
196
+ * `x-telo-error-context`, which is where a raised code is discharged. Found
197
+ * by the annotation, so a third-party composer's `catches:` is seen too. */
198
+ catches?: boolean;
199
+ /**
200
+ * Where this row's call is WRITTEN, and what may fill it.
201
+ *
202
+ * A row is the dispatch site a reader manipulates — a step's `invoke:`, a
203
+ * route's `handler:`, a boot target — and until now the site was recoverable
204
+ * only from an edge, so a row dispatching to nothing yet had no address at
205
+ * all. That is exactly the row an editor has something to offer at: it is
206
+ * where a reference is written, and where a new resource would be wired in.
207
+ *
208
+ * Absent for a row that dispatches nothing by grammar (a pure `value:` step)
209
+ * and for a declaration row, which IS the thing dispatched to.
210
+ */
211
+ dispatch?: {
212
+ path: string;
213
+ refs: string[];
214
+ /** The slot holds a DECLARATION written at the site rather than a reference
215
+ * to one elsewhere. A consumer offers different things at the two: nothing
216
+ * can be wired into an occupied declaration without destroying it, and a
217
+ * declaration is the one thing that can be given a name of its own. */
218
+ inline?: boolean;
219
+ /**
220
+ * The row's OTHER sites — the same call, written a different way, under a
221
+ * different constraint.
222
+ *
223
+ * A boot target is the case that forced it: the entry takes a bare
224
+ * `!ref` to a `Telo.Runnable | Telo.Service`, and it takes an invoke step
225
+ * whose `invoke:` takes any `Telo.Executable`. Reporting only the first made
226
+ * every `Telo.Invocable` in the application unbootable from the editor —
227
+ * legal in the manifest, and offered nowhere, since a slot with nothing to
228
+ * put in it reads as an empty module rather than as a missing site.
229
+ *
230
+ * Primary first, and a site is listed once per CONSTRAINT: a boot target's
231
+ * `ref:` accepts exactly what its bare form does, so the two are one site
232
+ * and the bare spelling wins. Which spelling to write is a choice a reader
233
+ * should not have to make, and the constraint is the only thing that
234
+ * changes what may be written at all.
235
+ */
236
+ alternatives?: { path: string; refs: string[] }[];
237
+ };
238
+ /** `inline` rows: the kind the declaration written at this site names. A
239
+ * declaration is not a reference — there is nothing elsewhere to point at,
240
+ * which is the whole reason the row has to carry its own identity. */
241
+ declares?: string;
242
+ /** That kind resolved to no definition. */
243
+ unknownKind?: boolean;
244
+ }
245
+
246
+ /** A resource, the module root, or a declaration owned by either. */
247
+ export interface GraphNode {
248
+ /** `<kind>\0<name>` for a module-level resource — the call graph's own id, so
249
+ * a consumer holding one can address the other. */
250
+ id: string;
251
+ kind: string;
252
+ name: string;
253
+ /** Declared capability, absent when the kind does not resolve — an unresolved
254
+ * import, a kind with no definition. A view must render it as unknown rather
255
+ * than guessing a placement it would have to take back. */
256
+ capability?: string;
257
+ /**
258
+ * `<module>.<Kind>` — what `kind` NAMES, resolved.
259
+ *
260
+ * `kind` is the string the author wrote, and it is written in the DECLARING
261
+ * module's alias scope: a library declares its own instances as
262
+ * `kind: Self.WriteLine`, and `Self` means that library. Carried into a
263
+ * flattened application the spelling survives and resolves to nothing there,
264
+ * so every consumer joining on a kind — does this slot accept it, which
265
+ * instances does this kind have, what schema does the form use — silently
266
+ * missed a whole imported library.
267
+ *
268
+ * Absent when the kind is already canonical, and when it resolves to nothing
269
+ * (which `unknownKind` says).
270
+ */
271
+ canonicalKind?: string;
272
+ /** The kind resolved to no definition at all. */
273
+ unknownKind?: boolean;
274
+ ownership: NodeOwnership;
275
+ /** Node that owns this declaration — set for `inline` and `scoped`. */
276
+ owner?: string;
277
+ /** Site on the owner that declares it (`/with`, `mounts[0].mount`). */
278
+ ownerSite?: string;
279
+ /** Module that declared it, when stamped. */
280
+ module?: string;
281
+ /** True when the declaring module is not the entry module — an instance
282
+ * reached across an import boundary. */
283
+ external?: boolean;
284
+ /** Import alias the entry module reaches it under, when it is external and
285
+ * one alias points at its module. What a boundary box is labelled by, and
286
+ * what a reference to it is written with. */
287
+ alias?: string;
288
+ ports: GraphPort[];
289
+ rows: GraphRow[];
290
+ /**
291
+ * The ordered arrays this kind can hold rows in, whether or not any exist.
292
+ *
293
+ * Declared rather than observed, for the same reason a port is: a server with
294
+ * no mounts still HAS mounts, and a canvas that lists only what is there
295
+ * offers no way to add the first one. Each is a field name plus what its rows
296
+ * would be.
297
+ */
298
+ rowArrays: { field: string; kind: RowKind }[];
299
+ /** What invoking this can raise, resolved along its own call graph — the
300
+ * error contract a caller has to render or let escape. `unbounded` means the
301
+ * union could not be closed statically, so a catch-all is required. */
302
+ throws?: { codes: string[]; unbounded: boolean };
303
+ /** The module root, which owns `targets` and the module's own config. */
304
+ root?: boolean;
305
+ }
306
+
307
+ /** A reference site, classed. */
308
+ export interface GraphEdge {
309
+ /** Stable within the graph: source, slot and site. */
310
+ id: string;
311
+ /** Node id of the declaring resource — never a step, since a step is a ROW of
312
+ * its owner here rather than a node. `row` says which row declared it. */
313
+ from: string;
314
+ /** Node id of the target, absent when the name resolves to nothing. */
315
+ to?: string;
316
+ /** The referenced name as written, always present — a `!ref` to a name that
317
+ * does not exist is a real edge some other pass reports, and dropping it
318
+ * would make the graph disagree with the manifest about what was written. */
319
+ toName: string;
320
+ class: EdgeClass;
321
+ /** The declared uses at this site, unreduced. */
322
+ use: RefUse[];
323
+ /** Field-map path of the slot — part of the edge's identity, so two slots
324
+ * naming one target are two edges. */
325
+ slot: string;
326
+ /** Concrete path of the site. */
327
+ path: string;
328
+ /** Row this edge leaves from, when a row declares it. */
329
+ row?: string;
330
+ /** JSON Pointer to this call's argument map, when declared. */
331
+ inputs?: string;
332
+ /** The edge is a boot target of the module root: ordered, and the reason the
333
+ * target runs at all. */
334
+ boot?: boolean;
335
+ /** The target is declared inside the source's own scope. */
336
+ scoped?: boolean;
337
+ /** Data edges only: the access chain as written (`resources.db.status.port`),
338
+ * so a reader is told WHAT is read rather than only that something is. */
339
+ read?: string;
340
+ }
341
+
342
+ /**
343
+ * A genuine containment: a set of nodes something else encloses.
344
+ *
345
+ * Reference reachability is NOT containment — that mistake is what drew a mount
346
+ * as a child of its server while the slot said `dependency`. The three that ARE:
347
+ * an **inline** declaration and a **scope**'s resources exist nowhere but their
348
+ * owner's YAML, and a **zone** is a region of execution every dispatch inside it
349
+ * runs within.
350
+ */
351
+ export interface GraphRegion {
352
+ id: string;
353
+ kind: "inline" | "scope" | "zone";
354
+ /** Node whose declaration encloses the members. */
355
+ owner: string;
356
+ /** Site on the owner (`/with`, `invoke`, `steps`). */
357
+ site: string;
358
+ /** Node ids inside. */
359
+ members: string[];
360
+ /** Zone regions only: what the region GUARANTEES about its contents, as the
361
+ * declaring kind wrote it — the attribute name mapped to the author's
362
+ * reason, which a consumer quotes rather than paraphrases. */
363
+ attributes?: Readonly<Record<string, string>>;
364
+ /** Zone regions only: dispatches inside the region the zone does NOT extend
365
+ * through — a detached call, an inbound trigger. Recorded because the site is
366
+ * inside the region even though its target is not. */
367
+ boundaries?: { from: string; toName: string; escaping: string[] }[];
368
+ }
369
+
370
+ /**
371
+ * A kind declaration — the second plane.
372
+ *
373
+ * Kept apart from the instance nodes rather than mixed in: a `Telo.Definition`
374
+ * is a TYPE, and drawing it among the instances would put things that exist at
375
+ * runtime and things that do not on one surface with nothing separating them.
376
+ * A module that declares only kinds has this plane and no other, which is why
377
+ * it is a first-class list rather than a flag on a node.
378
+ */
379
+ export interface GraphKind {
380
+ /** Canonical `<module>.<Name>` — what a `kind:` resolves to. */
381
+ id: string;
382
+ name: string;
383
+ module?: string;
384
+ /** Non-instantiable: the contract has no default implementation. */
385
+ abstract: boolean;
386
+ capability?: string;
387
+ /** Canonical id of the kind this one specializes, when it resolves. */
388
+ extendsId?: string;
389
+ /** The `extends` target as WRITTEN, kept when it resolves to nothing — an
390
+ * unresolved parent is a fact about the manifest, not a reason to draw the
391
+ * kind as having none. */
392
+ extendsName?: string;
393
+ /** Ids of the instance nodes declared of this kind — the join between the
394
+ * two planes. */
395
+ instances: string[];
396
+ /** Declares a body of its own (`resources:` / `invoke:` / `run:` / `provide:`)
397
+ * rather than naming a controller — the kind's interior. */
398
+ template: boolean;
399
+ /** Declared by the entry module rather than reached through an import. */
400
+ own: boolean;
401
+ /** Listed in the entry module's `exports.kinds`, so an importer may construct
402
+ * one. Undefined for a kind this module did not declare, whose gate is its
403
+ * own library's to state. */
404
+ exported?: boolean;
405
+ }
406
+
407
+ export interface ModuleGraph {
408
+ /** The module root, when one was supplied. */
409
+ root?: GraphNode;
410
+ nodes: GraphNode[];
411
+ edges: GraphEdge[];
412
+ regions: GraphRegion[];
413
+ /** The kind plane — every kind declaration in scope. */
414
+ kinds: GraphKind[];
415
+ nodeById(id: string): GraphNode | undefined;
416
+ edgesFrom(id: string): GraphEdge[];
417
+ edgesTo(id: string): GraphEdge[];
418
+ }
419
+
420
+ /**
421
+ * A hold whose target is ambient infrastructure — the collapse candidate.
422
+ *
423
+ * Stated here rather than in the view because it is the rule the plan fixes,
424
+ * and two hosts applying it differently would disagree about which edges exist:
425
+ * a hold into a shared connection or store is fan-in that swamps a layout and
426
+ * carries no structure, while a hold BETWEEN working resources is the
427
+ * application's spine — a server holding its mounts — and demoting the second
428
+ * with the first is exactly the mistake this replaces.
429
+ */
430
+ /**
431
+ * Is anything reaching this declaration at all?
432
+ *
433
+ * "Declared, referenced by nothing, in no `targets`" — the resource a reader
434
+ * cannot otherwise tell apart from a wired one, since a manifest states no
435
+ * difference between the two. Every incoming edge counts, not only flow: a
436
+ * connection is HELD rather than called, and reading it as unwired would mark
437
+ * every provider in the module. An owned declaration is reached by its owner,
438
+ * and the root is what reaches everything else.
439
+ *
440
+ * A declaration this module did not write is NEVER unwired, however little it
441
+ * is used here. An imported library exports what it exports, and the flatten
442
+ * forwards all of it; "nothing references this" would be a true sentence about
443
+ * an unused export and a useless one, since the reader cannot act on it — the
444
+ * declaration is not theirs to remove.
445
+ */
446
+ export function isUnwired(node: GraphNode, graph: ModuleGraph): boolean {
447
+ if (node.root || node.external) return false;
448
+ if (node.ownership === "inline" || node.ownership === "scoped") return false;
449
+ return graph.edgesTo(node.id).length === 0;
450
+ }
451
+
452
+ export function isAmbientHold(edge: GraphEdge, graph: ModuleGraph): boolean {
453
+ if (edge.class !== "holds" || !edge.to) return false;
454
+ const target = graph.nodeById(edge.to);
455
+ return isAmbientCapability(target?.capability);
456
+ }
457
+
458
+ /**
459
+ * Capabilities whose resources are AMBIENT: held and read, never run, and never
460
+ * drawn as the target of a line.
461
+ *
462
+ * Exported because the view partitions on the same fact — which boxes go off
463
+ * the canvas into the drawer — and two spellings of it is how a host ends up
464
+ * collapsing a hold the other still draws an edge for.
465
+ */
466
+ export const AMBIENT_CAPABILITIES: ReadonlySet<string> = new Set([
467
+ "Telo.Provider",
468
+ "Telo.Type",
469
+ ]);
470
+
471
+ /** Is this an ambient declaration — held and read rather than run? */
472
+ export function isAmbientCapability(capability: string | undefined): boolean {
473
+ return !!capability && AMBIENT_CAPABILITIES.has(capability);
474
+ }
475
+
476
+ /** Uses that transfer control, so the site is drawn as flow. */
477
+ const FLOW_USES: ReadonlySet<string> = new Set([
478
+ "call",
479
+ "detached",
480
+ "trigger.inbound",
481
+ "trigger.consumer",
482
+ ]);
483
+
484
+ /**
485
+ * The class a site is drawn as.
486
+ *
487
+ * A slot declaring NO use reads as flow, the same conservative direction the
488
+ * call graph takes: the cost of a false "control reaches here" is an edge drawn
489
+ * more prominently than it deserved, while the cost of a false "it never does"
490
+ * is a call the picture denies exists.
491
+ */
492
+ export function edgeClassOf(use: readonly RefUse[]): EdgeClass {
493
+ if (use.length === 0) return "flow";
494
+ if (use.some((u) => FLOW_USES.has(u))) return "flow";
495
+ if (use.includes("dependency" as RefUse)) return "holds";
496
+ return "shape";
497
+ }
498
+
499
+ /** What the projection needs from a registry, as a structural contract — so it
500
+ * folds over stubs in tests and over the real registry in a host, and so this
501
+ * module imports no registry class. */
502
+ export interface ModuleGraphDeps {
503
+ /** Every reference slot a resource's kind declares, filled or not. */
504
+ refFields(resource: ResourceManifest): {
505
+ path: string;
506
+ isArray: boolean;
507
+ refs: string[];
508
+ capabilities: string[];
509
+ }[];
510
+ /** The resource's definition, resolved in its declaring module's scope. */
511
+ definition(kind: string, module?: string): ResourceDefinition | undefined;
512
+ /** What invoking this resource can raise. Optional: a host without the
513
+ * resolver gets nodes with no error contract rather than a wrong one. */
514
+ throwsOf?(manifest: ResourceManifest): { codes: string[]; unbounded: boolean } | undefined;
515
+ /** Import aliases pointing at a module, so a reference written across the
516
+ * boundary as `!ref <Alias>.<name>` resolves to the instance it names. The
517
+ * call graph resolves bare names only — correct for a name declared here,
518
+ * and the reason every cross-module reference otherwise reads as dangling. */
519
+ aliasesForModule(module: string): string[];
520
+ }
521
+
522
+ export interface BuildModuleGraphOptions {
523
+ /** The module doc (`Telo.Application` / `Telo.Library`), which is not a
524
+ * resource but owns `targets` and is the boot root. */
525
+ root?: ResourceManifest;
526
+ /** Module name of the entry module, so an instance declared elsewhere is
527
+ * marked external rather than being told apart by a heuristic. */
528
+ entryModule?: string;
529
+ }
530
+
531
+ /**
532
+ * Documents that declare a TYPE or a module rather than an instance.
533
+ *
534
+ * The flattened analysis carries every imported library's definitions beside
535
+ * its instances, so without this the instance plane fills with the abstracts a
536
+ * dependency happens to declare (`Sql.Connection`, `Codec.Encoder`) — boxes for
537
+ * things that never exist at runtime, drawn among the things that do. They are
538
+ * the kind plane's, which is a separate surface. The module docs are here too:
539
+ * the entry module's is minted as the ROOT, and an imported library's is not an
540
+ * instance at all.
541
+ */
542
+ const DECLARATION_KINDS: ReadonlySet<string> = new Set([
543
+ "Telo.Definition",
544
+ "Telo.Abstract",
545
+ "Telo.Import",
546
+ "Telo.Application",
547
+ "Telo.Library",
548
+ ]);
549
+
550
+ const moduleOf = (manifest: ResourceManifest): string | undefined =>
551
+ (manifest.metadata as { module?: string } | undefined)?.module;
552
+
553
+ /** The canonical id of a resolved kind definition — where it was declared plus
554
+ * what it is called there, which is the one spelling every module agrees on. */
555
+ const canonicalKindOf = (definition: ResourceDefinition | undefined): string | undefined => {
556
+ const metadata = definition?.metadata as { module?: string; name?: string } | undefined;
557
+ if (!metadata?.name) return undefined;
558
+ return metadata.module ? `${metadata.module}.${metadata.name}` : metadata.name;
559
+ };
560
+
561
+ const originOf = (
562
+ manifest: ResourceManifest,
563
+ ): { parentKind: string; parentName: string; pathFromParent: string } | undefined =>
564
+ (
565
+ manifest.metadata as
566
+ | { xTeloOrigin?: { parentKind: string; parentName: string; pathFromParent: string } }
567
+ | undefined
568
+ )?.xTeloOrigin;
569
+
570
+ const isForwardedExport = (manifest: ResourceManifest): boolean =>
571
+ (manifest.metadata as { forwardedExport?: boolean } | undefined)?.forwardedExport === true;
572
+
573
+ const isInjected = (manifest: ResourceManifest): boolean =>
574
+ (manifest.metadata as Record<string, unknown> | undefined)?.["xTeloInjected"] === true;
575
+
576
+ /**
577
+ * A short, stable key over a value's shape.
578
+ *
579
+ * FNV-1a over canonical JSON: what is wanted is that the same written entry
580
+ * keeps the same identity when a sibling is inserted above it, which a hash of
581
+ * the entry's own content gives and an index cannot. Collisions are resolved by
582
+ * declaration order at the call site, so two byte-identical rows stay
583
+ * distinguishable without either one's identity depending on the other's
584
+ * position.
585
+ */
586
+ export function contentKey(value: unknown): string {
587
+ const json = canonicalJson(value);
588
+ let hash = 0x811c9dc5;
589
+ for (let i = 0; i < json.length; i++) {
590
+ hash ^= json.charCodeAt(i);
591
+ hash = Math.imul(hash, 0x01000193) >>> 0;
592
+ }
593
+ return hash.toString(36);
594
+ }
595
+
596
+ /** Mints ids that are unique without being positional: the name where one
597
+ * exists, a content key where none does, and a `~n` suffix only when two
598
+ * siblings are genuinely indistinguishable. */
599
+ class IdMinter {
600
+ private readonly used = new Set<string>();
601
+
602
+ mint(base: string): string {
603
+ if (!this.used.has(base)) {
604
+ this.used.add(base);
605
+ return base;
606
+ }
607
+ for (let n = 2; ; n++) {
608
+ const candidate = `${base}~${n}`;
609
+ if (!this.used.has(candidate)) {
610
+ this.used.add(candidate);
611
+ return candidate;
612
+ }
613
+ }
614
+ }
615
+ }
616
+
617
+ /** The schema node at a field-map path, following `[]` into `items` and `{}`
618
+ * into `additionalProperties`, resolving local `$ref`s along the way. */
619
+ function schemaAt(
620
+ rootSchema: Record<string, any> | undefined,
621
+ slotPath: string,
622
+ ): Record<string, any> | undefined {
623
+ if (!rootSchema) return undefined;
624
+ let current: Record<string, any> | undefined = rootSchema;
625
+ for (const segment of slotPath.split(".")) {
626
+ if (!current) return undefined;
627
+ // A map's key step is its OWN segment (`columns.{}.type`), where an array's
628
+ // rides the field it belongs to (`mounts[].mount`). Reading only the suffix
629
+ // form walked into nothing at the first map, so every slot under one was
630
+ // left with no schema — and a slot with no schema declares no `use`, which
631
+ // classed a column's typed reference as a control transfer.
632
+ if (segment === "{}") {
633
+ current = resolveLocalRef(
634
+ current.additionalProperties as Record<string, any> | undefined,
635
+ rootSchema,
636
+ );
637
+ continue;
638
+ }
639
+ const bare = segment.replace(/(\[\]|\{\})+$/g, "");
640
+ let next: Record<string, any> | undefined = propertySchemas(current).find(
641
+ ([k]) => k === bare,
642
+ )?.[1];
643
+ for (const marker of segment.slice(bare.length).match(/\[\]|\{\}/g) ?? []) {
644
+ next = resolveLocalRef(
645
+ marker === "[]"
646
+ ? (next?.items as Record<string, any> | undefined)
647
+ : (next?.additionalProperties as Record<string, any> | undefined),
648
+ rootSchema,
649
+ );
650
+ if (!next || typeof next !== "object") return undefined;
651
+ }
652
+ current = resolveLocalRef(next, rootSchema);
653
+ }
654
+ return current;
655
+ }
656
+
657
+ /** Every array field of a kind carrying `x-telo-topology-role: entries`, with
658
+ * the roles declared inside its items — `matcher` fields identify an entry to
659
+ * a reader, `handler` fields say what it dispatches to. No kind is named: a
660
+ * third-party router declaring the same three tokens renders identically. */
661
+ interface EntryListSpec {
662
+ field: string;
663
+ matchers: string[];
664
+ handlers: string[];
665
+ /** Sub-fields annotated `x-telo-error-context` — where an entry discharges a
666
+ * raised code. */
667
+ errorBranches: string[];
668
+ }
669
+
670
+ /**
671
+ * Does this field hold the branch that DISCHARGES a raised error?
672
+ *
673
+ * Two annotations mark one, from two layers, and both are read: the shared CEL
674
+ * one (`x-telo-error-context`, which types the `error` variable inside a
675
+ * `catch:`) and the dispatch outcome vocabulary (`x-telo-outcome-list: catches`,
676
+ * which an HTTP-style router uses to render a code as a response). Neither is a
677
+ * field NAME, so a third-party composer spelling its branch differently is seen
678
+ * as long as it annotates it; recognizing only one would silently mark every
679
+ * route in the standard library as handling nothing.
680
+ */
681
+ function isErrorBranch(schema: Record<string, any> | undefined): boolean {
682
+ return (
683
+ schema?.["x-telo-error-context"] !== undefined ||
684
+ schema?.["x-telo-outcome-list"] === "catches"
685
+ );
686
+ }
687
+
688
+ function entryListsOf(rootSchema: Record<string, any> | undefined): EntryListSpec[] {
689
+ if (!rootSchema) return [];
690
+ const out: EntryListSpec[] = [];
691
+ for (const [key, propSchema] of propertySchemas(rootSchema)) {
692
+ if (propSchema?.["x-telo-topology-role"] !== "entries") continue;
693
+ const items = resolveLocalRef(propSchema.items as Record<string, any>, rootSchema);
694
+ const matchers: string[] = [];
695
+ const handlers: string[] = [];
696
+ const errorBranches: string[] = [];
697
+ for (const [subKey, subSchema] of propertySchemas(items ?? {})) {
698
+ const role = subSchema?.["x-telo-topology-role"];
699
+ if (role === "matcher") matchers.push(subKey);
700
+ else if (role === "handler") handlers.push(subKey);
701
+ if (isErrorBranch(subSchema)) errorBranches.push(subKey);
702
+ }
703
+ out.push({ field: key, matchers, handlers, errorBranches });
704
+ }
705
+ return out;
706
+ }
707
+
708
+ /** A value written AT a ref slot that declares a resource rather than naming
709
+ * one — `{kind, …config}` with no `name`. */
710
+ function isInlineDeclaration(value: unknown): boolean {
711
+ if (isRefSentinel(value) || !value || typeof value !== "object" || Array.isArray(value)) {
712
+ return false;
713
+ }
714
+ // The shape test itself is the field map's — one reader for "is this a
715
+ // declaration rather than a reference", since the extraction pass keys on the
716
+ // same answer and a second opinion here would decide differently the day the
717
+ // form gains a key.
718
+ return isInlineResource(value as Record<string, unknown>);
719
+ }
720
+
721
+ /** The referenced name a ref value carries, across both written forms: an
722
+ * unresolved `!ref <name>` sentinel and the `{kind, name}` object
723
+ * `resolveRefSentinels` rewrites it into. */
724
+ function refName(value: unknown): string | undefined {
725
+ if (isRefSentinel(value)) return value.source;
726
+ if (!value || typeof value !== "object") return undefined;
727
+ const name = (value as Record<string, unknown>).name;
728
+ return typeof name === "string" ? name : undefined;
729
+ }
730
+
731
+ /**
732
+ * Fold a manifest set into the module graph.
733
+ *
734
+ * The call graph supplies what calls what — including the scoped nodes and step
735
+ * bodies it already discovers — and this pass adds what a picture needs and a
736
+ * call graph has no reason to carry: declared-but-empty ports, ownership,
737
+ * ordered rows, region membership, and the reduction of six uses to three
738
+ * classes.
739
+ */
740
+ export function buildModuleGraph(
741
+ resources: ResourceManifest[],
742
+ callGraph: CallGraph,
743
+ deps: ModuleGraphDeps,
744
+ options: BuildModuleGraphOptions = {},
745
+ ): ModuleGraph {
746
+ const nodes: GraphNode[] = [];
747
+ const edges: GraphEdge[] = [];
748
+ const regions: GraphRegion[] = [];
749
+ const byId = new Map<string, GraphNode>();
750
+ const rowIdByPath = new Map<string, string>();
751
+ /** References found inside inline declarations, resolved once every node
752
+ * exists — a declaration may name a resource declared later in the file. */
753
+ const inlineEdgeSeeds = new Map<string, InlineEdgeSeed[]>();
754
+
755
+ const add = (node: GraphNode): GraphNode => {
756
+ nodes.push(node);
757
+ byId.set(node.id, node);
758
+ return node;
759
+ };
760
+
761
+ // --- the module root -------------------------------------------------------
762
+ // Not a resource: it owns `targets` and the module's own configuration, and
763
+ // the call graph deliberately skips it. Minting it here is what makes a boot
764
+ // target an ordinary edge rather than a fact a consumer has to fetch from
765
+ // somewhere else.
766
+ let root: GraphNode | undefined;
767
+ if (options.root) {
768
+ const name = (options.root.metadata?.name as string | undefined) ?? "";
769
+ const module = moduleOf(options.root);
770
+ root = add({
771
+ id: resourceId(options.root.kind as string, name),
772
+ kind: options.root.kind as string,
773
+ name,
774
+ ownership: "root",
775
+ ...(module ? { module } : {}),
776
+ ports: [],
777
+ rows: [],
778
+ // Boot targets are an ordered list the root always has, empty or not.
779
+ rowArrays: [{ field: "targets", kind: "target" }],
780
+ root: true,
781
+ });
782
+ }
783
+
784
+ // --- resource nodes --------------------------------------------------------
785
+ // Minted from the MANIFEST LIST, not from the call graph's node map.
786
+ //
787
+ // The call graph keys a resource by `(kind, name)`, which is unique within one
788
+ // module and not across a flattened set: two libraries each exporting an
789
+ // `Http.Api` named `routes` collapse onto one node there, and a picture built
790
+ // from that map draws one box for two declarations. Minting here from the
791
+ // manifests keeps both, qualified by their declaring module. What is still the
792
+ // call graph's — steps and edges — is translated through `projectedId`, and
793
+ // the collapsed twin's own edges are missing from it; its ports and rows are
794
+ // read from its manifest here, so the box is drawn and wired correctly and
795
+ // only the edges the call graph lost are absent.
796
+ // One id scheme, the call graph's — a resource name is module-scoped, so the
797
+ // module is part of the identity wherever one is stamped. Stating it here a
798
+ // second way is how the two halves would disagree about which box an edge
799
+ // arrives at.
800
+ const idOf = (manifest: ResourceManifest): string => nodeIdFor(manifest);
801
+
802
+ const manifestById = new Map<string, ResourceManifest>();
803
+ for (const manifest of resources) {
804
+ const name = manifest.metadata?.name;
805
+ if (typeof name !== "string" || !manifest.kind || DECLARATION_KINDS.has(manifest.kind)) continue;
806
+ if (root && manifest === options.root) continue;
807
+ const id = idOf(manifest);
808
+ if (byId.has(id)) continue;
809
+ add(projectResource(id, manifest, deps, options));
810
+ manifestById.set(id, manifest);
811
+ }
812
+
813
+ // Call-graph node id → the node it designates here, so a step or an edge the
814
+ // call graph produced lands on the box this pass minted.
815
+ const projectedId = new Map<string, string>();
816
+ const scopedIdByKey = new Map<string, string>();
817
+ const scopedByOwner = new Map<string, Map<string, string[]>>();
818
+ for (const graphNode of callGraph.nodes.values()) {
819
+ if (graphNode.type !== "resource") continue;
820
+ if (DECLARATION_KINDS.has(graphNode.kind)) continue;
821
+ if (graphNode.scoped) {
822
+ // A `with:`-scoped resource is declared inside another's body, so it is in
823
+ // no manifest list of its own — the call graph is where it exists.
824
+ //
825
+ // One declaration, one box: the call graph keys a scoped node by the
826
+ // scope POINTER, and `x-telo-scope` lists every region a scoped name
827
+ // resolves in (`Run.Sequence` names both `/steps` and `/targets`), so one
828
+ // `with:` entry arrives once per pointer. The pointers say where the name
829
+ // is visible, not where the resource was declared.
830
+ const key = `${graphNode.scopeOwner ?? ""}#scope#${resourceId(graphNode.kind, graphNode.name)}`;
831
+ const already = scopedIdByKey.get(key);
832
+ if (already) {
833
+ projectedId.set(graphNode.id, already);
834
+ continue;
835
+ }
836
+ const node = add(projectResource(graphNode.id, graphNode.manifest, deps, options));
837
+ scopedIdByKey.set(key, node.id);
838
+ node.ownership = "scoped";
839
+ if (graphNode.scopeOwner) node.owner = graphNode.scopeOwner;
840
+ if (graphNode.scopeSite) node.ownerSite = graphNode.scopeSite;
841
+ manifestById.set(node.id, graphNode.manifest);
842
+ projectedId.set(graphNode.id, node.id);
843
+ const owner = graphNode.scopeOwner;
844
+ if (owner) {
845
+ const sites = scopedByOwner.get(owner) ?? new Map<string, string[]>();
846
+ const site = graphNode.scopeSite ?? "";
847
+ sites.set(site, [...(sites.get(site) ?? []), node.id]);
848
+ scopedByOwner.set(owner, sites);
849
+ }
850
+ continue;
851
+ }
852
+ projectedId.set(graphNode.id, idOf(graphNode.manifest));
853
+ }
854
+ // A scoped node's owner is a call-graph id; translate it now that every
855
+ // resource node has one.
856
+ for (const node of nodes) {
857
+ if (node.ownership === "scoped" && node.owner) {
858
+ node.owner = projectedId.get(node.owner) ?? node.owner;
859
+ }
860
+ }
861
+ for (const [owner, sites] of [...scopedByOwner]) {
862
+ const translated = projectedId.get(owner);
863
+ if (translated && translated !== owner) {
864
+ scopedByOwner.delete(owner);
865
+ scopedByOwner.set(translated, sites);
866
+ }
867
+ }
868
+
869
+ // Inline children: the extraction stamps the parent and the path it was
870
+ // written at, so ownership is read off the declaration rather than guessed
871
+ // from a name pattern. The stamp names the parent by `(kind, name)`, so it is
872
+ // translated through the same table a call-graph id is.
873
+ const inlineByOwner = new Map<string, Map<string, string[]>>();
874
+ for (const node of nodes) {
875
+ if (node.ownership !== "inline" || !node.owner) continue;
876
+ node.owner = projectedId.get(node.owner) ?? node.owner;
877
+ const sites = inlineByOwner.get(node.owner) ?? new Map<string, string[]>();
878
+ const site = node.ownerSite ?? "";
879
+ sites.set(site, [...(sites.get(site) ?? []), node.id]);
880
+ inlineByOwner.set(node.owner, sites);
881
+ }
882
+
883
+ for (const [owner, sites] of inlineByOwner) {
884
+ for (const [site, members] of sites) {
885
+ regions.push({ id: `${owner}#inline:${site}`, kind: "inline", owner, site, members });
886
+ }
887
+ }
888
+ for (const [owner, sites] of scopedByOwner) {
889
+ for (const [site, members] of sites) {
890
+ regions.push({ id: `${owner}#scope:${site}`, kind: "scope", owner, site, members });
891
+ }
892
+ }
893
+
894
+ // Execution zones: a region every dispatch inside runs within. Read from the
895
+ // containment walk rather than re-derived, so what the editor draws and what
896
+ // `telo check` enforces are the same region — including one declaring no
897
+ // attributes, which is still a zone.
898
+ for (const zone of findZoneProviders(callGraph, (kind, module) => deps.definition(kind, module))) {
899
+ const owner = projectedId.get(zone.provider.id) ?? zone.provider.id;
900
+ if (!byId.has(owner)) continue;
901
+ const members: string[] = [];
902
+ for (const [id, contained] of zone.contents) {
903
+ // A step is a ROW of its owner here, so a zone reaching one is a zone
904
+ // reaching the resource whose body declares it.
905
+ const memberId =
906
+ contained.node.type === "step"
907
+ ? (projectedId.get(contained.node.owner) ?? contained.node.owner)
908
+ : (projectedId.get(id) ?? id);
909
+ if (memberId !== owner && byId.has(memberId) && !members.includes(memberId)) {
910
+ members.push(memberId);
911
+ }
912
+ }
913
+ const boundaries = zone.boundaries.map((b) => ({
914
+ from: projectedId.get(b.from.id) ?? b.from.id,
915
+ toName: b.edge.toName,
916
+ escaping: b.escaping,
917
+ }));
918
+ regions.push({
919
+ id: `${owner}#zone:${zone.slot}`,
920
+ kind: "zone",
921
+ owner,
922
+ site: zone.slot,
923
+ members,
924
+ attributes: zone.attributes,
925
+ ...(boundaries.length > 0 ? { boundaries } : {}),
926
+ });
927
+ }
928
+
929
+ // --- rows ------------------------------------------------------------------
930
+ // Steps come from the call graph, which owns the analyzer's only step-array
931
+ // recursion; entry lists and boot targets are read here, since neither is a
932
+ // step body and neither has a node of its own.
933
+ const callGraphIdByNode = invertProjectedIds(projectedId);
934
+ const callGraphIdOf = (nodeId: string): string => callGraphIdByNode.get(nodeId) ?? nodeId;
935
+
936
+ for (const node of nodes) {
937
+ const manifest = node.root ? options.root : manifestById.get(node.id);
938
+ if (!manifest) continue;
939
+ const definition = deps.definition(node.kind, node.module);
940
+ const schema = definition?.schema as Record<string, any> | undefined;
941
+ // The root's rows are its BOOT LIST and nothing else. `targets` carries the
942
+ // step grammar, so the call graph mints a step node for every entry that is
943
+ // not a bare `!ref` — and `targetRows` already renders every shape an entry
944
+ // takes, so collecting both listed an inline target twice.
945
+ node.rows = node.root
946
+ ? targetRows(node, manifest, rowIdByPath)
947
+ : [
948
+ ...stepRows(node, callGraph, callGraphIdOf(node.id), rowIdByPath),
949
+ ...entryRows(node, manifest, schema, rowIdByPath),
950
+ ];
951
+ if (!node.root) node.rowArrays = declaredRowArrays(schema);
952
+ }
953
+
954
+ // --- ports and edges -------------------------------------------------------
955
+ for (const node of nodes) {
956
+ const manifest = node.root ? options.root : manifestById.get(node.id);
957
+ if (!manifest) continue;
958
+ const definition = deps.definition(node.kind, node.module);
959
+ const schema = definition?.schema as Record<string, any> | undefined;
960
+ // A slot whose occupancy is DRAWN AS ROWS is not also a port: a route, a
961
+ // boot target and a step are manipulated as the ordered thing they are, and
962
+ // a second rendering of the same occupancy beside it is two controls for
963
+ // one fact. Read off the DECLARED arrays, not the rows: an empty `mounts`
964
+ // would otherwise be row-owned only once it had a mount in it, so a fresh
965
+ // server showed both a port and an add control for the same list.
966
+ const rowArrays = new Set(node.rowArrays.map((a) => a.field));
967
+ node.ports = buildPorts(manifest, deps, schema, rowArrays);
968
+ const throws = deps.throwsOf?.(manifest);
969
+ if (throws && (throws.codes.length > 0 || throws.unbounded)) node.throws = throws;
970
+ // A declaration written at a dispatch site hangs under the row that
971
+ // declares it — see `inlineRows`. After the ports, because a route's
972
+ // `handler:` is a port slot and its occupancy is what names the site; and
973
+ // woven rather than appended, so the body stays pre-order, which every
974
+ // consumer of `parent` relies on.
975
+ node.rows = weaveInlineRows(
976
+ node,
977
+ manifest,
978
+ callGraph,
979
+ callGraphIdOf(node.id),
980
+ deps,
981
+ rowIdByPath,
982
+ inlineEdgeSeeds,
983
+ );
984
+ }
985
+
986
+ // Alias-qualified names, so a reference across an import boundary resolves.
987
+ // The call graph matches bare names — right for a name declared here, and the
988
+ // reason `!ref Console.writeLine` reached this pass as a dangling edge.
989
+ // Every row is known by now, so the per-owner index the longest-prefix walk
990
+ // needs is built once rather than re-scanned per edge.
991
+ const rowsByOwner = rowsByOwnerOf(rowIdByPath);
992
+
993
+ const byQualifiedName = new Map<string, string>();
994
+ for (const node of nodes) {
995
+ if (!node.module) continue;
996
+ for (const alias of deps.aliasesForModule(node.module)) {
997
+ const key = `${alias}.${node.name}`;
998
+ if (!byQualifiedName.has(key)) byQualifiedName.set(key, node.id);
999
+ }
1000
+ }
1001
+
1002
+ // Edges come from the call graph — one per site, already resolved — re-keyed
1003
+ // onto the boxes a view draws: a step's edge is attributed to the resource
1004
+ // whose body declares it, with the row that declared it named, because a step
1005
+ // is a row here rather than a node of its own.
1006
+ for (const edge of callGraph.edges) {
1007
+ const projected = projectEdge(
1008
+ edge,
1009
+ callGraph,
1010
+ byId,
1011
+ rowIdByPath,
1012
+ rowsByOwner,
1013
+ byQualifiedName,
1014
+ projectedId,
1015
+ );
1016
+ if (!projected) continue;
1017
+ // A reference leaving the module root IS a boot target — the root has no
1018
+ // other slots — so the flag is stamped here rather than by a second pass
1019
+ // over `targets`, which emitted a duplicate edge for every one of them.
1020
+ if (root && projected.from === root.id) projected.boot = true;
1021
+ edges.push(projected);
1022
+ }
1023
+
1024
+ // Data edges: one resource reading another's published state in CEL. Parsed,
1025
+ // never scanned — `extractAccessChains` reads `resources.db.status.port` as a
1026
+ // chain and a name inside a string literal as nothing, which a token scan
1027
+ // cannot tell apart.
1028
+ // A bare name resolves in the module that WROTE it — the call graph's own
1029
+ // rule, shared rather than restated. Keeping a first-wins index here would
1030
+ // have put every inline declaration's reference and every CEL state read back
1031
+ // on whichever module happened to come first in the flattened list, which is
1032
+ // the collision module-scoped identity exists to prevent.
1033
+ const nodesByName = new Map<string, GraphNode[]>();
1034
+ for (const node of nodes) {
1035
+ if (node.root) continue;
1036
+ nodesByName.set(node.name, [...(nodesByName.get(node.name) ?? []), node]);
1037
+ }
1038
+ const resolveName = (name: string, fromModule: string | undefined): string | undefined =>
1039
+ resolveScopedName(nodesByName.get(name), (node) => node.module, fromModule)?.id;
1040
+
1041
+ // References written INSIDE a declaration. Resolved here rather than where
1042
+ // they were found, because a declaration may name a resource declared later
1043
+ // in the file — and against the same name index every other edge uses, so a
1044
+ // hold reached through an inline declaration counts exactly as one written at
1045
+ // a named resource's own slot.
1046
+ for (const [from, list] of inlineEdgeSeeds) {
1047
+ const fromModule = byId.get(from)?.module;
1048
+ for (const seed of list) {
1049
+ const to = resolveName(seed.toName, fromModule) ?? byQualifiedName.get(seed.toName);
1050
+ const edge: GraphEdge = {
1051
+ id: `${from}\0${seed.path}`,
1052
+ from,
1053
+ toName: seed.toName,
1054
+ class: edgeClassOf(seed.uses),
1055
+ use: seed.uses,
1056
+ slot: seed.slot,
1057
+ path: seed.path,
1058
+ row: seed.rowId,
1059
+ };
1060
+ if (to) edge.to = to;
1061
+ edges.push(edge);
1062
+ }
1063
+ }
1064
+
1065
+ for (const node of nodes) {
1066
+ const manifest = node.root ? options.root : manifestById.get(node.id);
1067
+ if (!manifest) continue;
1068
+ edges.push(...dataEdges(node, manifest, node.module, resolveName, rowIdByPath, rowsByOwner));
1069
+ }
1070
+
1071
+ // Where each row's call is WRITTEN, and what may fill it — see
1072
+ // `GraphRow.dispatch`. Three shapes, because the grammar has three: a step's
1073
+ // slot is declared on its item schema and reachable only through the step
1074
+ // walk; an entry's is a row-owned port of the array it sits in; a boot target
1075
+ // IS its own slot. All three are stated even when nothing fills them, since
1076
+ // an empty site is exactly the one an editor has something to offer at.
1077
+ for (const node of nodes) {
1078
+ const stepSlots = new Map<string, GraphRow["dispatch"]>();
1079
+ const stepSites = new Map<string, { path: string; refs: string[] }[]>();
1080
+ for (const step of callGraph.steps(callGraphIdOf(node.id))) {
1081
+ const first = step.refSlots?.[0];
1082
+ if (first) {
1083
+ stepSlots.set(step.path, {
1084
+ path: first.path,
1085
+ refs: first.kinds,
1086
+ ...(first.inline ? { inline: true } : {}),
1087
+ });
1088
+ }
1089
+ if (step.refSlots?.length) {
1090
+ stepSites.set(
1091
+ step.path,
1092
+ step.refSlots.map((slot) => ({ path: slot.path, refs: slot.kinds })),
1093
+ );
1094
+ }
1095
+ }
1096
+ // Whether a port-derived site holds a declaration, by its concrete path.
1097
+ const inlineAt = new Set(
1098
+ node.ports.flatMap((port) => port.slots.filter((s) => s.inline).map((s) => s.path)),
1099
+ );
1100
+ const rowOwnedPorts = node.ports.filter((port) => port.rowOwned);
1101
+ for (const row of node.rows) {
1102
+ if (row.kind === "step") {
1103
+ const slot = stepSlots.get(row.path);
1104
+ if (slot) {
1105
+ row.dispatch = withAlternatives(slot, stepSites.get(row.path) ?? []);
1106
+ }
1107
+ continue;
1108
+ }
1109
+ if (row.kind === "target") {
1110
+ const port = node.ports.find((p) => p.slot === `${row.array}[]`);
1111
+ if (port) {
1112
+ row.dispatch = withAlternatives(
1113
+ {
1114
+ path: row.path,
1115
+ refs: port.refs,
1116
+ ...(inlineAt.has(row.path) ? { inline: true } : {}),
1117
+ },
1118
+ // A boot target IS a step, and the step walk is what sees the sites
1119
+ // the entry's own grammar declares — the bare reference the port
1120
+ // reports is one spelling of one of them.
1121
+ stepSites.get(row.path) ?? [],
1122
+ );
1123
+ }
1124
+ continue;
1125
+ }
1126
+ if (row.kind !== "entry") continue;
1127
+ // `routes[].handler` → the handler of THIS route, whether or not one is
1128
+ // written: the port's own slots list only the routes that have one.
1129
+ const port = rowOwnedPorts.find((p) => containerArrayOf(p.slot) === row.array);
1130
+ if (port) {
1131
+ const path = `${row.path}.${port.slot.slice(port.slot.indexOf("[].") + 3)}`;
1132
+ row.dispatch = {
1133
+ path,
1134
+ refs: port.refs,
1135
+ ...(inlineAt.has(path) ? { inline: true } : {}),
1136
+ };
1137
+ }
1138
+ }
1139
+ }
1140
+
1141
+ // Back-fill what a row learns from the edge it declares: where its target
1142
+ // resolved, and where this call's arguments are written. Both are the edge's
1143
+ // to know — a row is read off the manifest, while `inputs` is a POINTER the
1144
+ // slot declares and the target is a name the graph resolved — so they are
1145
+ // stamped here rather than guessed twice.
1146
+ const rowById = new Map<string, GraphRow>();
1147
+ for (const node of nodes) for (const row of node.rows) rowById.set(row.id, row);
1148
+ for (const edge of edges) {
1149
+ const row = edge.row ? rowById.get(edge.row) : undefined;
1150
+ if (!row) continue;
1151
+ if (edge.to && row.targetNode === undefined) row.targetNode = edge.to;
1152
+ if (row.target === undefined) row.target = edge.toName;
1153
+ if (edge.inputs !== undefined && row.inputs === undefined) {
1154
+ // The pointer is relative to the object ENCLOSING the slot, which for a
1155
+ // step or an entry is the row itself.
1156
+ row.inputs = `${row.path}${edge.inputs.replace(/\//g, ".")}`;
1157
+ }
1158
+ }
1159
+
1160
+ const fromIndex = new Map<string, GraphEdge[]>();
1161
+ const toIndex = new Map<string, GraphEdge[]>();
1162
+ for (const edge of edges) {
1163
+ fromIndex.set(edge.from, [...(fromIndex.get(edge.from) ?? []), edge]);
1164
+ if (edge.to) toIndex.set(edge.to, [...(toIndex.get(edge.to) ?? []), edge]);
1165
+ }
1166
+
1167
+ return {
1168
+ root,
1169
+ nodes,
1170
+ edges,
1171
+ regions,
1172
+ kinds: buildKindPlane(resources, nodes, deps, options),
1173
+ nodeById: (id) => byId.get(id),
1174
+ edgesFrom: (id) => fromIndex.get(id) ?? [],
1175
+ edgesTo: (id) => toIndex.get(id) ?? [],
1176
+ };
1177
+ }
1178
+
1179
+ /**
1180
+ * The call-graph id a projected node came from — the reverse of `projectedId`.
1181
+ *
1182
+ * Built ONCE. Inverting the map per lookup was a linear scan inside three
1183
+ * per-node loops, so a module of n boxes paid O(n²) three times over on every
1184
+ * keystroke.
1185
+ */
1186
+ function invertProjectedIds(projectedId: ReadonlyMap<string, string>): Map<string, string> {
1187
+ const out = new Map<string, string>();
1188
+ for (const [callGraphId, projected] of projectedId) {
1189
+ if (!out.has(projected)) out.set(projected, callGraphId);
1190
+ }
1191
+ return out;
1192
+ }
1193
+
1194
+ function projectResource(
1195
+ id: string,
1196
+ manifest: ResourceManifest,
1197
+ deps: ModuleGraphDeps,
1198
+ options: BuildModuleGraphOptions,
1199
+ ): GraphNode {
1200
+ const module = moduleOf(manifest);
1201
+ const kind = manifest.kind as string;
1202
+ const definition = deps.definition(kind, module);
1203
+ const origin = originOf(manifest);
1204
+
1205
+ const node: GraphNode = {
1206
+ id,
1207
+ kind,
1208
+ name: manifest.metadata?.name as string,
1209
+ ownership: "named",
1210
+ ports: [],
1211
+ rows: [],
1212
+ rowArrays: [],
1213
+ };
1214
+ if (definition?.capability) node.capability = definition.capability as string;
1215
+ const canonical = canonicalKindOf(definition);
1216
+ if (canonical && canonical !== kind) node.canonicalKind = canonical;
1217
+ if (!definition) node.unknownKind = true;
1218
+ if (module) node.module = module;
1219
+
1220
+ if (origin) {
1221
+ node.ownership = "inline";
1222
+ node.owner = resourceId(origin.parentKind, origin.parentName);
1223
+ node.ownerSite = origin.pathFromParent;
1224
+ } else if (isInjected(manifest)) {
1225
+ node.ownership = "injected";
1226
+ } else if (isForwardedExport(manifest)) {
1227
+ node.ownership = "imported";
1228
+ }
1229
+
1230
+ // External is a fact about the DECLARING module, not about the ownership
1231
+ // class: a library's own named resource forwarded into an app is `imported`,
1232
+ // while a resource the app declares in an included partial is not — both are
1233
+ // decided by the module stamp rather than by how the reference reached here.
1234
+ if (options.entryModule && module && module !== options.entryModule) {
1235
+ node.external = true;
1236
+ // The alias the reference is WRITTEN with. Several may point at one module;
1237
+ // the first is taken, because a boundary box needs one label and every
1238
+ // alias designates the same module.
1239
+ const alias = module ? deps.aliasesForModule(module)[0] : undefined;
1240
+ if (alias) node.alias = alias;
1241
+ }
1242
+
1243
+ return node;
1244
+ }
1245
+
1246
+ /** Step rows, from the call graph's step nodes. Depth and parent come from the
1247
+ * nesting the call graph already recorded; identity is re-anchored on names. */
1248
+ function stepRows(
1249
+ node: GraphNode,
1250
+ callGraph: CallGraph,
1251
+ callGraphId: string,
1252
+ rowIdByPath: Map<string, string>,
1253
+ ): GraphRow[] {
1254
+ const steps = callGraph.steps(callGraphId);
1255
+ if (steps.length === 0) return [];
1256
+ const minter = new IdMinter();
1257
+ const idByStepPath = new Map<string, string>();
1258
+ const rows: GraphRow[] = [];
1259
+
1260
+ for (const step of steps) {
1261
+ const parentId = step.parent ? idByStepPath.get(step.parent) : undefined;
1262
+ const anchor = parentId ? `${parentId}/` : `${node.id}#step:`;
1263
+ const key = step.name ?? `@${contentKey(step.step)}`;
1264
+ const id = minter.mint(`${anchor}${key}`);
1265
+ idByStepPath.set(step.id, id);
1266
+ rowIdByPath.set(`${node.id}\0${step.path}`, id);
1267
+
1268
+ const row: GraphRow = {
1269
+ id,
1270
+ kind: "step",
1271
+ path: step.path,
1272
+ array: step.array,
1273
+ index: step.index,
1274
+ depth: depthOf(step, callGraph, callGraphId),
1275
+ ...(step.name !== undefined ? { name: step.name } : {}),
1276
+ ...(step.variant !== undefined ? { variant: step.variant } : {}),
1277
+ ...(step.variantLabel !== undefined ? { variantLabel: step.variantLabel } : {}),
1278
+ ...(step.predicate !== undefined ? { predicate: step.predicate } : {}),
1279
+ ...(parentId ? { parent: parentId } : {}),
1280
+ };
1281
+ rows.push(row);
1282
+ }
1283
+ return rows;
1284
+ }
1285
+
1286
+ /**
1287
+ * One dispatch, with the other ways its grammar lets it be written.
1288
+ *
1289
+ * Deduplicated by CONSTRAINT, not by path: two spellings accepting the same
1290
+ * kinds are one site, and which of them to write is a choice a reader should
1291
+ * never be asked to make (the primary is the plainer form). A spelling that
1292
+ * accepts something the primary cannot is a site of its own, because it is the
1293
+ * only address a reference to such a target could be written at.
1294
+ */
1295
+ function withAlternatives(
1296
+ primary: NonNullable<GraphRow["dispatch"]>,
1297
+ sites: readonly { path: string; refs: string[] }[],
1298
+ ): NonNullable<GraphRow["dispatch"]> {
1299
+ const key = (refs: readonly string[]) => [...refs].sort().join("\u0000");
1300
+ const seen = new Set([key(primary.refs)]);
1301
+ const alternatives: { path: string; refs: string[] }[] = [];
1302
+ for (const site of sites) {
1303
+ if (site.path === primary.path || seen.has(key(site.refs))) continue;
1304
+ seen.add(key(site.refs));
1305
+ alternatives.push(site);
1306
+ }
1307
+ return alternatives.length > 0 ? { ...primary, alternatives } : primary;
1308
+ }
1309
+
1310
+ /**
1311
+ * The rows and edges a DECLARATION written at a dispatch site contributes.
1312
+ *
1313
+ * `invoke: { kind: Sql.Command, connection: !ref chatDb }` is a resource the
1314
+ * manifest genuinely declares, and until now the graph could see none of it: no
1315
+ * node, no edge, and a step row identical to one that dispatches nothing. The
1316
+ * hold was invisible too, so a connection reached only from inside inline
1317
+ * declarations was reported as referenced by nothing.
1318
+ *
1319
+ * What is emitted is one row for the declaration — named by its kind, addressed
1320
+ * at the site, so it can be opened and edited where it was written — and one row
1321
+ * per reference it fills, each carrying a real edge. That is what puts the hold
1322
+ * back on the graph, and it is why these are rows rather than a label: a
1323
+ * reference needs somewhere for its line to leave from.
1324
+ *
1325
+ * Recursive, because a declaration may hold another; bounded by the manifest,
1326
+ * which cannot contain itself.
1327
+ */
1328
+ function inlineRows(
1329
+ node: GraphNode,
1330
+ site: { path: string; value: Record<string, unknown> },
1331
+ host: { rowId: string; array: string; depth: number; slot: string },
1332
+ deps: ModuleGraphDeps,
1333
+ rowIdByPath: Map<string, string>,
1334
+ out: { rows: GraphRow[]; edges: InlineEdgeSeed[] },
1335
+ ): void {
1336
+ const kind = site.value.kind as string;
1337
+ const declared = deps.definition(kind, node.module);
1338
+ const id = `${host.rowId}/${lastPathSegment(site.path)}`;
1339
+ const row: GraphRow = {
1340
+ id,
1341
+ kind: "inline",
1342
+ path: site.path,
1343
+ array: host.array,
1344
+ index: 0,
1345
+ depth: host.depth + 1,
1346
+ parent: host.rowId,
1347
+ declares: kind,
1348
+ ...(declared ? {} : { unknownKind: true }),
1349
+ };
1350
+ out.rows.push(row);
1351
+ rowIdByPath.set(`${node.id}\0${site.path}`, id);
1352
+
1353
+ // The declaration's own reference slots, read through its kind's field map —
1354
+ // the same map a named resource's ports come from, so an inline declaration
1355
+ // and an extracted one describe themselves identically.
1356
+ const asManifest = { ...site.value, metadata: { name: id } } as unknown as ResourceManifest;
1357
+ const declaredSchema = declared?.schema as Record<string, any> | undefined;
1358
+ for (const field of deps.refFields(asManifest)) {
1359
+ for (const entry of resolveFieldEntries(asManifest, field.path)) {
1360
+ const path = `${site.path}.${entry.path}`;
1361
+ if (isInlineDeclaration(entry.value)) {
1362
+ inlineRows(
1363
+ node,
1364
+ { path, value: entry.value as Record<string, unknown> },
1365
+ { rowId: id, array: host.array, depth: row.depth, slot: `${host.slot}.${field.path}` },
1366
+ deps,
1367
+ rowIdByPath,
1368
+ out,
1369
+ );
1370
+ continue;
1371
+ }
1372
+ const target = refName(entry.value);
1373
+ if (target === undefined) continue;
1374
+ const refId = `${id}/${lastPathSegment(entry.path)}`;
1375
+ out.rows.push({
1376
+ id: refId,
1377
+ kind: "reference",
1378
+ name: lastPathSegment(field.path),
1379
+ path,
1380
+ array: host.array,
1381
+ index: 0,
1382
+ depth: row.depth + 1,
1383
+ parent: id,
1384
+ target,
1385
+ });
1386
+ rowIdByPath.set(`${node.id}\0${path}`, refId);
1387
+ out.edges.push({
1388
+ rowId: refId,
1389
+ toName: target,
1390
+ // The slot the OWNER declares, so the branch this edge leaves is the
1391
+ // host's own property — what decides whether it is drawn at all.
1392
+ slot: `${host.slot}.${field.path}`,
1393
+ path,
1394
+ // Read off the DECLARED kind's own schema, exactly as a port's is —
1395
+ // `use` is a property of the slot, and the slot belongs to the kind
1396
+ // written here rather than to the resource hosting it.
1397
+ uses: readUses(schemaAt(declaredSchema, field.path)),
1398
+ });
1399
+ }
1400
+ }
1401
+ }
1402
+
1403
+ /**
1404
+ * The body with each declaration's rows woven in beneath the row that declares
1405
+ * it, keeping the whole list pre-order.
1406
+ *
1407
+ * Pre-order is not a nicety: every consumer of `parent` — the tree's visibility
1408
+ * walk, the geometry, the renderer — settles a parent's verdict before it asks
1409
+ * about a child, and appending these at the end would silently break all three.
1410
+ *
1411
+ * Sites come from two places and neither is optional. A STEP's dispatch slot is
1412
+ * recorded by the call graph, which is the only walk that reaches a step's item
1413
+ * schema; every other slot — a route's `handler:`, a `mounts[].mount` — is an
1414
+ * ordinary field-map entry and is found here.
1415
+ */
1416
+ function weaveInlineRows(
1417
+ node: GraphNode,
1418
+ manifest: ResourceManifest,
1419
+ callGraph: CallGraph,
1420
+ callGraphId: string,
1421
+ deps: ModuleGraphDeps,
1422
+ rowIdByPath: Map<string, string>,
1423
+ seeds: Map<string, InlineEdgeSeed[]>,
1424
+ ): GraphRow[] {
1425
+ /**
1426
+ * Sites keyed by their concrete path, because the two walks OVERLAP: a step's
1427
+ * `invoke:` is both a step dispatch slot and a row-owned port slot, so
1428
+ * collecting them into a list emitted every declaration under a step twice —
1429
+ * two rows sharing one id, and two copies of every edge inside it.
1430
+ */
1431
+ // This node's rows as they stand before any declaration is woven in — which
1432
+ // is what a site can be hosted BY. Scoped to the node rather than scanning
1433
+ // every row in the module, and taken once because the weave only ADDS rows
1434
+ // below the ones a site could already have named.
1435
+ const ownRows = rowsByOwnerOf(rowIdByPath).get(node.id) ?? [];
1436
+
1437
+ const sites = new Map<string, { rowId: string; path: string; value: Record<string, unknown>; slot: string }>();
1438
+ const record = (rowId: string, path: string, value: unknown, slot: string): void => {
1439
+ if (!rowId || sites.has(path) || !isInlineDeclaration(value)) return;
1440
+ sites.set(path, { rowId, path, value: value as Record<string, unknown>, slot });
1441
+ };
1442
+
1443
+ for (const step of callGraph.steps(callGraphId)) {
1444
+ for (const site of (step.refSlots ?? []).filter((slot) => slot.inline)) {
1445
+ const rowId = rowIdByPath.get(`${node.id}\0${step.path}`);
1446
+ if (!rowId) continue;
1447
+ record(rowId, site.path, step.step[site.key], `${step.array}[].${site.key}`);
1448
+ }
1449
+ }
1450
+
1451
+ for (const port of node.ports) {
1452
+ if (!port.slots.some((slot) => slot.inline)) continue;
1453
+ for (const entry of resolveFieldEntries(manifest, port.slot)) {
1454
+ // A site on a slot no row owns — a plain `connection:` on a resource — is
1455
+ // left to the port, which already draws it. Only a ROW can host a subtree.
1456
+ const rowId =
1457
+ rowIdByPath.get(`${node.id}\0${entry.path}`) ??
1458
+ rowAt(new Map([[node.id, ownRows]]), node.id, entry.path);
1459
+ if (!rowId) continue;
1460
+ record(rowId, entry.path, entry.value, port.slot);
1461
+ }
1462
+ }
1463
+
1464
+ if (sites.size === 0) return node.rows;
1465
+
1466
+ const byRow = new Map<string, typeof sites extends Map<string, infer V> ? V[] : never>();
1467
+ for (const site of sites.values()) {
1468
+ byRow.set(site.rowId, [...(byRow.get(site.rowId) ?? []), site]);
1469
+ }
1470
+
1471
+
1472
+
1473
+ const out: GraphRow[] = [];
1474
+ for (const row of node.rows) {
1475
+ out.push(row);
1476
+ for (const site of byRow.get(row.id) ?? []) {
1477
+ const collected = { rows: [] as GraphRow[], edges: [] as InlineEdgeSeed[] };
1478
+ inlineRows(
1479
+ node,
1480
+ { path: site.path, value: site.value },
1481
+ { rowId: row.id, array: row.array, depth: row.depth, slot: site.slot },
1482
+ deps,
1483
+ rowIdByPath,
1484
+ collected,
1485
+ );
1486
+ out.push(...collected.rows);
1487
+ if (collected.edges.length > 0) {
1488
+ seeds.set(node.id, [...(seeds.get(node.id) ?? []), ...collected.edges]);
1489
+ }
1490
+ }
1491
+ }
1492
+ return out;
1493
+ }
1494
+
1495
+ /** A reference found inside a declaration, before its target is resolved. */
1496
+ interface InlineEdgeSeed {
1497
+ rowId: string;
1498
+ toName: string;
1499
+ slot: string;
1500
+ path: string;
1501
+ uses: RefUse[];
1502
+ }
1503
+
1504
+ /** `steps[0].invoke.connection` → `connection`; `routes[1]` → `routes`. */
1505
+ function lastPathSegment(path: string): string {
1506
+ const last = path.split(".").pop() ?? path;
1507
+ return last.replace(/\[\d+\]$/, "").replace(/\[\]$|\{\}$/, "");
1508
+ }
1509
+
1510
+ /** Nesting depth of a step: how many step parents stand above it. */
1511
+ function depthOf(step: StepGraphNode, callGraph: CallGraph, ownerId: string): number {
1512
+ let depth = 0;
1513
+ let current: StepGraphNode | undefined = step;
1514
+ const byId = new Map(callGraph.steps(ownerId).map((s) => [s.id, s] as const));
1515
+ while (current?.parent) {
1516
+ depth++;
1517
+ current = byId.get(current.parent);
1518
+ }
1519
+ return depth;
1520
+ }
1521
+
1522
+ /** Entry rows: one per item of an `x-telo-topology-role: entries` array. The
1523
+ * matcher fields are what identifies an entry to a reader, so they are also
1524
+ * what its identity is derived from — a route keeps its identity when a route
1525
+ * is inserted above it, and loses it only when its own path or method change,
1526
+ * which is what makes it a different route. */
1527
+ function entryRows(
1528
+ node: GraphNode,
1529
+ manifest: ResourceManifest,
1530
+ schema: Record<string, any> | undefined,
1531
+ rowIdByPath: Map<string, string>,
1532
+ ): GraphRow[] {
1533
+ const rows: GraphRow[] = [];
1534
+ for (const spec of entryListsOf(schema)) {
1535
+ const value = (manifest as Record<string, unknown>)[spec.field];
1536
+ if (!Array.isArray(value)) continue;
1537
+ const minter = new IdMinter();
1538
+ value.forEach((item, index) => {
1539
+ const entry = (item ?? {}) as Record<string, unknown>;
1540
+ // What IDENTIFIES an entry to a reader is the scalars its matcher holds —
1541
+ // a path and a method — not the whole matcher, which for an HTTP route
1542
+ // also carries the request schema. Taking the schema would put a row's
1543
+ // identity at the mercy of an edit to a property it does not show, so a
1544
+ // reader loses their selection by editing something else entirely.
1545
+ const match = scalarLeaves(
1546
+ Object.fromEntries(spec.matchers.filter((m) => entry[m] !== undefined).map((m) => [m, entry[m]])),
1547
+ );
1548
+ const key = Object.keys(match).length > 0 ? contentKey(match) : contentKey(entry);
1549
+ const path = `${spec.field}[${index}]`;
1550
+ const id = minter.mint(`${node.id}#entry:${spec.field}/${key}`);
1551
+ rowIdByPath.set(`${node.id}\0${path}`, id);
1552
+
1553
+ const handlerField = spec.handlers.find((h) => entry[h] !== undefined);
1554
+ const target = handlerField ? refName(entry[handlerField]) : undefined;
1555
+ const catches = spec.errorBranches.some((b) => {
1556
+ const value = entry[b];
1557
+ return Array.isArray(value) ? value.length > 0 : value !== undefined;
1558
+ });
1559
+ rows.push({
1560
+ id,
1561
+ kind: "entry",
1562
+ path,
1563
+ array: spec.field,
1564
+ index,
1565
+ depth: 0,
1566
+ ...(Object.keys(match).length > 0 ? { match } : {}),
1567
+ ...(target !== undefined ? { target } : {}),
1568
+ ...(catches ? { catches: true } : {}),
1569
+ });
1570
+ });
1571
+ }
1572
+ return rows;
1573
+ }
1574
+
1575
+ /**
1576
+ * The scalar leaves of a value, flattened to one map, to a bounded depth.
1577
+ *
1578
+ * A matcher is whatever the kind declared it to be: a flat `path` / `method`
1579
+ * pair on one router, a nested `request:` object on another. Reading the scalars
1580
+ * out of it works for both without naming either — and stopping at scalars is
1581
+ * what keeps a nested JSON Schema (which is an object all the way down) out of
1582
+ * something a reader is meant to recognize the row by.
1583
+ */
1584
+ function scalarLeaves(value: unknown, depth = 0): Record<string, unknown> {
1585
+ const out: Record<string, unknown> = {};
1586
+ if (depth > 2 || !value || typeof value !== "object" || Array.isArray(value)) return out;
1587
+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
1588
+ if (child === null) continue;
1589
+ if (typeof child !== "object") out[key] = child;
1590
+ else Object.assign(out, scalarLeaves(child, depth + 1));
1591
+ }
1592
+ return out;
1593
+ }
1594
+
1595
+ /**
1596
+ * The ordered arrays a kind declares — its entry lists and its step bodies.
1597
+ *
1598
+ * Both are found by annotation (`x-telo-topology-role: entries`, and the shared
1599
+ * step-body stamp), so a third-party composer's list is offered the same
1600
+ * affordances as `Http.Api`'s routes with no editor change.
1601
+ */
1602
+ function declaredRowArrays(
1603
+ schema: Record<string, any> | undefined,
1604
+ ): { field: string; kind: RowKind }[] {
1605
+ const out: { field: string; kind: RowKind }[] = [];
1606
+ for (const spec of entryListsOf(schema)) out.push({ field: spec.field, kind: "entry" });
1607
+ for (const [key, propSchema] of propertySchemas(schema ?? {})) {
1608
+ if (isStepSlot(propSchema)) out.push({ field: key, kind: "step" });
1609
+ }
1610
+ return out;
1611
+ }
1612
+
1613
+ /** Boot rows: the root's `targets`, which is an ordered step list — a later
1614
+ * target reads an earlier one's result — so it is rows, not a set. */
1615
+ function targetRows(
1616
+ node: GraphNode,
1617
+ manifest: ResourceManifest,
1618
+ rowIdByPath: Map<string, string>,
1619
+ ): GraphRow[] {
1620
+ const targets = (manifest as Record<string, unknown>).targets;
1621
+ if (!Array.isArray(targets)) return [];
1622
+ const minter = new IdMinter();
1623
+ return targets.map((entry, index) => {
1624
+ const record = (entry ?? {}) as Record<string, unknown>;
1625
+ const target =
1626
+ refName(entry) ?? refName(record.ref) ?? refName(record.invoke) ?? undefined;
1627
+ const name = typeof record.name === "string" ? record.name : undefined;
1628
+ const key = name ?? target ?? `@${contentKey(entry)}`;
1629
+ const path = `targets[${index}]`;
1630
+ const id = minter.mint(`${node.id}#target:${key}`);
1631
+ rowIdByPath.set(`${node.id}\0${path}`, id);
1632
+ return {
1633
+ id,
1634
+ kind: "target" as const,
1635
+ path,
1636
+ array: "targets",
1637
+ index,
1638
+ depth: 0,
1639
+ ...(name !== undefined ? { name } : {}),
1640
+ ...(target !== undefined ? { target } : {}),
1641
+ // A boot target's shapes carry no branch titles, so there is no variant
1642
+ // to report — but a GATED one is the same fact a step's `when:` is, and
1643
+ // a target drawn without its guard says it always runs.
1644
+ ...(guardOf(record) !== undefined ? { predicate: guardOf(record)! } : {}),
1645
+ };
1646
+ });
1647
+ }
1648
+
1649
+ /** The `when:` guard on a boot target, as written. */
1650
+ function guardOf(entry: Record<string, unknown>): string | undefined {
1651
+ const written = entry.when;
1652
+ if (typeof written === "string") return written;
1653
+ if (written && typeof written === "object") {
1654
+ const source = (written as { source?: unknown }).source;
1655
+ if (typeof source === "string") return source;
1656
+ }
1657
+ return undefined;
1658
+ }
1659
+
1660
+ /** Every declared reference slot as a port, with its occupancy read off the
1661
+ * manifest — so an empty slot is a port with no filled sites rather than an
1662
+ * absence a view has to infer. */
1663
+ function buildPorts(
1664
+ manifest: ResourceManifest,
1665
+ deps: ModuleGraphDeps,
1666
+ schema: Record<string, any> | undefined,
1667
+ rowArrays: ReadonlySet<string>,
1668
+ ): GraphPort[] {
1669
+ const fields = deps.refFields(manifest);
1670
+
1671
+ // The `anyOf` sub-shapes of one array-of-refs are ONE slot, not three. A boot
1672
+ // target may be written bare, as `{ref, when}` or as an inline invoke step, so
1673
+ // the field map lists `targets[]`, `targets[].ref` and `targets[].invoke` —
1674
+ // rendering each as its own port offers three sockets for one position and
1675
+ // says the module has slots it does not have.
1676
+ const arrayRefBases = new Set(
1677
+ fields.filter((f) => isArrayOfRefs(f.path)).map((f) => arrayBaseOf(f.path)),
1678
+ );
1679
+
1680
+ const ports: GraphPort[] = [];
1681
+ for (const field of fields) {
1682
+ if ([...arrayRefBases].some((base) => field.path.startsWith(`${base}[].`))) continue;
1683
+ const slotSchema = schemaAt(schema, field.path);
1684
+ const uses = readUses(slotSchema);
1685
+ const slots: PortSlot[] = [];
1686
+ for (const { value, path } of resolveFieldEntries(manifest, field.path)) {
1687
+ const target = refName(value);
1688
+ const slot: PortSlot = { path };
1689
+ if (target !== undefined) slot.target = target;
1690
+ // A slot holding a declaration rather than a reference is FILLED, and a
1691
+ // view that reads only `target` would draw it as an empty socket — the
1692
+ // one reading that is wrong in both directions, since it invites filling
1693
+ // a slot that is already occupied.
1694
+ else if (isInlineDeclaration(value)) slot.inline = true;
1695
+ slots.push(slot);
1696
+ }
1697
+
1698
+ // **An unwritten slot still has a write site.** Resolving the manifest for
1699
+ // `notFoundHandler.invoke` on a server that declares no `notFoundHandler`
1700
+ // yields nothing, so the port had no path at all — it rendered as an empty
1701
+ // socket that could not be filled, which is worse than not drawing it: it
1702
+ // offers an affordance and then refuses. The path IS the site for a slot in
1703
+ // no array, so it is synthesized here rather than left to every consumer to
1704
+ // reconstruct.
1705
+ if (slots.length === 0 && !field.path.includes("[]") && !field.path.includes("{}")) {
1706
+ slots.push({ path: field.path });
1707
+ }
1708
+ const port: GraphPort = {
1709
+ slot: field.path,
1710
+ refs: field.refs,
1711
+ capabilities: field.capabilities,
1712
+ array: field.isArray,
1713
+ class: edgeClassOf(uses),
1714
+ slots,
1715
+ };
1716
+ const append = appendPathFor(field.path, manifest);
1717
+ if (append) port.addPath = append;
1718
+ if (rowArrays.has(containerArrayOf(field.path))) port.rowOwned = true;
1719
+ ports.push(port);
1720
+ }
1721
+ return ports;
1722
+ }
1723
+
1724
+ /** A top-level array of direct refs (`targets[]`): the trailing `[]` is the
1725
+ * path's only marker. */
1726
+ function isArrayOfRefs(path: string): boolean {
1727
+ return path.endsWith("[]") && !path.slice(0, -2).match(/\[\]|\{\}/);
1728
+ }
1729
+
1730
+ /** `targets[]` → `targets`. */
1731
+ function arrayBaseOf(path: string): string {
1732
+ return path.slice(0, -2);
1733
+ }
1734
+
1735
+ /**
1736
+ * Where a NEW occupancy of this slot would be written.
1737
+ *
1738
+ * Both array shapes reach here: a direct array of refs (`targets[]` →
1739
+ * `targets[2]`) and a ref inside an array of objects (`mounts[].mount` →
1740
+ * `mounts[2].mount`). The second was missing, so an `Http.Server` with no mounts
1741
+ * offered no way to add one — the port drew an empty rail and the drag had
1742
+ * nowhere to land. Undefined for a slot in no array, and for one nested past a
1743
+ * single array, where the index of the outer item is not determined by the slot
1744
+ * alone.
1745
+ */
1746
+ function appendPathFor(path: string, manifest: ResourceManifest): string | undefined {
1747
+ const marker = path.indexOf("[]");
1748
+ if (marker === -1) return undefined;
1749
+ const array = path.slice(0, marker);
1750
+ const suffix = path.slice(marker + 2);
1751
+ if (array.includes("{}") || suffix.includes("[]") || suffix.includes("{}")) return undefined;
1752
+ const existing = (manifest as Record<string, unknown>)[array];
1753
+ return `${array}[${Array.isArray(existing) ? existing.length : 0}]${suffix}`;
1754
+ }
1755
+
1756
+ /** The array a slot's occupancy sits in (`routes[].handler` → `routes`,
1757
+ * `targets[]` → `targets`), or the path itself when it is in no array. */
1758
+ function containerArrayOf(path: string): string {
1759
+ const marker = path.indexOf("[]");
1760
+ return marker === -1 ? path : path.slice(0, marker);
1761
+ }
1762
+
1763
+ /**
1764
+ * Declared uses at a slot, through the annotation's ONE reader.
1765
+ *
1766
+ * It used to hand-parse `slotSchema["x-telo-ref"]`, which sees nothing when the
1767
+ * annotation sits in a `oneOf` branch — the sanctioned shape for a slot that
1768
+ * unions a value with a reference. A column's `type:` is exactly that, so its
1769
+ * `use: schema` read as no declared use at all and the slot was classed (and
1770
+ * drawn) as a control transfer. `readRefSlot` unions the branches; `possibleUses`
1771
+ * folds a case map's arms in, which is what a PORT wants: the port describes the
1772
+ * slot, and which arm holds is decided per site by the call graph.
1773
+ */
1774
+ function readUses(slotSchema: Record<string, any> | undefined): RefUse[] {
1775
+ const slot = readRefSlot(slotSchema);
1776
+ return slot ? possibleUses(slot) : [];
1777
+ }
1778
+
1779
+ /** Re-key one call-graph edge onto the boxes a view draws. A step's edge is
1780
+ * attributed to the resource whose body declares it — a step is a row here,
1781
+ * not a node — with the row named so the edge can dock onto it. */
1782
+ function projectEdge(
1783
+ edge: CallGraphEdge,
1784
+ callGraph: CallGraph,
1785
+ byId: ReadonlyMap<string, GraphNode>,
1786
+ rowIdByPath: ReadonlyMap<string, string>,
1787
+ rowsByOwner: ReadonlyMap<string, readonly { path: string; id: string }[]>,
1788
+ byQualifiedName: ReadonlyMap<string, string>,
1789
+ projectedId: ReadonlyMap<string, string>,
1790
+ ): GraphEdge | undefined {
1791
+ const source = callGraph.nodes.get(edge.from);
1792
+ const rawFrom = source?.type === "step" ? source.owner : edge.from;
1793
+ const fromId = projectedId.get(rawFrom) ?? rawFrom;
1794
+ if (!byId.has(fromId)) return undefined;
1795
+
1796
+ const projected: GraphEdge = {
1797
+ id: `${fromId}\0${edge.slot}\0${edge.path}`,
1798
+ from: fromId,
1799
+ toName: edge.toName,
1800
+ class: edgeClassOf(edge.use),
1801
+ use: edge.use,
1802
+ slot: edge.slot,
1803
+ path: edge.path,
1804
+ };
1805
+ const to = edge.to ? (projectedId.get(edge.to) ?? edge.to) : undefined;
1806
+ if (to && byId.has(to)) projected.to = to;
1807
+ else {
1808
+ const qualified = byQualifiedName.get(edge.toName);
1809
+ if (qualified) projected.to = qualified;
1810
+ }
1811
+ if (edge.inputs !== undefined) projected.inputs = edge.inputs;
1812
+ if (edge.scoped) projected.scoped = true;
1813
+
1814
+ // The row an edge leaves from: the step that declares it, or the entry whose
1815
+ // handler slot holds it. Longest-prefix on the concrete path, so a site
1816
+ // nested inside a branch docks onto the row that actually declares it.
1817
+ const row = rowIdByPath.get(`${fromId}\0${edge.path}`) ?? rowAt(rowsByOwner, fromId, edge.path);
1818
+ if (row) projected.row = row;
1819
+ return projected;
1820
+ }
1821
+
1822
+ /** The row whose path is the longest prefix of a site's path. */
1823
+ function rowAt(
1824
+ rowsByOwner: ReadonlyMap<string, readonly { path: string; id: string }[]>,
1825
+ ownerId: string,
1826
+ path: string,
1827
+ ): string | undefined {
1828
+ let best: string | undefined;
1829
+ let bestLength = -1;
1830
+ for (const row of rowsByOwner.get(ownerId) ?? []) {
1831
+ const inside = path.startsWith(`${row.path}.`) || path.startsWith(`${row.path}[`);
1832
+ if (inside && row.path.length > bestLength) {
1833
+ best = row.id;
1834
+ bestLength = row.path.length;
1835
+ }
1836
+ }
1837
+ return best;
1838
+ }
1839
+
1840
+ /**
1841
+ * The rows each box owns, by owner — so finding the row a nested site sits in
1842
+ * is a scan of one box's rows rather than of every row in the module.
1843
+ *
1844
+ * The flat `<owner>\0<path>` map is the right shape for an exact hit and the
1845
+ * wrong one for the longest-prefix walk, which is the COMMON case: a step's ref
1846
+ * is nested inside the step, so the exact lookup misses and the fallback ran
1847
+ * over every row of every box, for every edge and every CEL chain.
1848
+ */
1849
+ function rowsByOwnerOf(
1850
+ rowIdByPath: ReadonlyMap<string, string>,
1851
+ ): Map<string, { path: string; id: string }[]> {
1852
+ const out = new Map<string, { path: string; id: string }[]>();
1853
+ for (const [key, id] of rowIdByPath) {
1854
+ // The LAST separator: a node id contains NULs of its own (`kind\0name`, and
1855
+ // `module\0kind\0name` across a boundary) while a concrete path contains
1856
+ // none, so splitting at the first one takes the kind for the owner and
1857
+ // leaves the name glued to the path — an index that matches nothing.
1858
+ const marker = key.lastIndexOf("\0");
1859
+ if (marker === -1) continue;
1860
+ const owner = key.slice(0, marker);
1861
+ out.set(owner, [...(out.get(owner) ?? []), { path: key.slice(marker + 1), id }]);
1862
+ }
1863
+ return out;
1864
+ }
1865
+
1866
+ /** Kinds a definition body declares — the marks of a template rather than a
1867
+ * controller-backed kind. */
1868
+ const TEMPLATE_FIELDS = ["resources", "invoke", "run", "provide"] as const;
1869
+
1870
+ /**
1871
+ * The kind plane: every `Telo.Definition` / `Telo.Abstract` in scope, with its
1872
+ * lineage and the instances that were declared of it.
1873
+ *
1874
+ * Built from the same manifest list the instance plane skips them from, so a
1875
+ * kind-only library — one whose whole content is declarations — has a plane to
1876
+ * render rather than an empty canvas.
1877
+ */
1878
+ function buildKindPlane(
1879
+ resources: ResourceManifest[],
1880
+ nodes: readonly GraphNode[],
1881
+ deps: ModuleGraphDeps,
1882
+ options: BuildModuleGraphOptions,
1883
+ ): GraphKind[] {
1884
+ const exportedKinds = new Set(
1885
+ (((options.root as Record<string, any> | undefined)?.exports?.kinds ?? []) as unknown[]).filter(
1886
+ (k): k is string => typeof k === "string",
1887
+ ),
1888
+ );
1889
+
1890
+ // Keyed on the CANONICAL kind, because that is what a kind's own id is: an
1891
+ // instance a library declared as `kind: Self.WriteLine` belongs to
1892
+ // `console.WriteLine`, and keying on the written spelling gave every such kind
1893
+ // an empty instance list.
1894
+ const instancesByKind = new Map<string, string[]>();
1895
+ for (const node of nodes) {
1896
+ if (node.root) continue;
1897
+ const key = node.canonicalKind ?? node.kind;
1898
+ instancesByKind.set(key, [...(instancesByKind.get(key) ?? []), node.id]);
1899
+ }
1900
+
1901
+ const out: GraphKind[] = [];
1902
+ for (const manifest of resources) {
1903
+ const docKind = manifest.kind as string;
1904
+ if (docKind !== "Telo.Definition" && docKind !== "Telo.Abstract") continue;
1905
+ const name = manifest.metadata?.name as string | undefined;
1906
+ if (!name) continue;
1907
+ const module = moduleOf(manifest);
1908
+ const id = module ? `${module}.${name}` : name;
1909
+ const record = manifest as unknown as Record<string, unknown>;
1910
+ const extendsName = typeof record.extends === "string" ? record.extends : undefined;
1911
+ const parent = extendsName ? deps.definition(extendsName, module) : undefined;
1912
+ const parentModule = parent ? moduleOf(parent as unknown as ResourceManifest) : undefined;
1913
+ const parentName = parent?.metadata?.name as string | undefined;
1914
+
1915
+ const kind: GraphKind = {
1916
+ id,
1917
+ name,
1918
+ abstract: docKind === "Telo.Abstract",
1919
+ instances: instancesByKind.get(id) ?? [],
1920
+ template: TEMPLATE_FIELDS.some((f) => record[f] !== undefined),
1921
+ own: !!options.entryModule && module === options.entryModule,
1922
+ };
1923
+ if (module) kind.module = module;
1924
+ if (typeof record.capability === "string") kind.capability = record.capability;
1925
+ if (extendsName) kind.extendsName = extendsName;
1926
+ if (parent && parentName) kind.extendsId = parentModule ? `${parentModule}.${parentName}` : parentName;
1927
+ // Only the entry module's gate is in hand — an imported library's
1928
+ // `exports.kinds` is stamped on the import, not on the definition, so a
1929
+ // claim about it here would be a guess.
1930
+ if (kind.own) kind.exported = exportedKinds.has(name);
1931
+ out.push(kind);
1932
+ }
1933
+ return out;
1934
+ }
1935
+
1936
+ /**
1937
+ * Every `resources.<name>…` read in one resource's CEL, as an edge.
1938
+ *
1939
+ * This is the dependency a manifest states without a slot: a config provider
1940
+ * read by five resources has five edges the reference graph cannot show, and an
1941
+ * observed-state read is the same shape one level in. Deduplicated per
1942
+ * (target, chain), since the same read at two sites is one fact about the pair.
1943
+ */
1944
+ function dataEdges(
1945
+ node: GraphNode,
1946
+ manifest: ResourceManifest,
1947
+ fromModule: string | undefined,
1948
+ resolveName: (name: string, fromModule: string | undefined) => string | undefined,
1949
+ rowIdByPath: ReadonlyMap<string, string>,
1950
+ rowsByOwner: ReadonlyMap<string, readonly { path: string; id: string }[]>,
1951
+ ): GraphEdge[] {
1952
+ const out: GraphEdge[] = [];
1953
+ const seen = new Set<string>();
1954
+ walkCelExpressions(manifest, "", (source, path) => {
1955
+ for (const chain of accessChains(source)) {
1956
+ if (chain[0] !== "resources" || chain.length < 2) continue;
1957
+ const targetName = chain[1]!;
1958
+ // `resources.<name>` is a bare name written in THIS module's scope, so it
1959
+ // resolves the way every other bare name does.
1960
+ const to = resolveName(targetName, fromModule);
1961
+ if (!to || to === node.id) continue;
1962
+ const read = chain.join(".");
1963
+ const key = `${to}\0${read}`;
1964
+ if (seen.has(key)) continue;
1965
+ seen.add(key);
1966
+ const edge: GraphEdge = {
1967
+ id: `${node.id}\0data\0${path}\0${read}`,
1968
+ from: node.id,
1969
+ to,
1970
+ toName: targetName,
1971
+ class: "data",
1972
+ use: [],
1973
+ slot: "cel",
1974
+ path,
1975
+ read,
1976
+ };
1977
+ const row = rowIdByPath.get(`${node.id}\0${path}`) ?? rowAt(rowsByOwner, node.id, path);
1978
+ if (row) edge.row = row;
1979
+ out.push(edge);
1980
+ }
1981
+ });
1982
+ return out;
1983
+ }