@graphrefly/graphrefly 0.1.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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +234 -0
  3. package/dist/chunk-5X3LAO3B.js +1571 -0
  4. package/dist/chunk-5X3LAO3B.js.map +1 -0
  5. package/dist/chunk-6W5SGIGB.js +1793 -0
  6. package/dist/chunk-6W5SGIGB.js.map +1 -0
  7. package/dist/chunk-CP6MNKAA.js +97 -0
  8. package/dist/chunk-CP6MNKAA.js.map +1 -0
  9. package/dist/chunk-HP7OKEOE.js +107 -0
  10. package/dist/chunk-HP7OKEOE.js.map +1 -0
  11. package/dist/chunk-KWXPDASV.js +781 -0
  12. package/dist/chunk-KWXPDASV.js.map +1 -0
  13. package/dist/chunk-O3PI7W45.js +68 -0
  14. package/dist/chunk-O3PI7W45.js.map +1 -0
  15. package/dist/chunk-QW7H3ICI.js +1372 -0
  16. package/dist/chunk-QW7H3ICI.js.map +1 -0
  17. package/dist/chunk-VPS7L64N.js +4785 -0
  18. package/dist/chunk-VPS7L64N.js.map +1 -0
  19. package/dist/chunk-Z4Y4FMQN.js +1097 -0
  20. package/dist/chunk-Z4Y4FMQN.js.map +1 -0
  21. package/dist/compat/nestjs/index.cjs +4883 -0
  22. package/dist/compat/nestjs/index.cjs.map +1 -0
  23. package/dist/compat/nestjs/index.d.cts +7 -0
  24. package/dist/compat/nestjs/index.d.ts +7 -0
  25. package/dist/compat/nestjs/index.js +84 -0
  26. package/dist/compat/nestjs/index.js.map +1 -0
  27. package/dist/core/index.cjs +1632 -0
  28. package/dist/core/index.cjs.map +1 -0
  29. package/dist/core/index.d.cts +2 -0
  30. package/dist/core/index.d.ts +2 -0
  31. package/dist/core/index.js +90 -0
  32. package/dist/core/index.js.map +1 -0
  33. package/dist/extra/index.cjs +6885 -0
  34. package/dist/extra/index.cjs.map +1 -0
  35. package/dist/extra/index.d.cts +5 -0
  36. package/dist/extra/index.d.ts +5 -0
  37. package/dist/extra/index.js +290 -0
  38. package/dist/extra/index.js.map +1 -0
  39. package/dist/graph/index.cjs +3225 -0
  40. package/dist/graph/index.cjs.map +1 -0
  41. package/dist/graph/index.d.cts +3 -0
  42. package/dist/graph/index.d.ts +3 -0
  43. package/dist/graph/index.js +25 -0
  44. package/dist/graph/index.js.map +1 -0
  45. package/dist/graph-CL_ZDAj9.d.cts +605 -0
  46. package/dist/graph-D18qmsNm.d.ts +605 -0
  47. package/dist/index-B6SsZs2h.d.cts +3463 -0
  48. package/dist/index-B7eOdgEx.d.ts +449 -0
  49. package/dist/index-BHUvlQ3v.d.ts +3463 -0
  50. package/dist/index-BtK55IE2.d.ts +231 -0
  51. package/dist/index-BvhgZRHK.d.cts +231 -0
  52. package/dist/index-Bvy_6CaN.d.ts +452 -0
  53. package/dist/index-C3BMRmmp.d.cts +449 -0
  54. package/dist/index-C5mqLhMX.d.cts +452 -0
  55. package/dist/index-CP_QvbWu.d.ts +940 -0
  56. package/dist/index-D_geH2Bm.d.cts +940 -0
  57. package/dist/index.cjs +14843 -0
  58. package/dist/index.cjs.map +1 -0
  59. package/dist/index.d.cts +1517 -0
  60. package/dist/index.d.ts +1517 -0
  61. package/dist/index.js +3649 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/meta-BsF6Sag9.d.cts +607 -0
  64. package/dist/meta-BsF6Sag9.d.ts +607 -0
  65. package/dist/patterns/reactive-layout/index.cjs +4143 -0
  66. package/dist/patterns/reactive-layout/index.cjs.map +1 -0
  67. package/dist/patterns/reactive-layout/index.d.cts +3 -0
  68. package/dist/patterns/reactive-layout/index.d.ts +3 -0
  69. package/dist/patterns/reactive-layout/index.js +38 -0
  70. package/dist/patterns/reactive-layout/index.js.map +1 -0
  71. package/dist/reactive-log-BfvfNWQh.d.cts +137 -0
  72. package/dist/reactive-log-ohLmTXoZ.d.ts +137 -0
  73. package/package.json +256 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graph/graph.ts"],"sourcesContent":["import type { Actor } from \"../core/actor.js\";\nimport { isBatching } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { GuardDenied } from \"../core/guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport { type DescribeNodeOutput, describeNode } from \"../core/meta.js\";\nimport {\n\ttype Node,\n\tNodeImpl,\n\ttype NodeInspectorHookEvent,\n\ttype NodeSink,\n\ttype NodeTransportOptions,\n} from \"../core/node.js\";\nimport { state as stateNode } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\n\n/** The separator used for qualified paths in {@link Graph.resolve} et al. */\nconst PATH_SEP = \"::\";\n\n/**\n * Reserved segment for meta companion paths: `nodeName::__meta__::metaKey` (GRAPHREFLY-SPEC §3.6).\n * Forbidden as a local node or mount name.\n */\nexport const GRAPH_META_SEGMENT = \"__meta__\";\n\n/** Options for {@link Graph} (reserved for future hooks). */\nexport type GraphOptions = Record<string, unknown>;\n\n/** Filter for {@link Graph.describe} — object-style partial match or predicate. */\nexport type DescribeFilter =\n\t| Partial<Pick<DescribeNodeOutput, \"type\" | \"status\">>\n\t| {\n\t\t\ttype?: DescribeNodeOutput[\"type\"];\n\t\t\tstatus?: DescribeNodeOutput[\"status\"];\n\t\t\t/** Keep nodes whose `deps` includes this qualified path. */\n\t\t\tdepsIncludes?: string;\n\t\t\t/** Snake-case alias for `depsIncludes` (Python parity). */\n\t\t\tdeps_includes?: string;\n\t\t\t/** Keep nodes whose `meta` contains this key. */\n\t\t\tmetaHas?: string;\n\t\t\t/** Snake-case alias for `metaHas` (Python parity). */\n\t\t\tmeta_has?: string;\n\t }\n\t| ((node: DescribeNodeOutput) => boolean)\n\t| ((nodePath: string, node: DescribeNodeOutput) => boolean);\n\n/** Options for {@link Graph.signal} and {@link Graph.set} (actor context, internal lifecycle). */\nexport type GraphActorOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips node guards (graph lifecycle TEARDOWN, unmount teardown, etc.).\n\t */\n\tinternal?: boolean;\n};\n\n/** JSON snapshot from {@link Graph.describe} (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type GraphDescribeOutput = {\n\tname: string;\n\tnodes: Record<string, DescribeNodeOutput>;\n\tedges: ReadonlyArray<{ from: string; to: string }>;\n\tsubgraphs: string[];\n};\n\n/**\n * Persisted graph snapshot: {@link GraphDescribeOutput} plus optional format version\n * ({@link Graph.snapshot}, {@link Graph.restore}, {@link Graph.fromSnapshot}, {@link Graph.toJSON},\n * {@link Graph.toJSONString} — §3.8).\n */\nexport type GraphPersistSnapshot = GraphDescribeOutput & {\n\tversion?: number;\n};\n\nexport type GraphFactoryContext = {\n\tpath: string;\n\ttype: DescribeNodeOutput[\"type\"];\n\tvalue: unknown;\n\tmeta: Record<string, unknown>;\n\tdeps: readonly string[];\n\tresolvedDeps: readonly Node[];\n};\n\nexport type GraphNodeFactory = (name: string, context: GraphFactoryContext) => Node;\n\nexport type AutoCheckpointAdapter = {\n\tsave(data: unknown): void;\n};\n\nexport type GraphCheckpointRecord =\n\t| { mode: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { mode: \"diff\"; diff: GraphDiffResult; snapshot: GraphPersistSnapshot; seq: number };\n\nexport type GraphAutoCheckpointOptions = {\n\tdebounceMs?: number;\n\tcompactEvery?: number;\n\tfilter?: (name: string, described: DescribeNodeOutput) => boolean;\n\tonError?: (error: unknown) => void;\n};\n\nexport type GraphAutoCheckpointHandle = {\n\tdispose(): void;\n};\n\n/** Direction options for diagram export helpers. */\nexport type GraphDiagramDirection = \"TD\" | \"LR\" | \"BT\" | \"RL\";\n\n/** Options for {@link Graph.toMermaid} / {@link Graph.toD2}. */\nexport type GraphDiagramOptions = {\n\t/**\n\t * Diagram flow direction.\n\t * - `TD`: top-down\n\t * - `LR`: left-right (default)\n\t * - `BT`: bottom-top\n\t * - `RL`: right-left\n\t */\n\tdirection?: GraphDiagramDirection;\n};\n\n/** Snapshot format version (§3.8). */\nconst SNAPSHOT_VERSION = 1;\n\n/**\n * Validate the snapshot envelope: version, required keys, types. Aligned with\n * Python `_parse_snapshot_envelope`. Throws on invalid data.\n */\nfunction parseSnapshotEnvelope(data: GraphPersistSnapshot): void {\n\tif (data.version !== SNAPSHOT_VERSION) {\n\t\tthrow new Error(\n\t\t\t`unsupported snapshot version ${String(data.version)} (expected ${SNAPSHOT_VERSION})`,\n\t\t);\n\t}\n\tfor (const key of [\"name\", \"nodes\", \"edges\", \"subgraphs\"] as const) {\n\t\tif (!(key in data)) {\n\t\t\tthrow new Error(`snapshot missing required key \"${key}\"`);\n\t\t}\n\t}\n\tif (typeof data.name !== \"string\") {\n\t\tthrow new TypeError(`snapshot 'name' must be a string`);\n\t}\n\tif (typeof data.nodes !== \"object\" || data.nodes === null || Array.isArray(data.nodes)) {\n\t\tthrow new TypeError(`snapshot 'nodes' must be an object`);\n\t}\n\tif (!Array.isArray(data.edges)) {\n\t\tthrow new TypeError(`snapshot 'edges' must be an array`);\n\t}\n\tif (!Array.isArray(data.subgraphs)) {\n\t\tthrow new TypeError(`snapshot 'subgraphs' must be an array`);\n\t}\n}\n\n/** Recursively sort object keys for deterministic JSON (git-diffable). */\nfunction sortJsonValue(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sortJsonValue);\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\tconst out: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tout[k] = sortJsonValue(obj[k]);\n\t}\n\treturn out;\n}\n\nfunction stableJsonStringify(value: unknown): string {\n\treturn `${JSON.stringify(sortJsonValue(value))}\\n`;\n}\n\nfunction escapeMermaidLabel(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction escapeD2Label(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction d2DirectionFromGraphDirection(direction: GraphDiagramDirection): string {\n\tif (direction === \"TD\") return \"down\";\n\tif (direction === \"BT\") return \"up\";\n\tif (direction === \"RL\") return \"left\";\n\treturn \"right\";\n}\n\n/** Collect deduplicated (from, to) arrows from deps + edges. */\nfunction collectDiagramArrows(described: GraphDescribeOutput): [string, string][] {\n\tconst seen = new Set<string>();\n\tconst arrows: [string, string][] = [];\n\tfunction add(from: string, to: string): void {\n\t\tconst key = `${from}\\0${to}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tarrows.push([from, to]);\n\t}\n\tfor (const [path, info] of Object.entries(described.nodes)) {\n\t\tconst deps: string[] | undefined = (info as Record<string, unknown>).deps as\n\t\t\t| string[]\n\t\t\t| undefined;\n\t\tif (deps) {\n\t\t\tfor (const dep of deps) add(dep, path);\n\t\t}\n\t}\n\tfor (const edge of described.edges) add(edge.from, edge.to);\n\treturn arrows;\n}\n\nfunction normalizeDiagramDirection(direction: unknown): GraphDiagramDirection {\n\tif (direction === undefined) return \"LR\";\n\tif (direction === \"TD\" || direction === \"LR\" || direction === \"BT\" || direction === \"RL\") {\n\t\treturn direction;\n\t}\n\tthrow new Error(\n\t\t`invalid diagram direction ${String(direction)}; expected one of: TD, LR, BT, RL`,\n\t);\n}\n\nfunction escapeRegexLiteral(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet re = \"^\";\n\tfor (let i = 0; i < pattern.length; i += 1) {\n\t\tconst ch = pattern[i]!;\n\t\tif (ch === \"*\") {\n\t\t\tre += \".*\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"?\") {\n\t\t\tre += \".\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tconst end = pattern.indexOf(\"]\", i + 1);\n\t\t\tif (end <= i + 1) {\n\t\t\t\tre += \"\\\\[\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet cls = pattern.slice(i + 1, end);\n\t\t\tif (cls.startsWith(\"!\")) cls = `^${cls.slice(1)}`;\n\t\t\tcls = cls.replace(/\\\\/g, \"\\\\\\\\\");\n\t\t\tre += `[${cls}]`;\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tre += escapeRegexLiteral(ch);\n\t}\n\tre += \"$\";\n\treturn new RegExp(re);\n}\n\n/** Fixed-capacity ring buffer — O(1) push and eviction. */\nclass RingBuffer<T> {\n\tprivate buf: (T | undefined)[];\n\tprivate head = 0;\n\tprivate _size = 0;\n\tconstructor(private capacity: number) {\n\t\tthis.buf = new Array(capacity);\n\t}\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\tpush(item: T): void {\n\t\tconst idx = (this.head + this._size) % this.capacity;\n\t\tthis.buf[idx] = item;\n\t\tif (this._size < this.capacity) this._size++;\n\t\telse this.head = (this.head + 1) % this.capacity;\n\t}\n\ttoArray(): T[] {\n\t\tconst result: T[] = [];\n\t\tfor (let i = 0; i < this._size; i++) result.push(this.buf[(this.head + i) % this.capacity]!);\n\t\treturn result;\n\t}\n}\n\nconst SPY_ANSI_THEME: Required<GraphSpyTheme> = {\n\tdata: \"\\u001b[32m\",\n\tdirty: \"\\u001b[33m\",\n\tresolved: \"\\u001b[36m\",\n\tcomplete: \"\\u001b[34m\",\n\terror: \"\\u001b[31m\",\n\tderived: \"\\u001b[35m\",\n\tpath: \"\\u001b[90m\",\n\treset: \"\\u001b[0m\",\n};\n\nconst SPY_NO_COLOR_THEME: Required<GraphSpyTheme> = {\n\tdata: \"\",\n\tdirty: \"\",\n\tresolved: \"\",\n\tcomplete: \"\",\n\terror: \"\",\n\tderived: \"\",\n\tpath: \"\",\n\treset: \"\",\n};\n\nfunction describeData(value: unknown): string {\n\tif (typeof value === \"string\") return JSON.stringify(value);\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || value == null)\n\t\treturn String(value);\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction resolveSpyTheme(theme: GraphSpyOptions[\"theme\"]): Required<GraphSpyTheme> {\n\tif (theme === \"none\") return SPY_NO_COLOR_THEME;\n\tif (theme === \"ansi\" || theme == null) return SPY_ANSI_THEME;\n\treturn {\n\t\tdata: theme.data ?? \"\",\n\t\tdirty: theme.dirty ?? \"\",\n\t\tresolved: theme.resolved ?? \"\",\n\t\tcomplete: theme.complete ?? \"\",\n\t\terror: theme.error ?? \"\",\n\t\tderived: theme.derived ?? \"\",\n\t\tpath: theme.path ?? \"\",\n\t\treset: theme.reset ?? \"\",\n\t};\n}\n\n/** {@link Graph.observe} on a single node or meta path — sink receives plain message batches. */\nexport type GraphObserveOne = {\n\tsubscribe(sink: NodeSink): () => void;\n\t/** Send messages upstream toward the observed node's sources (e.g. PAUSE/RESUME). */\n\tup(messages: Messages): void;\n};\n\n/**\n * {@link Graph.observe} on the whole graph — sink receives each batch with the qualified source path.\n * Subscription order follows code-point sort on paths (mounts-first walk, then sorted locals/meta).\n */\nexport type GraphObserveAll = {\n\tsubscribe(sink: (nodePath: string, messages: Messages) => void): () => void;\n\t/** Send messages upstream toward a specific observed node's sources (e.g. PAUSE/RESUME). */\n\tup(path: string, messages: Messages): void;\n};\n\n/** Options for structured observation modes on {@link Graph.observe}. */\nexport type ObserveOptions = {\n\tactor?: Actor;\n\t/** Return an {@link ObserveResult} accumulator instead of a raw stream. */\n\tstructured?: boolean;\n\t/** Include causal trace info (which dep triggered each recomputation). */\n\tcausal?: boolean;\n\t/** Include timestamps and batch context on each event. */\n\ttimeline?: boolean;\n\t/** Include per-evaluation dep snapshots for compute/derived nodes. */\n\tderived?: boolean;\n};\n\n/** Accumulated observation result (structured mode). */\nexport type ObserveResult<T = unknown> = {\n\t/** Latest DATA value by observed path. */\n\treadonly values: Record<string, T>;\n\t/** Number of DIRTY messages received. */\n\treadonly dirtyCount: number;\n\t/** Number of RESOLVED messages received. */\n\treadonly resolvedCount: number;\n\t/** All events in order. */\n\treadonly events: ObserveEvent[];\n\t/** True if COMPLETE received without prior ERROR. */\n\treadonly completedCleanly: boolean;\n\t/** True if ERROR received. */\n\treadonly errored: boolean;\n\t/** Stop observing. */\n\tdispose(): void;\n};\n\n/** A single event in the structured observation log. */\nexport type ObserveEvent = {\n\ttype: \"data\" | \"dirty\" | \"resolved\" | \"complete\" | \"error\" | \"derived\";\n\tpath?: string;\n\tdata?: unknown;\n\ttimestamp_ns?: number;\n\tin_batch?: boolean;\n\ttrigger_dep_index?: number;\n\ttrigger_dep_name?: string;\n\t/**\n\t * V0 version of the triggering dep at observation time (§6.0b).\n\t * This is the dep's post-emission version (after its own `advanceVersion`),\n\t * not the pre-emission version that caused this node's recomputation.\n\t */\n\ttrigger_version?: { id: string; version: number };\n\tdep_values?: unknown[];\n};\n\n/** Built-in color presets for {@link Graph.spy}. */\nexport type GraphSpyThemeName = \"none\" | \"ansi\";\n\n/** ANSI/style overrides for {@link Graph.spy} event rendering. */\nexport type GraphSpyTheme = Partial<Record<ObserveEvent[\"type\"] | \"path\" | \"reset\", string>>;\n\n/** Options for {@link Graph.spy}. */\nexport type GraphSpyOptions = ObserveOptions & {\n\t/** Observe one path; omit for graph-wide mode. */\n\tpath?: string;\n\t/** Keep only these event types in spy output. */\n\tincludeTypes?: ObserveEvent[\"type\"][];\n\t/** Exclude these event types from spy output. */\n\texcludeTypes?: ObserveEvent[\"type\"][];\n\t/** Built-in color preset (`ansi` default) or explicit color tokens. */\n\ttheme?: GraphSpyThemeName | GraphSpyTheme;\n\t/** One-line `pretty` output (default) or JSON-per-event. */\n\tformat?: \"pretty\" | \"json\";\n\t/** Optional sink for rendered lines (`console.log` by default). */\n\tlogger?: (line: string, event: ObserveEvent) => void;\n};\n\n/** Handle returned by {@link Graph.spy}. */\nexport type GraphSpyHandle = {\n\treadonly result: ObserveResult;\n\tdispose(): void;\n};\n\n/** Options for {@link Graph.dumpGraph}. */\nexport type GraphDumpOptions = {\n\tactor?: Actor;\n\tfilter?: DescribeFilter;\n\tformat?: \"pretty\" | \"json\";\n\tindent?: number;\n\tincludeEdges?: boolean;\n\tincludeSubgraphs?: boolean;\n\tlogger?: (text: string) => void;\n};\n\nfunction assertLocalName(name: string, graphName: string, label: string): void {\n\tif (name === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": ${label} name must be non-empty`);\n\t}\n}\n\nfunction assertNoPathSep(name: string, graphName: string, label: string): void {\n\tif (name.includes(PATH_SEP)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} \"${name}\" must not contain '${PATH_SEP}' (path separator)`,\n\t\t);\n\t}\n}\n\nfunction assertNotReservedMetaSegment(name: string, graphName: string, label: string): void {\n\tif (name === GRAPH_META_SEGMENT) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} name \"${GRAPH_META_SEGMENT}\" is reserved for meta companion paths`,\n\t\t);\n\t}\n}\n\n/** `connect` / `disconnect` endpoints must be registered graph nodes, not meta paths (graphrefly-py parity). */\nfunction assertConnectPathNotMeta(path: string, graphName: string): void {\n\tif (path.split(PATH_SEP).includes(GRAPH_META_SEGMENT)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": connect/disconnect endpoints must be registered graph nodes, not meta paths (got \"${path}\")`,\n\t\t);\n\t}\n}\n\nfunction splitPath(path: string, graphName: string): string[] {\n\tif (path === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": resolve path must be non-empty`);\n\t}\n\tconst segments = path.split(PATH_SEP);\n\tfor (const s of segments) {\n\t\tif (s === \"\") {\n\t\t\tthrow new Error(`Graph \"${graphName}\": resolve path has empty segment`);\n\t\t}\n\t}\n\treturn segments;\n}\n\n/** Canonical string key for an edge pair (deterministic, splittable). */\nfunction edgeKey(from: string, to: string): string {\n\treturn `${from}\\t${to}`;\n}\n\nfunction parseEdgeKey(key: string): [string, string] {\n\tconst i = key.indexOf(\"\\t\");\n\treturn [key.slice(0, i), key.slice(i + 1)];\n}\n\n/**\n * Lifecycle-destructive message types that meta companion nodes ignore\n * during graph-wide signal propagation (spec §2.3 Companion lifecycle).\n * TEARDOWN: parent already cascades explicitly.\n * INVALIDATE/COMPLETE/ERROR: meta stores outlive these lifecycle events.\n * To target a meta node directly, call `meta.down(...)` on it.\n */\nconst META_FILTERED_TYPES = new Set([TEARDOWN, INVALIDATE, COMPLETE, ERROR]);\n\n/** Strip lifecycle-destructive messages; returns empty array when nothing remains. */\nfunction filterMetaMessages(messages: Messages): Messages {\n\tconst kept = messages.filter((m) => !META_FILTERED_TYPES.has(m[0]));\n\treturn kept as unknown as Messages;\n}\n\n/** TEARDOWN every node in a mounted graph tree (depth-first into mounts). */\nfunction teardownMountedGraph(root: Graph): void {\n\tfor (const child of root._mounts.values()) {\n\t\tteardownMountedGraph(child);\n\t}\n\tfor (const n of root._nodes.values()) {\n\t\tn.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n}\n\n/**\n * Named container for nodes and explicit edges (GRAPHREFLY-SPEC §3.1–§3.7).\n *\n * Qualified paths use `::` as the segment separator (for example `parent::child::node`).\n *\n * Edges are pure wires: `connect` only validates wiring — the target must already list the source in\n * its dependency array; no transforms run on the edge.\n *\n * @example\n * ```ts\n * import { Graph, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * g.add(\"counter\", state(0));\n * ```\n *\n * @category graph\n */\nexport class Graph {\n\tprivate static readonly _factories: Array<{\n\t\tpattern: string;\n\t\tre: RegExp;\n\t\tfactory: GraphNodeFactory;\n\t}> = [];\n\n\treadonly name: string;\n\treadonly opts: Readonly<GraphOptions>;\n\t/** @internal — exposed for {@link teardownMountedGraph} and cross-graph helpers. */\n\treadonly _nodes = new Map<string, Node>();\n\tprivate readonly _edges = new Set<string>();\n\t/** @internal — exposed for {@link teardownMountedGraph}. */\n\treadonly _mounts = new Map<string, Graph>();\n\tprivate readonly _autoCheckpointDisposers = new Set<() => void>();\n\tprivate _defaultVersioningLevel: VersioningLevel | undefined;\n\n\tstatic registerFactory(pattern: string, factory: GraphNodeFactory): void {\n\t\tif (!pattern) {\n\t\t\tthrow new Error(\"Graph.registerFactory requires a non-empty pattern\");\n\t\t}\n\t\tGraph.unregisterFactory(pattern);\n\t\tGraph._factories.push({ pattern, re: globToRegex(pattern), factory });\n\t}\n\n\tstatic unregisterFactory(pattern: string): void {\n\t\tconst i = Graph._factories.findIndex((entry) => entry.pattern === pattern);\n\t\tif (i >= 0) Graph._factories.splice(i, 1);\n\t}\n\n\t/**\n\t * @param name - Non-empty graph id (must not contain `::`).\n\t * @param opts - Reserved for future hooks; currently unused.\n\t */\n\tconstructor(name: string, opts?: GraphOptions) {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(\"Graph name must be non-empty\");\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\tthrow new Error(`Graph name must not contain '${PATH_SEP}' (got \"${name}\")`);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.opts = opts ?? {};\n\t}\n\n\tprivate static _factoryForPath(path: string): GraphNodeFactory | undefined {\n\t\tfor (let i = Graph._factories.length - 1; i >= 0; i -= 1) {\n\t\t\tconst entry = Graph._factories[i]!;\n\t\t\tif (entry.re.test(path)) return entry.factory;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate static _ownerForPath(root: Graph, path: string): [Graph, string] {\n\t\tconst segments = path.split(PATH_SEP);\n\t\tconst local = segments.pop();\n\t\tif (local == null || local.length === 0) {\n\t\t\tthrow new Error(`invalid snapshot path \"${path}\"`);\n\t\t}\n\t\tlet owner = root;\n\t\tfor (const seg of segments) {\n\t\t\tconst next = owner._mounts.get(seg);\n\t\t\tif (!next) throw new Error(`unknown mount \"${seg}\" in path \"${path}\"`);\n\t\t\towner = next;\n\t\t}\n\t\treturn [owner, local];\n\t}\n\n\t/**\n\t * Graphs reachable from this instance via nested {@link Graph.mount} (includes `this`).\n\t */\n\tprivate _graphsReachableViaMounts(seen = new Set<Graph>()): Set<Graph> {\n\t\tif (seen.has(this)) return seen;\n\t\tseen.add(this);\n\t\tfor (const child of this._mounts.values()) {\n\t\t\tchild._graphsReachableViaMounts(seen);\n\t\t}\n\t\treturn seen;\n\t}\n\n\t/**\n\t * Resolve an endpoint: returns `[owningGraph, localName, node]`.\n\t * Accepts both local names and `::` qualified paths.\n\t */\n\tprivate _resolveEndpoint(path: string): [Graph, string, Node] {\n\t\tif (!path.includes(PATH_SEP)) {\n\t\t\tconst n = this._nodes.get(path);\n\t\t\tif (!n) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${path}\"`);\n\t\t\t}\n\t\t\treturn [this, path, n];\n\t\t}\n\t\tconst segments = splitPath(path, this.name);\n\t\treturn this._resolveEndpointFromSegments(segments, path);\n\t}\n\n\tprivate _resolveEndpointFromSegments(\n\t\tsegments: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return [this, head, n];\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${head}\" (from path \"${fullPath}\")`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaEndpointKeys(localN, head, rest, fullPath);\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\t\treturn child._resolveEndpointFromSegments(rest, fullPath);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Node registry\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Registers a node under a local name. Fails if the name is already used,\n\t * reserved by a mount, or the same node instance is already registered.\n\t *\n\t * @param name - Local key (no `::`).\n\t * @param node - Node instance to own.\n\t */\n\tadd(name: string, node: Node): void {\n\t\tassertLocalName(name, this.name, \"add\");\n\t\tassertNoPathSep(name, this.name, \"add\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"node\");\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": name \"${name}\" is already a mount point`);\n\t\t}\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node \"${name}\" already exists`);\n\t\t}\n\t\tfor (const [existingName, existing] of this._nodes) {\n\t\t\tif (existing === node) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": node instance already registered as \"${existingName}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._nodes.set(name, node);\n\t\tif (node instanceof NodeImpl) {\n\t\t\tnode._assignRegistryName(name);\n\t\t\tif (this._defaultVersioningLevel != null) {\n\t\t\t\tnode._applyVersioning(this._defaultVersioningLevel);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Set a default versioning level for all nodes added to this graph (roadmap §6.0).\n\t *\n\t * Nodes already registered are retroactively upgraded. Nodes added later via\n\t * {@link add} will inherit this level unless they already have versioning.\n\t *\n\t * **Scope:** Does not propagate to mounted subgraphs. Call `setVersioning`\n\t * on each child graph separately if needed.\n\t *\n\t * @param level - `0` for V0, `1` for V1, or `undefined` to clear.\n\t */\n\tsetVersioning(level: VersioningLevel | undefined): void {\n\t\tthis._defaultVersioningLevel = level;\n\t\tif (level == null) return;\n\t\tfor (const n of this._nodes.values()) {\n\t\t\tif (n instanceof NodeImpl) {\n\t\t\t\tn._applyVersioning(level);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters a node or unmounts a subgraph, drops incident edges, and sends\n\t * `[[TEARDOWN]]` to the removed node or recursively through the mounted subtree (§3.2).\n\t *\n\t * @param name - Local mount or node name.\n\t */\n\tremove(name: string): void {\n\t\tassertLocalName(name, this.name, \"remove\");\n\t\tassertNoPathSep(name, this.name, \"remove\");\n\n\t\t// Case 1: unmount a subgraph\n\t\tconst child = this._mounts.get(name);\n\t\tif (child) {\n\t\t\tthis._mounts.delete(name);\n\t\t\t// Drop edges touching this mount name or qualified paths under it.\n\t\t\tconst prefix = `${name}${PATH_SEP}`;\n\t\t\tfor (const key of [...this._edges]) {\n\t\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\t\tif (from === name || to === name || from.startsWith(prefix) || to.startsWith(prefix)) {\n\t\t\t\t\tthis._edges.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tteardownMountedGraph(child);\n\t\t\treturn;\n\t\t}\n\n\t\t// Case 2: remove a local node\n\t\tconst node = this._nodes.get(name);\n\t\tif (!node) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node or mount \"${name}\"`);\n\t\t}\n\t\tthis._nodes.delete(name);\n\t\tfor (const key of [...this._edges]) {\n\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\tif (from === name || to === name) this._edges.delete(key);\n\t\t}\n\t\tnode.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n\n\t/**\n\t * Returns a node by local name or `::` qualified path.\n\t * Local names are looked up directly; paths with `::` delegate to {@link resolve}.\n\t *\n\t * @param name - Local name or qualified path.\n\t */\n\tnode(name: string): Node {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node name must be non-empty`);\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\treturn this.resolve(name);\n\t\t}\n\t\tconst n = this._nodes.get(name);\n\t\tif (!n) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${name}\"`);\n\t\t}\n\t\treturn n;\n\t}\n\n\t/**\n\t * Reads `graph.node(name).get()` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @returns Cached value or `undefined`.\n\t */\n\tget(name: string): unknown {\n\t\treturn this.node(name).get();\n\t}\n\n\t/**\n\t * Shorthand for `graph.node(name).down([[DATA, value]], { actor })` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @param value - Next `DATA` payload.\n\t * @param options - Optional `actor` and `internal` guard bypass.\n\t */\n\tset(name: string, value: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[DATA, value]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Edges\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Record a wire from `fromPath` → `toPath` (§3.3). Accepts local names or\n\t * `::` qualified paths. The target must be a {@link NodeImpl} whose `_deps`\n\t * includes the source node (same reference). Idempotent.\n\t *\n\t * Same-owner edges are stored on the owning child graph; cross-subgraph edges\n\t * are stored on this (parent) graph's registry.\n\t *\n\t * @param fromPath - Source endpoint (local or qualified).\n\t * @param toPath - Target endpoint whose deps already include the source node.\n\t */\n\tconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": connect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal, fromNode] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal, toNode] = this._resolveEndpoint(toPath);\n\n\t\tif (fromNode === toNode) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot connect a node to itself`);\n\t\t}\n\n\t\tif (!(toNode instanceof NodeImpl)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) requires the target to be a graphrefly NodeImpl so deps can be validated`,\n\t\t\t);\n\t\t}\n\t\tif (!toNode._deps.includes(fromNode)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) — target must include source in its constructor deps (same node reference)`,\n\t\t\t);\n\t\t}\n\n\t\tif (fromGraph === toGraph) {\n\t\t\t// Same-owner: store on the child graph\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tfromGraph._edges.add(key);\n\t\t} else {\n\t\t\t// Cross-subgraph: store on this (parent) graph\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tthis._edges.add(key);\n\t\t}\n\t}\n\n\t/**\n\t * Remove a registered edge (§3.3). Accepts local names or `::` qualified paths.\n\t *\n\t * **Registry-only (§C resolved):** This drops the edge from the graph's edge\n\t * registry only. It does **not** mutate the target node's constructor-time\n\t * dependency list, bitmasks, or upstream subscriptions. Message flow follows\n\t * constructor-time deps, not the edge registry. For runtime dep rewiring, use\n\t * {@link dynamicNode}.\n\t *\n\t * @param fromPath - Registered edge tail.\n\t * @param toPath - Registered edge head.\n\t */\n\tdisconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": disconnect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal] = this._resolveEndpoint(toPath);\n\n\t\tif (fromGraph === toGraph) {\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tif (!fromGraph._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tif (!this._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns registered `[from, to]` edge pairs (read-only snapshot).\n\t *\n\t * @returns Edge pairs recorded on this graph instance’s local `_edges` set.\n\t */\n\tedges(): ReadonlyArray<[string, string]> {\n\t\tconst result: [string, string][] = [];\n\t\tfor (const key of this._edges) {\n\t\t\tresult.push(parseEdgeKey(key));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Composition\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Embed a child graph at a local mount name (§3.4). Child nodes are reachable via\n\t * {@link Graph.resolve} using `::` delimited paths (§3.5). Lifecycle\n\t * {@link Graph.signal} visits mounted subgraphs recursively.\n\t *\n\t * Rejects: same name as existing node or mount, self-mount, mount cycles,\n\t * and the same child graph instance mounted twice on one parent.\n\t *\n\t * @param name - Local mount point.\n\t * @param child - Nested `Graph` instance.\n\t */\n\tmount(name: string, child: Graph): void {\n\t\tassertLocalName(name, this.name, \"mount\");\n\t\tassertNoPathSep(name, this.name, \"mount\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"mount\");\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": cannot mount at \"${name}\" — node with that name exists`,\n\t\t\t);\n\t\t}\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount \"${name}\" already exists`);\n\t\t}\n\t\tif (child === this) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot mount a graph into itself`);\n\t\t}\n\t\t// Reject same child instance mounted twice on this parent.\n\t\tfor (const existing of this._mounts.values()) {\n\t\t\tif (existing === child) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": this child graph is already mounted on this graph`);\n\t\t\t}\n\t\t}\n\t\tif (child._graphsReachableViaMounts().has(this)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount(\"${name}\", …) would create a mount cycle`);\n\t\t}\n\t\tthis._mounts.set(name, child);\n\t}\n\n\t/**\n\t * Look up a node by qualified path (§3.5). Segments are separated by `::`.\n\t *\n\t * If the first segment equals this graph's {@link Graph.name}, it is stripped\n\t * (so `root.resolve(\"app::a\")` works when `root.name === \"app\"`).\n\t *\n\t * @param path - Qualified `::` path or local name.\n\t * @returns The resolved `Node`.\n\t */\n\tresolve(path: string): Node {\n\t\tlet segments = splitPath(path, this.name);\n\t\tif (segments[0] === this.name) {\n\t\t\tsegments = segments.slice(1);\n\t\t\tif (segments.length === 0) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": resolve path ends at graph name only`);\n\t\t\t}\n\t\t}\n\t\treturn this._resolveFromSegments(segments);\n\t}\n\n\tprivate _resolveFromSegments(segments: readonly string[]): Node {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return n;\n\t\t\tif (this._mounts.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": path ends at subgraph \"${head}\" — not a node (GRAPHREFLY-SPEC §3.5)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown name \"${head}\"`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaChainFromNode(localN, rest, segments.join(PATH_SEP));\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\n\t\treturn child.resolve(rest.join(PATH_SEP));\n\t}\n\n\t/**\n\t * Resolve `::__meta__::key` segments from a registered primary node (possibly chained).\n\t */\n\tprivate _resolveMetaChainFromNode(n: Node, parts: readonly string[], fullPath: string): Node {\n\t\tlet current = n;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = p[i + 1] as string;\n\t\t\tconst next = current.meta[key];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown meta \"${key}\" in path \"${fullPath}\"`);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate _resolveMetaEndpointKeys(\n\t\tbaseNode: Node,\n\t\tbaseLocalKey: string,\n\t\tparts: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tlet current = baseNode;\n\t\tlet localKey = baseLocalKey;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst metaKey = p[i + 1] as string;\n\t\t\tconst next = current.meta[metaKey];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": unknown meta \"${metaKey}\" on node (in \"${fullPath}\")`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlocalKey = `${localKey}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${metaKey}`;\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn [this, localKey, current];\n\t}\n\n\t/**\n\t * Deliver a message batch to every registered node in this graph and, recursively,\n\t * in mounted child graphs (§3.7). Recurses into mounts first, then delivers to\n\t * local nodes (sorted by name). Each {@link Node} receives at most one delivery\n\t * per call (deduped by reference).\n\t *\n\t * Companion `meta` nodes receive the same batch for control-plane types (e.g.\n\t * PAUSE) that the primary does not forward. **TEARDOWN-only** batches skip the\n\t * extra meta pass — the primary’s `down()` already cascades TEARDOWN to meta.\n\t *\n\t * @param messages - Batch to deliver to every registered node (and mounts, recursively).\n\t * @param options - Optional `actor` / `internal` for transport.\n\t */\n\tsignal(messages: Messages, options?: GraphActorOptions): void {\n\t\tthis._signalDeliver(messages, options ?? {}, new Set());\n\t}\n\n\tprivate _signalDeliver(messages: Messages, opts: GraphActorOptions, vis: Set<Node>): void {\n\t\tfor (const sub of this._mounts.values()) {\n\t\t\tsub._signalDeliver(messages, opts, vis);\n\t\t}\n\t\tconst internal = opts.internal === true;\n\t\tconst downOpts: NodeTransportOptions = internal\n\t\t\t? { internal: true }\n\t\t\t: { actor: opts.actor, delivery: \"signal\" };\n\t\tconst metaMessages = filterMetaMessages(messages);\n\t\tfor (const localName of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(localName)!;\n\t\t\tif (vis.has(n)) continue;\n\t\t\tvis.add(n);\n\t\t\tn.down(messages, downOpts);\n\t\t\tif (metaMessages.length === 0) continue;\n\t\t\tthis._signalMetaSubtree(n, metaMessages, vis, downOpts);\n\t\t}\n\t}\n\n\tprivate _signalMetaSubtree(\n\t\troot: Node,\n\t\tmessages: Messages,\n\t\tvis: Set<Node>,\n\t\tdownOpts: NodeTransportOptions,\n\t): void {\n\t\tfor (const mk of Object.keys(root.meta).sort()) {\n\t\t\tconst mnode = root.meta[mk];\n\t\t\tif (vis.has(mnode)) continue;\n\t\t\tvis.add(mnode);\n\t\t\tmnode.down(messages, downOpts);\n\t\t\tthis._signalMetaSubtree(mnode, messages, vis, downOpts);\n\t\t}\n\t}\n\n\t/**\n\t * Static structure snapshot: qualified node keys, edges, mount names (GRAPHREFLY-SPEC §3.6, Appendix B).\n\t *\n\t * @param options - Optional `actor` for guard-scoped visibility and/or `filter` for selective output.\n\t * @returns JSON-shaped describe payload for this graph tree.\n\t *\n\t * @example\n\t * ```ts\n\t * graph.describe() // full snapshot\n\t * graph.describe({ actor: llm }) // guard-scoped\n\t * graph.describe({ filter: { status: \"errored\" } }) // only errored nodes\n\t * graph.describe({ filter: (n) => n.type === \"state\" }) // predicate filter\n\t * ```\n\t */\n\tdescribe(options?: { actor?: Actor; filter?: DescribeFilter }): GraphDescribeOutput {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\tconst nodeToPath = new Map<Node, string>();\n\t\tfor (const [p, n] of targets) {\n\t\t\tnodeToPath.set(n, p);\n\t\t}\n\t\tconst nodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const [p, n] of targets) {\n\t\t\tif (actor != null && !n.allowsObserve(actor)) continue;\n\t\t\tconst raw = describeNode(n);\n\t\t\tconst deps =\n\t\t\t\tn instanceof NodeImpl ? n._deps.map((d) => nodeToPath.get(d) ?? d.name ?? \"\") : [];\n\t\t\tconst { name: _name, ...rest } = raw;\n\t\t\tconst entry: DescribeNodeOutput = { ...rest, deps };\n\t\t\tif (filter != null) {\n\t\t\t\tif (typeof filter === \"function\") {\n\t\t\t\t\tconst fn = filter as\n\t\t\t\t\t\t| ((nodePath: string, node: DescribeNodeOutput) => boolean)\n\t\t\t\t\t\t| ((node: DescribeNodeOutput) => boolean);\n\t\t\t\t\tconst pass =\n\t\t\t\t\t\tfn.length >= 2\n\t\t\t\t\t\t\t? (fn as (nodePath: string, node: DescribeNodeOutput) => boolean)(p, entry)\n\t\t\t\t\t\t\t: (fn as (node: DescribeNodeOutput) => boolean)(entry);\n\t\t\t\t\tif (!pass) continue;\n\t\t\t\t} else {\n\t\t\t\t\tlet match = true;\n\t\t\t\t\tfor (const [fk, fv] of Object.entries(filter)) {\n\t\t\t\t\t\tconst normalizedKey =\n\t\t\t\t\t\t\tfk === \"deps_includes\" ? \"depsIncludes\" : fk === \"meta_has\" ? \"metaHas\" : fk;\n\t\t\t\t\t\tif (normalizedKey === \"depsIncludes\") {\n\t\t\t\t\t\t\tif (!entry.deps.includes(String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (normalizedKey === \"metaHas\") {\n\t\t\t\t\t\t\tif (!Object.hasOwn(entry.meta, String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((entry as Record<string, unknown>)[normalizedKey] !== fv) {\n\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) continue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodes[p] = entry;\n\t\t}\n\t\tconst nodeKeys = new Set(Object.keys(nodes));\n\t\tlet edges = this._collectAllEdges(\"\");\n\t\tif (actor != null || filter != null) {\n\t\t\tedges = edges.filter((e) => nodeKeys.has(e.from) && nodeKeys.has(e.to));\n\t\t}\n\t\tedges.sort((a, b) => {\n\t\t\tif (a.from < b.from) return -1;\n\t\t\tif (a.from > b.from) return 1;\n\t\t\tif (a.to < b.to) return -1;\n\t\t\tif (a.to > b.to) return 1;\n\t\t\treturn 0;\n\t\t});\n\t\tconst allSubgraphs = this._collectSubgraphs(\"\");\n\t\tconst subgraphs =\n\t\t\tactor != null || filter != null\n\t\t\t\t? allSubgraphs.filter((sg) => {\n\t\t\t\t\t\tconst prefix = `${sg}${PATH_SEP}`;\n\t\t\t\t\t\treturn [...nodeKeys].some((k) => k === sg || k.startsWith(prefix));\n\t\t\t\t\t})\n\t\t\t\t: allSubgraphs;\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t};\n\t}\n\n\tprivate _collectSubgraphs(prefix: string): string[] {\n\t\tconst out: string[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst q = prefix === \"\" ? m : `${prefix}${m}`;\n\t\t\tout.push(q);\n\t\t\tout.push(...this._mounts.get(m)!._collectSubgraphs(`${q}${PATH_SEP}`));\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _collectAllEdges(prefix: string): { from: string; to: string }[] {\n\t\tconst out: { from: string; to: string }[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tout.push(...this._mounts.get(m)!._collectAllEdges(p2));\n\t\t}\n\t\tfor (const [f, t] of this.edges()) {\n\t\t\tout.push({\n\t\t\t\tfrom: this._qualifyEdgeEndpoint(f, prefix),\n\t\t\t\tto: this._qualifyEdgeEndpoint(t, prefix),\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _qualifyEdgeEndpoint(part: string, prefix: string): string {\n\t\tif (part.includes(PATH_SEP)) return part;\n\t\treturn prefix === \"\" ? part : `${prefix}${PATH_SEP}${part}`;\n\t}\n\n\tprivate _collectObserveTargets(prefix: string, out: [string, Node][]): void {\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tthis._mounts.get(m)!._collectObserveTargets(p2, out);\n\t\t}\n\t\tfor (const loc of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(loc)!;\n\t\t\tconst p = prefix === \"\" ? loc : `${prefix}${PATH_SEP}${loc}`;\n\t\t\tout.push([p, n]);\n\t\t\tthis._appendMetaObserveTargets(p, n, out);\n\t\t}\n\t}\n\n\tprivate _appendMetaObserveTargets(basePath: string, n: Node, out: [string, Node][]): void {\n\t\tfor (const mk of Object.keys(n.meta).sort()) {\n\t\t\tconst m = n.meta[mk];\n\t\t\tconst mp = `${basePath}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${mk}`;\n\t\t\tout.push([mp, m]);\n\t\t\tthis._appendMetaObserveTargets(mp, m, out);\n\t\t}\n\t}\n\n\t/**\n\t * Live message stream from one node (or meta path), or from the whole graph (§3.6).\n\t *\n\t * Overloads: `(path, options?)` for one node; `(options?)` for all nodes. Whole-graph mode\n\t * subscribes in **sorted path order** (code-point order). With structured options\n\t * (`structured`, `timeline`, `causal`, `derived`), returns an {@link ObserveResult}.\n\t * Inspector-gated extras (`causal` / `derived`) require {@link Graph.inspectorEnabled}.\n\t *\n\t * @param pathOrOpts - Qualified `path` string, or omit and pass only `options` for graph-wide observation.\n\t * @param options - Optional `actor`, `structured`, `causal`, `timeline` (inspector-gated).\n\t * @returns `GraphObserveOne`, `GraphObserveAll`, or `ObserveResult` depending on overload/options.\n\t */\n\tobserve(\n\t\tpath: string,\n\t\toptions?: ObserveOptions & {\n\t\t\tstructured?: true;\n\t\t\ttimeline?: true;\n\t\t\tcausal?: true;\n\t\t\tderived?: true;\n\t\t},\n\t): ObserveResult;\n\tobserve(path: string, options?: ObserveOptions): GraphObserveOne;\n\tobserve(\n\t\toptions: ObserveOptions & { structured?: true; timeline?: true; causal?: true; derived?: true },\n\t): ObserveResult;\n\tobserve(options?: ObserveOptions): GraphObserveAll;\n\tobserve(\n\t\tpathOrOpts?: string | ObserveOptions,\n\t\toptions?: ObserveOptions,\n\t): GraphObserveOne | GraphObserveAll | ObserveResult {\n\t\tif (typeof pathOrOpts === \"string\") {\n\t\t\tconst path = pathOrOpts;\n\t\t\tconst actor = options?.actor;\n\t\t\tconst target = this.resolve(path);\n\t\t\tif (actor != null && !target.allowsObserve(actor)) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: path });\n\t\t\t}\n\t\t\tconst wantsStructured =\n\t\t\t\toptions?.structured === true ||\n\t\t\t\toptions?.timeline === true ||\n\t\t\t\toptions?.causal === true ||\n\t\t\t\toptions?.derived === true;\n\t\t\tif (wantsStructured && Graph.inspectorEnabled) {\n\t\t\t\treturn this._createObserveResult(path, target, options);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsubscribe(sink: NodeSink) {\n\t\t\t\t\treturn target.subscribe(sink);\n\t\t\t\t},\n\t\t\t\tup(messages: Messages) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttarget.up?.(messages);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst opts = pathOrOpts as ObserveOptions | undefined;\n\t\tconst actor = opts?.actor;\n\t\tconst wantsStructured =\n\t\t\topts?.structured === true ||\n\t\t\topts?.timeline === true ||\n\t\t\topts?.causal === true ||\n\t\t\topts?.derived === true;\n\t\tif (wantsStructured && Graph.inspectorEnabled) {\n\t\t\treturn this._createObserveResultForAll(opts ?? {});\n\t\t}\n\t\treturn {\n\t\t\tsubscribe: (sink: (nodePath: string, messages: Messages) => void) => {\n\t\t\t\tconst targets: [string, Node][] = [];\n\t\t\t\tthis._collectObserveTargets(\"\", targets);\n\t\t\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\t\t\tconst picked =\n\t\t\t\t\tactor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\t\t\tconst unsubs = picked.map(([p, nd]) =>\n\t\t\t\t\tnd.subscribe((msgs) => {\n\t\t\t\t\t\tsink(p, msgs);\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn () => {\n\t\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\t};\n\t\t\t},\n\t\t\tup: (upPath: string, messages: Messages) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst nd = this.resolve(upPath);\n\t\t\t\t\tnd.up?.(messages);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResult<T>(\n\t\tpath: string,\n\t\ttarget: Node<T>,\n\t\toptions: ObserveOptions,\n\t): ObserveResult<T> {\n\t\tconst timeline = options.timeline === true;\n\t\tconst causal = options.causal === true;\n\t\tconst derived = options.derived === true;\n\t\tconst result: {\n\t\t\tvalues: Record<string, T>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tcompletedCleanly: boolean;\n\t\t\terrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tcompletedCleanly: false,\n\t\t\terrored: false,\n\t\t};\n\n\t\tlet lastTriggerDepIndex: number | undefined;\n\t\tlet lastRunDepValues: unknown[] | undefined;\n\t\tlet detachInspectorHook: (() => void) | undefined;\n\t\tif ((causal || derived) && target instanceof NodeImpl) {\n\t\t\tdetachInspectorHook = target._setInspectorHook((event: NodeInspectorHookEvent) => {\n\t\t\t\tif (event.kind === \"dep_message\") {\n\t\t\t\t\tlastTriggerDepIndex = event.depIndex;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlastRunDepValues = [...event.depValues];\n\t\t\t\tif (derived) {\n\t\t\t\t\tresult.events.push({\n\t\t\t\t\t\ttype: \"derived\",\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tdep_values: [...event.depValues],\n\t\t\t\t\t\t...(timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {}),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst unsub = target.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst t = m[0];\n\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\tconst withCausal =\n\t\t\t\t\tcausal && lastRunDepValues != null\n\t\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\t\tconst triggerDep =\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex != null &&\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex >= 0 &&\n\t\t\t\t\t\t\t\t\ttarget instanceof NodeImpl\n\t\t\t\t\t\t\t\t\t\t? target._deps[lastTriggerDepIndex]\n\t\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\t\tconst tv = triggerDep?.v;\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\ttrigger_dep_index: lastTriggerDepIndex,\n\t\t\t\t\t\t\t\t\ttrigger_dep_name: triggerDep?.name,\n\t\t\t\t\t\t\t\t\t...(tv != null ? { trigger_version: { id: tv.id, version: tv.version } } : {}),\n\t\t\t\t\t\t\t\t\tdep_values: [...lastRunDepValues],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t})()\n\t\t\t\t\t\t: {};\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tresult.values[path] = m[1] as T;\n\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base, ...withCausal });\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base, ...withCausal });\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!result.errored) result.completedCleanly = true;\n\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tresult.errored = true;\n\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget completedCleanly() {\n\t\t\t\treturn result.completedCleanly;\n\t\t\t},\n\t\t\tget errored() {\n\t\t\t\treturn result.errored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tunsub();\n\t\t\t\tdetachInspectorHook?.();\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResultForAll(options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline === true;\n\t\tconst result: {\n\t\t\tvalues: Record<string, unknown>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tcompletedCleanly: boolean;\n\t\t\terrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tcompletedCleanly: false,\n\t\t\terrored: false,\n\t\t};\n\t\tconst actor = options.actor;\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst picked = actor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\tconst unsubs = picked.map(([path, nd]) =>\n\t\t\tnd.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tconst t = m[0];\n\t\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tresult.values[path] = m[1];\n\t\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base });\n\t\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\tif (!result.errored) result.completedCleanly = true;\n\t\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tresult.errored = true;\n\t\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget completedCleanly() {\n\t\t\t\treturn result.completedCleanly;\n\t\t\t},\n\t\t\tget errored() {\n\t\t\t\treturn result.errored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Convenience live debugger over {@link Graph.observe}. Logs protocol events as they flow.\n\t *\n\t * Supports one-node (`path`) and graph-wide modes, event filtering, and JSON/pretty rendering.\n\t * Color themes are built in (`ansi` / `none`) to avoid external dependencies.\n\t *\n\t * @param options - Spy configuration.\n\t * @returns Disposable handle plus a structured observation accumulator.\n\t */\n\tspy(options: GraphSpyOptions = {}): GraphSpyHandle {\n\t\tconst include = options.includeTypes ? new Set(options.includeTypes) : null;\n\t\tconst exclude = options.excludeTypes ? new Set(options.excludeTypes) : null;\n\t\tconst theme = resolveSpyTheme(options.theme);\n\t\tconst format = options.format ?? \"pretty\";\n\t\tconst logger = options.logger ?? ((line: string) => console.log(line));\n\n\t\tconst shouldLog = (type: ObserveEvent[\"type\"]): boolean => {\n\t\t\tif (include?.has(type) === false) return false;\n\t\t\tif (exclude?.has(type) === true) return false;\n\t\t\treturn true;\n\t\t};\n\n\t\tconst renderEvent = (event: ObserveEvent): string => {\n\t\t\tif (format === \"json\") {\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.stringify(event);\n\t\t\t\t} catch {\n\t\t\t\t\treturn JSON.stringify({\n\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\tpath: event.path,\n\t\t\t\t\t\tdata: \"[unserializable]\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst color = theme[event.type] ?? \"\";\n\t\t\tconst pathPart = event.path ? `${theme.path}${event.path}${theme.reset} ` : \"\";\n\t\t\tconst dataPart = event.data !== undefined ? ` ${describeData(event.data)}` : \"\";\n\t\t\tconst triggerPart =\n\t\t\t\tevent.trigger_dep_name != null\n\t\t\t\t\t? ` <- ${event.trigger_dep_name}`\n\t\t\t\t\t: event.trigger_dep_index != null\n\t\t\t\t\t\t? ` <- #${event.trigger_dep_index}`\n\t\t\t\t\t\t: \"\";\n\t\t\tconst batchPart = event.in_batch ? \" [batch]\" : \"\";\n\t\t\treturn `${pathPart}${color}${event.type.toUpperCase()}${theme.reset}${dataPart}${triggerPart}${batchPart}`;\n\t\t};\n\n\t\tif (!Graph.inspectorEnabled) {\n\t\t\tconst timeline = options.timeline ?? true;\n\t\t\tconst acc: {\n\t\t\t\tvalues: Record<string, unknown>;\n\t\t\t\tdirtyCount: number;\n\t\t\t\tresolvedCount: number;\n\t\t\t\tevents: ObserveEvent[];\n\t\t\t\tcompletedCleanly: boolean;\n\t\t\t\terrored: boolean;\n\t\t\t} = {\n\t\t\t\tvalues: {},\n\t\t\t\tdirtyCount: 0,\n\t\t\t\tresolvedCount: 0,\n\t\t\t\tevents: [],\n\t\t\t\tcompletedCleanly: false,\n\t\t\t\terrored: false,\n\t\t\t};\n\t\t\tlet stop: () => void = () => {};\n\t\t\tconst result: ObserveResult = {\n\t\t\t\tget values() {\n\t\t\t\t\treturn acc.values;\n\t\t\t\t},\n\t\t\t\tget dirtyCount() {\n\t\t\t\t\treturn acc.dirtyCount;\n\t\t\t\t},\n\t\t\t\tget resolvedCount() {\n\t\t\t\t\treturn acc.resolvedCount;\n\t\t\t\t},\n\t\t\t\tget events() {\n\t\t\t\t\treturn acc.events;\n\t\t\t\t},\n\t\t\t\tget completedCleanly() {\n\t\t\t\t\treturn acc.completedCleanly;\n\t\t\t\t},\n\t\t\t\tget errored() {\n\t\t\t\t\treturn acc.errored;\n\t\t\t\t},\n\t\t\t\tdispose() {\n\t\t\t\t\tstop();\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tconst pushEvent = (path: string | undefined, message: Messages[number]) => {\n\t\t\t\tconst t = message[0];\n\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\tlet event: ObserveEvent | undefined;\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tif (path != null) acc.values[path] = message[1];\n\t\t\t\t\tevent = { type: \"data\", ...(path != null ? { path } : {}), data: message[1], ...base };\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tacc.dirtyCount += 1;\n\t\t\t\t\tevent = { type: \"dirty\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tacc.resolvedCount += 1;\n\t\t\t\t\tevent = { type: \"resolved\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!acc.errored) acc.completedCleanly = true;\n\t\t\t\t\tevent = { type: \"complete\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tacc.errored = true;\n\t\t\t\t\tevent = {\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t...(path != null ? { path } : {}),\n\t\t\t\t\t\tdata: message[1],\n\t\t\t\t\t\t...base,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!event) return;\n\t\t\t\tacc.events.push(event);\n\t\t\t\tif (!shouldLog(event.type)) return;\n\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t};\n\n\t\t\tif (options.path != null) {\n\t\t\t\tconst stream = this.observe(options.path, {\n\t\t\t\t\tactor: options.actor,\n\t\t\t\t\tstructured: false,\n\t\t\t\t});\n\t\t\t\tstop = stream.subscribe((messages) => {\n\t\t\t\t\tfor (const m of messages) {\n\t\t\t\t\t\tpushEvent(options.path, m);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst stream = this.observe({ actor: options.actor, structured: false });\n\t\t\t\tstop = stream.subscribe((path, messages) => {\n\t\t\t\t\tfor (const m of messages) {\n\t\t\t\t\t\tpushEvent(path, m);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresult,\n\t\t\t\tdispose() {\n\t\t\t\t\tresult.dispose();\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst structuredObserveOptions = {\n\t\t\tactor: options.actor,\n\t\t\tstructured: true as const,\n\t\t\t...(options.timeline !== false ? { timeline: true as const } : {}),\n\t\t\t...(options.causal ? { causal: true as const } : {}),\n\t\t\t...(options.derived ? { derived: true as const } : {}),\n\t\t};\n\t\tconst result: ObserveResult =\n\t\t\toptions.path != null\n\t\t\t\t? this.observe(options.path, structuredObserveOptions)\n\t\t\t\t: this.observe(structuredObserveOptions);\n\n\t\tlet cursor = 0;\n\t\tconst flushNewEvents = () => {\n\t\t\tconst nextEvents = result.events.slice(cursor);\n\t\t\tcursor = result.events.length;\n\t\t\tfor (const event of nextEvents) {\n\t\t\t\tif (!shouldLog(event.type)) continue;\n\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t}\n\t\t};\n\n\t\tconst stream =\n\t\t\toptions.path != null\n\t\t\t\t? this.observe(options.path, { actor: options.actor, structured: false })\n\t\t\t\t: this.observe({ actor: options.actor, structured: false });\n\n\t\tconst stop =\n\t\t\toptions.path != null\n\t\t\t\t? (stream as GraphObserveOne).subscribe((messages) => {\n\t\t\t\t\t\tif (messages.length > 0) {\n\t\t\t\t\t\t\tflushNewEvents();\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t: (stream as GraphObserveAll).subscribe((_path, messages) => {\n\t\t\t\t\t\tif (messages.length > 0) {\n\t\t\t\t\t\t\tflushNewEvents();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\treturn {\n\t\t\tresult,\n\t\t\tdispose() {\n\t\t\t\tstop();\n\t\t\t\tflushNewEvents();\n\t\t\t\tresult.dispose();\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * CLI/debug-friendly graph dump built on {@link Graph.describe}.\n\t *\n\t * @param options - Optional actor/filter/format toggles.\n\t * @returns Rendered graph text.\n\t */\n\tdumpGraph(options: GraphDumpOptions = {}): string {\n\t\tconst described = this.describe({\n\t\t\tactor: options.actor,\n\t\t\tfilter: options.filter,\n\t\t});\n\t\tconst includeEdges = options.includeEdges ?? true;\n\t\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\t\tif (options.format === \"json\") {\n\t\t\tconst payload: GraphDescribeOutput = {\n\t\t\t\tname: described.name,\n\t\t\t\tnodes: described.nodes,\n\t\t\t\tedges: includeEdges ? described.edges : [],\n\t\t\t\tsubgraphs: includeSubgraphs ? described.subgraphs : [],\n\t\t\t};\n\t\t\tconst text = JSON.stringify(sortJsonValue(payload), null, options.indent ?? 2);\n\t\t\toptions.logger?.(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tconst lines: string[] = [];\n\t\tlines.push(`Graph ${described.name}`);\n\t\tlines.push(\"Nodes:\");\n\t\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\t\tconst n = described.nodes[path]!;\n\t\t\tlines.push(`- ${path} (${n.type}/${n.status}): ${describeData(n.value)}`);\n\t\t}\n\t\tif (includeEdges) {\n\t\t\tlines.push(\"Edges:\");\n\t\t\tfor (const edge of described.edges) {\n\t\t\t\tlines.push(`- ${edge.from} -> ${edge.to}`);\n\t\t\t}\n\t\t}\n\t\tif (includeSubgraphs) {\n\t\t\tlines.push(\"Subgraphs:\");\n\t\t\tfor (const sg of described.subgraphs) {\n\t\t\t\tlines.push(`- ${sg}`);\n\t\t\t}\n\t\t}\n\t\tconst text = lines.join(\"\\n\");\n\t\toptions.logger?.(text);\n\t\treturn text;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Lifecycle & persistence (§3.7–§3.8)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Sends `[[TEARDOWN]]` to all nodes, then clears registries on this graph and every\n\t * mounted subgraph (§3.7). The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\tthis.signal([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tfor (const dispose of [...this._autoCheckpointDisposers]) {\n\t\t\ttry {\n\t\t\t\tdispose();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t\tthis._autoCheckpointDisposers.clear();\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/** Clear structure after parent already signaled TEARDOWN through this subtree. */\n\tprivate _destroyClearOnly(): void {\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/**\n\t * Serializes structure and current values to JSON-shaped data (§3.8). Same information\n\t * as {@link Graph.describe} plus a `version` field for format evolution.\n\t *\n\t * @returns Persistable snapshot with sorted keys.\n\t */\n\tsnapshot(): GraphPersistSnapshot {\n\t\tconst d = this.describe();\n\t\t// Explicit key sorting for deterministic output — don't rely on\n\t\t// describe() iteration order (audit batch-3, §3.8).\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tsortedNodes[key] = d.nodes[key]!;\n\t\t}\n\t\tconst sortedSubgraphs = [...d.subgraphs].sort();\n\t\treturn { ...d, version: 1, nodes: sortedNodes, subgraphs: sortedSubgraphs };\n\t}\n\n\t/**\n\t * Apply persisted values onto an existing graph whose topology matches the snapshot\n\t * (§3.8). Only {@link DescribeNodeOutput.type} `state` and `producer` entries with a\n\t * `value` field are written; `derived` / `operator` / `effect` are skipped so deps\n\t * drive recomputation. Unknown paths are ignored.\n\t *\n\t * @param data - Snapshot envelope with matching `name` and node slices.\n\t * @throws If `data.name` does not equal {@link Graph.name}.\n\t */\n\trestore(data: GraphPersistSnapshot, options?: { only?: string | readonly string[] }): void {\n\t\tparseSnapshotEnvelope(data);\n\t\tif (data.name !== this.name) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": restore snapshot name \"${data.name}\" does not match this graph`,\n\t\t\t);\n\t\t}\n\t\tconst onlyPatterns =\n\t\t\toptions?.only == null\n\t\t\t\t? null\n\t\t\t\t: (Array.isArray(options.only) ? options.only : [options.only]).map((p) => globToRegex(p));\n\t\tfor (const path of Object.keys(data.nodes).sort()) {\n\t\t\tif (onlyPatterns !== null && !onlyPatterns.some((re) => re.test(path))) continue;\n\t\t\tconst slice = data.nodes[path];\n\t\t\tif (slice === undefined || slice.value === undefined) continue;\n\t\t\tif (slice.type === \"derived\" || slice.type === \"operator\" || slice.type === \"effect\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.set(path, slice.value);\n\t\t\t} catch {\n\t\t\t\t/* missing path or set not applicable */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a graph named from the snapshot, optionally runs `build` to register nodes\n\t * and mounts, then {@link Graph.restore} values (§3.8).\n\t *\n\t * @param data - Snapshot envelope (`version` checked).\n\t * @param build - Optional callback to construct topology before values are applied.\n\t * @returns Hydrated `Graph` instance.\n\t */\n\tstatic fromSnapshot(data: GraphPersistSnapshot, build?: (g: Graph) => void): Graph {\n\t\tparseSnapshotEnvelope(data);\n\t\tconst g = new Graph(data.name);\n\t\tif (build) {\n\t\t\tbuild(g);\n\t\t\tg.restore(data);\n\t\t\treturn g;\n\t\t}\n\t\t// Auto-create mount hierarchy from subgraphs.\n\t\tfor (const mount of [...data.subgraphs].sort((a, b) => {\n\t\t\tconst da = a.split(PATH_SEP).length;\n\t\t\tconst db = b.split(PATH_SEP).length;\n\t\t\tif (da !== db) return da - db;\n\t\t\tif (a < b) return -1;\n\t\t\tif (a > b) return 1;\n\t\t\treturn 0;\n\t\t})) {\n\t\t\tconst parts = mount.split(PATH_SEP);\n\t\t\tlet target: Graph = g;\n\t\t\tfor (const seg of parts) {\n\t\t\t\tif (!target._mounts.has(seg)) {\n\t\t\t\t\ttarget.mount(seg, new Graph(seg));\n\t\t\t\t}\n\t\t\t\ttarget = target._mounts.get(seg)!;\n\t\t\t}\n\t\t}\n\n\t\tconst primaryEntries = Object.entries(data.nodes)\n\t\t\t.filter(([path]) => !path.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`))\n\t\t\t.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst pending = new Map(primaryEntries);\n\t\tconst created = new Map<string, Node>();\n\n\t\tlet progressed = true;\n\t\twhile (pending.size > 0 && progressed) {\n\t\t\tprogressed = false;\n\t\t\tfor (const [path, slice] of [...pending.entries()]) {\n\t\t\t\tconst deps = slice?.deps ?? [];\n\t\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\t\t\t\tconst [owner, localName] = Graph._ownerForPath(g, path);\n\t\t\t\tconst meta: Record<string, unknown> = { ...(slice?.meta ?? {}) };\n\t\t\t\tconst factory = Graph._factoryForPath(path);\n\t\t\t\tlet node: Node;\n\t\t\t\tif (slice?.type === \"state\") {\n\t\t\t\t\tnode = stateNode(slice.value, { meta });\n\t\t\t\t} else {\n\t\t\t\t\tif (factory == null) continue;\n\t\t\t\t\tnode = factory(localName, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\ttype: slice.type,\n\t\t\t\t\t\tvalue: slice.value,\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tresolvedDeps: deps.map((dep) => created.get(dep)!),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\towner.add(localName, node);\n\t\t\t\tcreated.set(path, node);\n\t\t\t\tpending.delete(path);\n\t\t\t\tprogressed = true;\n\t\t\t}\n\t\t}\n\t\tif (pending.size > 0) {\n\t\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`Graph.fromSnapshot could not reconstruct nodes without build callback: ${unresolved}. ` +\n\t\t\t\t\t`Register matching factories with Graph.registerFactory(pattern, factory).`,\n\t\t\t);\n\t\t}\n\t\tfor (const edge of data.edges) {\n\t\t\ttry {\n\t\t\t\tg.connect(edge.from, edge.to);\n\t\t\t} catch {\n\t\t\t\t/* ignore malformed or non-reconstructable edge */\n\t\t\t}\n\t\t}\n\t\tg.restore(data);\n\t\treturn g;\n\t}\n\n\t/**\n\t * Plain snapshot with **recursively sorted object keys** for deterministic serialization (§3.8).\n\t *\n\t * @remarks\n\t * ECMAScript `JSON.stringify(graph)` invokes this method; it must return a plain object, not an\n\t * already-stringified JSON string (otherwise the graph would be double-encoded).\n\t * For a single UTF-8 string with a trailing newline (convenient for git), use {@link Graph.toJSONString}.\n\t *\n\t * @returns Same object as {@link Graph.snapshot}.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * Deterministic JSON **text**: `JSON.stringify` of {@link Graph.toJSON} plus a trailing newline (§3.8).\n\t *\n\t * @returns Stable string suitable for diffs.\n\t */\n\ttoJSONString(): string {\n\t\treturn stableJsonStringify(this.snapshot());\n\t}\n\n\t/**\n\t * Debounced persistence wired to graph-wide observe stream (spec §3.8 auto-checkpoint).\n\t *\n\t * Checkpoint trigger uses {@link messageTier}: only batches containing tier >= 2 messages\n\t * schedule a save (`DATA`/`RESOLVED`/terminal/destruction), never pure tier-0/1 control waves.\n\t */\n\tautoCheckpoint(\n\t\tadapter: AutoCheckpointAdapter,\n\t\toptions: GraphAutoCheckpointOptions = {},\n\t): GraphAutoCheckpointHandle {\n\t\tconst debounceMs = Math.max(0, options.debounceMs ?? 500);\n\t\tconst compactEvery = Math.max(1, options.compactEvery ?? 10);\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet seq = 0;\n\t\tlet pending = false;\n\t\tlet lastDescribe: GraphDescribeOutput | undefined;\n\n\t\tconst flush = () => {\n\t\t\ttimer = undefined;\n\t\t\tif (!pending) return;\n\t\t\tpending = false;\n\t\t\ttry {\n\t\t\t\tconst described = this.describe();\n\t\t\t\tconst snapshot = { ...described, version: SNAPSHOT_VERSION };\n\t\t\t\tseq += 1;\n\t\t\t\tconst shouldCompact = lastDescribe == null || seq % compactEvery === 0;\n\t\t\t\tif (shouldCompact) {\n\t\t\t\t\tadapter.save({ mode: \"full\", snapshot, seq } satisfies GraphCheckpointRecord);\n\t\t\t\t} else {\n\t\t\t\t\tconst previous = lastDescribe;\n\t\t\t\t\tif (previous == null) return;\n\t\t\t\t\tadapter.save({\n\t\t\t\t\t\tmode: \"diff\",\n\t\t\t\t\t\tdiff: Graph.diff(previous, described),\n\t\t\t\t\t\tsnapshot,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t} satisfies GraphCheckpointRecord);\n\t\t\t\t}\n\t\t\t\tlastDescribe = described;\n\t\t\t} catch (error) {\n\t\t\t\toptions.onError?.(error);\n\t\t\t}\n\t\t};\n\n\t\tconst schedule = () => {\n\t\t\tpending = true;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = setTimeout(flush, debounceMs);\n\t\t};\n\n\t\tconst off = this.observe().subscribe((path, messages) => {\n\t\t\tconst triggeredByTier = messages.some((m) => messageTier(m[0]) >= 2);\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst described = this.describe().nodes[path];\n\t\t\t\tif (described == null || !options.filter(path, described)) return;\n\t\t\t}\n\t\t\tschedule();\n\t\t});\n\n\t\tconst dispose = () => {\n\t\t\toff();\n\t\t\tif (timer !== undefined) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = undefined;\n\t\t\t}\n\t\t\tthis._autoCheckpointDisposers.delete(dispose);\n\t\t};\n\t\tthis._autoCheckpointDisposers.add(dispose);\n\t\treturn { dispose };\n\t}\n\n\t/**\n\t * Export the current graph topology as Mermaid flowchart text.\n\t *\n\t * Renders qualified node paths and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns Mermaid flowchart source.\n\t */\n\ttoMermaid(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`flowchart ${direction}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(` ${id}[\"${escapeMermaidLabel(path)}\"]`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(` ${fromId} --> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t/**\n\t * Export the current graph topology as D2 diagram text.\n\t *\n\t * Renders qualified node paths, constructor deps, and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns D2 source text.\n\t */\n\ttoD2(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`direction: ${d2DirectionFromGraphDirection(direction)}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(`${id}: \"${escapeD2Label(path)}\"`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(`${fromId} -> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Inspector (roadmap 3.3) — reasoning trace, overhead gating\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * When `false`, structured observation options (`causal`, `timeline`),\n\t * `annotate()`, and `traceLog()` are no-ops. Raw `observe()` always works.\n\t *\n\t * Default: `true` outside production (`process.env.NODE_ENV !== \"production\"`).\n\t */\n\tstatic inspectorEnabled = !(\n\t\ttypeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n\t);\n\n\tprivate _annotations = new Map<string, string>();\n\tprivate _traceRing = new RingBuffer<TraceEntry>(1000);\n\n\t/**\n\t * Attaches a reasoning annotation to a node — captures *why* an AI agent set a value.\n\t *\n\t * No-op when {@link Graph.inspectorEnabled} is `false`.\n\t *\n\t * @param path - Qualified node path.\n\t * @param reason - Free-text note stored in the trace ring buffer.\n\t */\n\tannotate(path: string, reason: string): void {\n\t\tif (!Graph.inspectorEnabled) return;\n\t\tthis.resolve(path); // validate path exists\n\t\tthis._annotations.set(path, reason);\n\t\tthis._traceRing.push({ path, reason, timestamp_ns: monotonicNs() });\n\t}\n\n\t/**\n\t * Returns a chronological log of all reasoning annotations (ring buffer).\n\t *\n\t * @returns `[]` when {@link Graph.inspectorEnabled} is `false`.\n\t */\n\ttraceLog(): readonly TraceEntry[] {\n\t\tif (!Graph.inspectorEnabled) return [];\n\t\treturn this._traceRing.toArray();\n\t}\n\n\t/**\n\t * Computes structural + value diff between two {@link Graph.describe} snapshots.\n\t *\n\t * @param a - Earlier describe output.\n\t * @param b - Later describe output.\n\t * @returns Added/removed nodes, changed fields, and edge deltas.\n\t */\n\tstatic diff(a: GraphDescribeOutput, b: GraphDescribeOutput): GraphDiffResult {\n\t\tconst aKeys = new Set(Object.keys(a.nodes));\n\t\tconst bKeys = new Set(Object.keys(b.nodes));\n\n\t\tconst nodesAdded = [...bKeys].filter((k) => !aKeys.has(k)).sort();\n\t\tconst nodesRemoved = [...aKeys].filter((k) => !bKeys.has(k)).sort();\n\t\tconst nodesChanged: GraphDiffChange[] = [];\n\n\t\tfor (const key of aKeys) {\n\t\t\tif (!bKeys.has(key)) continue;\n\t\t\tconst na = a.nodes[key];\n\t\t\tconst nb = b.nodes[key];\n\t\t\t// V0 optimization: skip value comparison when both nodes have matching versions.\n\t\t\tconst av = na.v;\n\t\t\tconst bv = nb.v;\n\t\t\tif (av != null && bv != null && av.id === bv.id && av.version === bv.version) {\n\t\t\t\t// Version unchanged — only check type/status (cheap string compare).\n\t\t\t\tfor (const field of [\"type\", \"status\"] as const) {\n\t\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\t\tif (va !== vb) {\n\t\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const field of [\"type\", \"status\", \"value\"] as const) {\n\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\tif (!Object.is(va, vb) && JSON.stringify(va) !== JSON.stringify(vb)) {\n\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst edgeKey = (e: { from: string; to: string }) => `${e.from}\\t${e.to}`;\n\t\tconst aEdges = new Set(a.edges.map(edgeKey));\n\t\tconst bEdges = new Set(b.edges.map(edgeKey));\n\n\t\tconst edgesAdded = b.edges.filter((e) => !aEdges.has(edgeKey(e)));\n\t\tconst edgesRemoved = a.edges.filter((e) => !bEdges.has(edgeKey(e)));\n\t\tconst aSubgraphs = new Set(a.subgraphs);\n\t\tconst bSubgraphs = new Set(b.subgraphs);\n\t\tconst subgraphsAdded = [...bSubgraphs].filter((s) => !aSubgraphs.has(s)).sort();\n\t\tconst subgraphsRemoved = [...aSubgraphs].filter((s) => !bSubgraphs.has(s)).sort();\n\n\t\treturn {\n\t\t\tnodesAdded,\n\t\t\tnodesRemoved,\n\t\t\tnodesChanged,\n\t\t\tedgesAdded,\n\t\t\tedgesRemoved,\n\t\t\tsubgraphsAdded,\n\t\t\tsubgraphsRemoved,\n\t\t};\n\t}\n}\n\n/** Entry in the reasoning trace ring buffer (roadmap 3.3). */\nexport type TraceEntry = {\n\tpath: string;\n\treason: string;\n\ttimestamp_ns: number;\n};\n\n/** Result of {@link Graph.diff}. */\nexport type GraphDiffResult = {\n\tnodesAdded: string[];\n\tnodesRemoved: string[];\n\tnodesChanged: GraphDiffChange[];\n\tedgesAdded: Array<{ from: string; to: string }>;\n\tedgesRemoved: Array<{ from: string; to: string }>;\n\tsubgraphsAdded: string[];\n\tsubgraphsRemoved: string[];\n};\n\n/** A single field change within a diff. */\nexport type GraphDiffChange = {\n\tpath: string;\n\tfield: string;\n\tfrom: unknown;\n\tto: unknown;\n};\n\n/** Direction for {@link reachable} graph traversal. */\nexport type ReachableDirection = \"upstream\" | \"downstream\";\n\n/** Options for {@link reachable}. */\nexport type ReachableOptions = {\n\t/** Maximum hop depth from `from` (0 returns `[]`). Omit for unbounded traversal. */\n\tmaxDepth?: number;\n};\n\n/**\n * Reachability query over a {@link Graph.describe} snapshot.\n *\n * Traversal combines dependency links (`deps`) and explicit graph edges (`edges`):\n * - `upstream`: follows `deps` plus incoming edges.\n * - `downstream`: follows reverse-`deps` plus outgoing edges.\n *\n * @param described - `graph.describe()` output to traverse.\n * @param from - Start path (qualified node path).\n * @param direction - Traversal direction.\n * @param options - Optional max depth bound.\n * @returns Sorted list of reachable paths (excluding `from`).\n *\n * @example\n * ```ts\n * import { Graph, reachable } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const a = g.register(\"a\");\n * const b = g.register(\"b\", [a]);\n * const described = g.describe();\n *\n * reachable(described, \"app.a\", \"downstream\"); // [\"app.b\"]\n * reachable(described, \"app.b\", \"upstream\"); // [\"app.a\"]\n * ```\n */\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions: ReachableOptions = {},\n): string[] {\n\tif (!from) return [];\n\tif (direction !== \"upstream\" && direction !== \"downstream\") {\n\t\tthrow new Error(`reachable: direction must be \"upstream\" or \"downstream\"`);\n\t}\n\tconst maxDepth = options.maxDepth;\n\tif (maxDepth != null && (!Number.isInteger(maxDepth) || maxDepth < 0)) {\n\t\tthrow new Error(`reachable: maxDepth must be an integer >= 0`);\n\t}\n\tif (maxDepth === 0) return [];\n\n\tconst depsByPath = new Map<string, string[]>();\n\tconst reverseDeps = new Map<string, Set<string>>();\n\tconst incomingEdges = new Map<string, Set<string>>();\n\tconst outgoingEdges = new Map<string, Set<string>>();\n\tconst universe = new Set<string>();\n\n\tconst nodesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"nodes\" in described &&\n\t\ttypeof (described as Record<string, unknown>).nodes === \"object\" &&\n\t\t(described as Record<string, unknown>).nodes !== null &&\n\t\t!Array.isArray((described as Record<string, unknown>).nodes)\n\t\t\t? ((described as Record<string, unknown>).nodes as Record<string, unknown>)\n\t\t\t: {};\n\tconst edgesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"edges\" in described &&\n\t\tArray.isArray((described as Record<string, unknown>).edges)\n\t\t\t? ((described as Record<string, unknown>).edges as unknown[])\n\t\t\t: [];\n\n\tfor (const [path, node] of Object.entries(nodesRaw)) {\n\t\tif (!path) continue;\n\t\tuniverse.add(path);\n\t\tconst deps =\n\t\t\tnode != null && typeof node === \"object\" && Array.isArray((node as { deps?: unknown[] }).deps)\n\t\t\t\t? (node as { deps: unknown[] }).deps\n\t\t\t\t: [];\n\t\tconst cleanDeps = deps.filter((d): d is string => typeof d === \"string\" && d.length > 0);\n\t\tdepsByPath.set(path, cleanDeps);\n\t\tfor (const dep of cleanDeps) {\n\t\t\tuniverse.add(dep);\n\t\t\tif (!reverseDeps.has(dep)) reverseDeps.set(dep, new Set());\n\t\t\treverseDeps.get(dep)!.add(path);\n\t\t}\n\t}\n\tfor (const edge of edgesRaw) {\n\t\tif (edge == null || typeof edge !== \"object\") continue;\n\t\tconst edgeFrom =\n\t\t\t\"from\" in edge && typeof (edge as { from?: unknown }).from === \"string\"\n\t\t\t\t? ((edge as { from: string }).from as string)\n\t\t\t\t: \"\";\n\t\tconst edgeTo =\n\t\t\t\"to\" in edge && typeof (edge as { to?: unknown }).to === \"string\"\n\t\t\t\t? ((edge as { to: string }).to as string)\n\t\t\t\t: \"\";\n\t\tif (!edgeFrom || !edgeTo) continue;\n\t\tuniverse.add(edgeFrom);\n\t\tuniverse.add(edgeTo);\n\t\tif (!outgoingEdges.has(edgeFrom)) outgoingEdges.set(edgeFrom, new Set());\n\t\toutgoingEdges.get(edgeFrom)!.add(edgeTo);\n\t\tif (!incomingEdges.has(edgeTo)) incomingEdges.set(edgeTo, new Set());\n\t\tincomingEdges.get(edgeTo)!.add(edgeFrom);\n\t}\n\n\tif (!universe.has(from)) return [];\n\n\tconst neighbors = (path: string): string[] => {\n\t\tif (direction === \"upstream\") {\n\t\t\tconst depNeighbors = depsByPath.get(path) ?? [];\n\t\t\tconst edgeNeighbors = [...(incomingEdges.get(path) ?? [])];\n\t\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t\t}\n\t\tconst depNeighbors = [...(reverseDeps.get(path) ?? [])];\n\t\tconst edgeNeighbors = [...(outgoingEdges.get(path) ?? [])];\n\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t};\n\n\tconst visited = new Set<string>([from]);\n\tconst out = new Set<string>();\n\tconst queue: Array<{ path: string; depth: number }> = [{ path: from, depth: 0 }];\n\twhile (queue.length > 0) {\n\t\tconst next = queue.shift()!;\n\t\tif (maxDepth != null && next.depth >= maxDepth) continue;\n\t\tfor (const nb of neighbors(next.path)) {\n\t\t\tif (!nb || visited.has(nb)) continue;\n\t\t\tvisited.add(nb);\n\t\t\tout.add(nb);\n\t\t\tqueue.push({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,QAAQ,EAAE,CAAC;AAAA,IAC/C;AAAA,EACD;AAEA,SAAO,CAAC,GAAG,GAAG,EAAE,KAAK,CAAC,GAAG,MAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE;AAC5D;","names":["actor","wantsStructured","stop","result","stream","text","edgeKey","depNeighbors","edgeNeighbors"]}
@@ -0,0 +1,97 @@
1
+ import {
2
+ describeNode,
3
+ metaSnapshot
4
+ } from "./chunk-O3PI7W45.js";
5
+ import {
6
+ COMPLETE,
7
+ DATA,
8
+ DEFAULT_ACTOR,
9
+ DIRTY,
10
+ DynamicNodeImpl,
11
+ ERROR,
12
+ GuardDenied,
13
+ INVALIDATE,
14
+ PAUSE,
15
+ RESOLVED,
16
+ RESUME,
17
+ TEARDOWN,
18
+ __export,
19
+ accessHintForGuard,
20
+ advanceVersion,
21
+ batch,
22
+ createVersioning,
23
+ defaultHash,
24
+ derived,
25
+ dynamicNode,
26
+ effect,
27
+ emitWithBatch,
28
+ isBatching,
29
+ isKnownMessageType,
30
+ isPhase2Message,
31
+ isTerminalMessage,
32
+ isV1,
33
+ knownMessageTypes,
34
+ messageTier,
35
+ monotonicNs,
36
+ node,
37
+ normalizeActor,
38
+ partitionForBatch,
39
+ pipe,
40
+ policy,
41
+ policyFromRules,
42
+ producer,
43
+ propagatesToMeta,
44
+ state,
45
+ wallClockNs
46
+ } from "./chunk-5X3LAO3B.js";
47
+
48
+ // src/core/index.ts
49
+ var core_exports = {};
50
+ __export(core_exports, {
51
+ COMPLETE: () => COMPLETE,
52
+ DATA: () => DATA,
53
+ DEFAULT_ACTOR: () => DEFAULT_ACTOR,
54
+ DIRTY: () => DIRTY,
55
+ DynamicNodeImpl: () => DynamicNodeImpl,
56
+ ERROR: () => ERROR,
57
+ GuardDenied: () => GuardDenied,
58
+ INVALIDATE: () => INVALIDATE,
59
+ PAUSE: () => PAUSE,
60
+ RESOLVED: () => RESOLVED,
61
+ RESUME: () => RESUME,
62
+ TEARDOWN: () => TEARDOWN,
63
+ accessHintForGuard: () => accessHintForGuard,
64
+ advanceVersion: () => advanceVersion,
65
+ batch: () => batch,
66
+ createVersioning: () => createVersioning,
67
+ defaultHash: () => defaultHash,
68
+ derived: () => derived,
69
+ describeNode: () => describeNode,
70
+ dynamicNode: () => dynamicNode,
71
+ effect: () => effect,
72
+ emitWithBatch: () => emitWithBatch,
73
+ isBatching: () => isBatching,
74
+ isKnownMessageType: () => isKnownMessageType,
75
+ isPhase2Message: () => isPhase2Message,
76
+ isTerminalMessage: () => isTerminalMessage,
77
+ isV1: () => isV1,
78
+ knownMessageTypes: () => knownMessageTypes,
79
+ messageTier: () => messageTier,
80
+ metaSnapshot: () => metaSnapshot,
81
+ monotonicNs: () => monotonicNs,
82
+ node: () => node,
83
+ normalizeActor: () => normalizeActor,
84
+ partitionForBatch: () => partitionForBatch,
85
+ pipe: () => pipe,
86
+ policy: () => policy,
87
+ policyFromRules: () => policyFromRules,
88
+ producer: () => producer,
89
+ propagatesToMeta: () => propagatesToMeta,
90
+ state: () => state,
91
+ wallClockNs: () => wallClockNs
92
+ });
93
+
94
+ export {
95
+ core_exports
96
+ };
97
+ //# sourceMappingURL=chunk-CP6MNKAA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/index.ts"],"sourcesContent":["/**\n * Core layer: message protocol, node primitive, lifecycle (Phase 0).\n */\nexport * from \"./actor.js\";\nexport * from \"./batch.js\";\nexport { monotonicNs, wallClockNs } from \"./clock.js\";\nexport * from \"./dynamic-node.js\";\nexport * from \"./guard.js\";\nexport * from \"./messages.js\";\nexport * from \"./meta.js\";\nexport {\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeFn,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\tnode,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node.js\";\nexport * from \"./sugar.js\";\nexport {\n\tadvanceVersion,\n\tcreateVersioning,\n\tdefaultHash,\n\ttype HashFn,\n\tisV1,\n\ttype NodeVersionInfo,\n\ttype V0,\n\ttype V1,\n\ttype VersioningLevel,\n\ttype VersioningOptions,\n} from \"./versioning.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;","names":[]}
@@ -0,0 +1,107 @@
1
+ import {
2
+ GRAPH_META_SEGMENT,
3
+ Graph,
4
+ reachable
5
+ } from "./chunk-6W5SGIGB.js";
6
+ import {
7
+ __export
8
+ } from "./chunk-5X3LAO3B.js";
9
+
10
+ // src/graph/index.ts
11
+ var graph_exports = {};
12
+ __export(graph_exports, {
13
+ GRAPH_META_SEGMENT: () => GRAPH_META_SEGMENT,
14
+ Graph: () => Graph,
15
+ JsonCodec: () => JsonCodec,
16
+ createDagCborCodec: () => createDagCborCodec,
17
+ createDagCborZstdCodec: () => createDagCborZstdCodec,
18
+ negotiateCodec: () => negotiateCodec,
19
+ reachable: () => reachable,
20
+ replayWAL: () => replayWAL
21
+ });
22
+
23
+ // src/graph/codec.ts
24
+ var JsonCodec = {
25
+ contentType: "application/json",
26
+ name: "json",
27
+ encode(snapshot) {
28
+ const json = JSON.stringify(snapshot);
29
+ return new TextEncoder().encode(json);
30
+ },
31
+ decode(buffer) {
32
+ const json = new TextDecoder().decode(buffer);
33
+ return JSON.parse(json);
34
+ }
35
+ };
36
+ function createDagCborCodec(dagCbor) {
37
+ return {
38
+ contentType: "application/dag-cbor",
39
+ name: "dag-cbor",
40
+ encode: (snapshot) => dagCbor.encode(snapshot),
41
+ decode: (buffer) => dagCbor.decode(buffer)
42
+ };
43
+ }
44
+ function createDagCborZstdCodec(dagCbor, zstd) {
45
+ return {
46
+ contentType: "application/dag-cbor+zstd",
47
+ name: "dag-cbor-zstd",
48
+ encode: (snapshot) => zstd.compressSync(dagCbor.encode(snapshot)),
49
+ decode: (buffer) => dagCbor.decode(zstd.decompressSync(buffer))
50
+ };
51
+ }
52
+ function negotiateCodec(localPreference, remoteContentTypes) {
53
+ const remoteSet = new Set(remoteContentTypes);
54
+ for (const codec of localPreference) {
55
+ if (remoteSet.has(codec.contentType)) return codec;
56
+ }
57
+ return null;
58
+ }
59
+ function replayWAL(entries) {
60
+ if (entries.length === 0) {
61
+ throw new Error("WAL is empty \u2014 need at least one full snapshot");
62
+ }
63
+ const first = entries[0];
64
+ if (first.type !== "full") {
65
+ throw new Error("WAL must start with a full snapshot");
66
+ }
67
+ const result = JSON.parse(JSON.stringify(first.snapshot));
68
+ for (let i = 1; i < entries.length; i++) {
69
+ const entry = entries[i];
70
+ if (entry.type === "full") {
71
+ Object.assign(result, JSON.parse(JSON.stringify(entry.snapshot)));
72
+ continue;
73
+ }
74
+ const delta = entry.delta;
75
+ for (const [name, patch] of Object.entries(delta.nodes)) {
76
+ if (result.nodes[name]) {
77
+ result.nodes[name].value = patch.value;
78
+ if (patch.meta) {
79
+ result.nodes[name].meta = patch.meta;
80
+ }
81
+ }
82
+ }
83
+ for (const name of delta.removed) {
84
+ delete result.nodes[name];
85
+ }
86
+ const edges = [...result.edges];
87
+ for (const edge of delta.edgesRemoved) {
88
+ const idx = edges.findIndex((e) => e.from === edge.from && e.to === edge.to);
89
+ if (idx !== -1) edges.splice(idx, 1);
90
+ }
91
+ for (const edge of delta.edgesAdded) {
92
+ edges.push(edge);
93
+ }
94
+ result.edges = edges;
95
+ }
96
+ return result;
97
+ }
98
+
99
+ export {
100
+ JsonCodec,
101
+ createDagCborCodec,
102
+ createDagCborZstdCodec,
103
+ negotiateCodec,
104
+ replayWAL,
105
+ graph_exports
106
+ };
107
+ //# sourceMappingURL=chunk-HP7OKEOE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graph/index.ts","../src/graph/codec.ts"],"sourcesContent":["/**\n * Graph container: registry, wiring, introspection (Phase 1).\n */\n\nexport {\n\tcreateDagCborCodec,\n\tcreateDagCborZstdCodec,\n\ttype DeltaCheckpoint,\n\ttype EvictedSubgraphInfo,\n\ttype EvictionPolicy,\n\ttype GraphCodec,\n\tJsonCodec,\n\ttype LazyGraphCodec,\n\tnegotiateCodec,\n\treplayWAL,\n\ttype WALEntry,\n} from \"./codec.js\";\nexport {\n\ttype AutoCheckpointAdapter,\n\ttype DescribeFilter,\n\tGRAPH_META_SEGMENT,\n\tGraph,\n\ttype GraphActorOptions,\n\ttype GraphAutoCheckpointHandle,\n\ttype GraphAutoCheckpointOptions,\n\ttype GraphCheckpointRecord,\n\ttype GraphDescribeOutput,\n\ttype GraphDiagramDirection,\n\ttype GraphDiagramOptions,\n\ttype GraphDiffChange,\n\ttype GraphDiffResult,\n\ttype GraphDumpOptions,\n\ttype GraphFactoryContext,\n\ttype GraphNodeFactory,\n\ttype GraphObserveAll,\n\ttype GraphObserveOne,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n\ttype GraphSpyHandle,\n\ttype GraphSpyOptions,\n\ttype GraphSpyTheme,\n\ttype GraphSpyThemeName,\n\ttype ObserveEvent,\n\ttype ObserveOptions,\n\ttype ObserveResult,\n\ttype ReachableDirection,\n\ttype ReachableOptions,\n\treachable,\n\ttype TraceEntry,\n} from \"./graph.js\";\n","/**\n * GraphCodec — pluggable serialization for graph snapshots (Phase 8.6).\n *\n * Design reference: `archive/docs/SESSION-serialization-memory-footprint.md`\n *\n * The codec interface decouples snapshot format from graph internals.\n * Default is JSON (current behavior). DAG-CBOR and compressed variants\n * ship as optional codecs. FlatBuffers/Arrow for advanced tiers.\n *\n * Tiered representation:\n * HOT — JS objects (live propagation, no codec involved)\n * WARM — DAG-CBOR in-memory buffer (lazy hydration, delta checkpoints)\n * COLD — Arrow/Parquet (bulk storage, ML pipelines, archival)\n * PEEK — FlatBuffers (zero-copy read from dormant graph)\n */\n\nimport type { GraphPersistSnapshot } from \"./graph.js\";\n\n// ---------------------------------------------------------------------------\n// Core codec interface\n// ---------------------------------------------------------------------------\n\n/**\n * Encode/decode graph snapshots to/from binary.\n *\n * Implementations must be deterministic: `encode(x)` always produces the\n * same bytes for the same input. This is critical for CID computation (V1)\n * and snapshot hash-comparison.\n */\nexport interface GraphCodec {\n\t/** MIME-like content type identifier (e.g. \"application/dag-cbor+zstd\"). */\n\treadonly contentType: string;\n\n\t/** Human-readable name for diagnostics. */\n\treadonly name: string;\n\n\t/** Encode a snapshot to binary. */\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array;\n\n\t/**\n\t * Decode binary back to a snapshot.\n\t *\n\t * For lazy codecs, this may return a proxy that decodes nodes on access\n\t * (see {@link LazyGraphCodec}).\n\t */\n\tdecode(buffer: Uint8Array): GraphPersistSnapshot;\n}\n\n/**\n * Extended codec that supports lazy (on-demand) node decoding.\n *\n * `decodeLazy` returns a snapshot where `nodes` is a Proxy — individual\n * nodes are decoded only when accessed. This enables near-zero cold-start\n * for large graphs (decode envelope + topology, skip node values until read).\n */\nexport interface LazyGraphCodec extends GraphCodec {\n\t/** Decode envelope and topology; defer node value decoding to access time. */\n\tdecodeLazy(buffer: Uint8Array): GraphPersistSnapshot;\n}\n\n// ---------------------------------------------------------------------------\n// Delta checkpoint types (requires V0 — Phase 6.0)\n// ---------------------------------------------------------------------------\n\n/**\n * A delta checkpoint: only the nodes that changed since last checkpoint.\n *\n * Append-only: each delta is identified by `seq` (monotonic). A full\n * snapshot is taken every `compactEvery` deltas for WAL compaction.\n */\nexport interface DeltaCheckpoint {\n\t/** Monotonic sequence number. */\n\tseq: number;\n\t/** Graph name. */\n\tname: string;\n\t/** Base snapshot seq this delta applies to (0 = initial full snapshot). */\n\tbaseSec: number;\n\t/** Only nodes with version > lastCheckpoint. Keyed by node name. */\n\tnodes: Record<\n\t\tstring,\n\t\t{\n\t\t\t/** V0 version at time of checkpoint. */\n\t\t\tversion: number;\n\t\t\t/** Serialized node value (codec-dependent). */\n\t\t\tvalue: unknown;\n\t\t\t/** Meta snapshot (only if materialized). */\n\t\t\tmeta?: Record<string, unknown>;\n\t\t}\n\t>;\n\t/** Nodes removed since last checkpoint. */\n\tremoved: string[];\n\t/** Edges added since last checkpoint. */\n\tedgesAdded: ReadonlyArray<{ from: string; to: string }>;\n\t/** Edges removed since last checkpoint. */\n\tedgesRemoved: ReadonlyArray<{ from: string; to: string }>;\n\t/** Timestamp (wall-clock ns) of this checkpoint. */\n\ttimestampNs: bigint;\n}\n\n/**\n * WAL entry: either a full snapshot or a delta.\n */\nexport type WALEntry =\n\t| { type: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { type: \"delta\"; delta: DeltaCheckpoint };\n\n// ---------------------------------------------------------------------------\n// Eviction policy (dormant subgraph management)\n// ---------------------------------------------------------------------------\n\n/**\n * Policy for evicting dormant subgraphs to reduce memory.\n *\n * When a subgraph hasn't propagated for `idleTimeoutMs`, it is serialized\n * using the graph's codec and JS objects are released. Re-hydrated on next\n * access (read, propagation, describe).\n */\nexport interface EvictionPolicy {\n\t/** Milliseconds of inactivity before eviction. */\n\tidleTimeoutMs: number;\n\t/** Codec to use for serializing evicted subgraphs (default: graph's codec). */\n\tcodec?: GraphCodec;\n}\n\n/** Metadata about an evicted subgraph, exposed via describe(). */\nexport interface EvictedSubgraphInfo {\n\t/** True if currently evicted (serialized, JS objects released). */\n\tevicted: true;\n\t/** Wall-clock ns of last propagation before eviction. */\n\tlastActiveNs: bigint;\n\t/** Size of serialized buffer in bytes. */\n\tserializedBytes: number;\n\t/** Codec used for serialization. */\n\tcodecName: string;\n}\n\n// ---------------------------------------------------------------------------\n// JSON codec (default — wraps current behavior)\n// ---------------------------------------------------------------------------\n\n/**\n * Default JSON codec. Wraps `JSON.stringify`/`JSON.parse` with deterministic\n * key ordering (matching current `snapshot()` behavior).\n */\nexport const JsonCodec: GraphCodec = {\n\tcontentType: \"application/json\",\n\tname: \"json\",\n\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array {\n\t\t// Deterministic: snapshot() already sorts keys.\n\t\tconst json = JSON.stringify(snapshot);\n\t\treturn new TextEncoder().encode(json);\n\t},\n\n\tdecode(buffer: Uint8Array): GraphPersistSnapshot {\n\t\tconst json = new TextDecoder().decode(buffer);\n\t\treturn JSON.parse(json) as GraphPersistSnapshot;\n\t},\n};\n\n// ---------------------------------------------------------------------------\n// DAG-CBOR codec (stub — requires @ipld/dag-cbor)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a DAG-CBOR codec.\n *\n * Requires `@ipld/dag-cbor` as a peer dependency. ~40-50% smaller than JSON,\n * deterministic encoding (required for V1 CID), CID links as native type.\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * const codec = createDagCborCodec(dagCbor);\n * const bytes = codec.encode(graph.snapshot());\n * ```\n */\nexport function createDagCborCodec(dagCbor: {\n\tencode: (value: unknown) => Uint8Array;\n\tdecode: (bytes: Uint8Array) => unknown;\n}): GraphCodec {\n\treturn {\n\t\tcontentType: \"application/dag-cbor\",\n\t\tname: \"dag-cbor\",\n\t\tencode: (snapshot) => dagCbor.encode(snapshot),\n\t\tdecode: (buffer) => dagCbor.decode(buffer) as GraphPersistSnapshot,\n\t};\n}\n\n/**\n * Create a DAG-CBOR + zstd codec. ~80-90% smaller than JSON.\n *\n * Requires `@ipld/dag-cbor` and a zstd implementation (e.g. `fzstd` for\n * browser, `node:zlib` for Node.js).\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * import { compressSync, decompressSync } from \"fzstd\";\n * const codec = createDagCborZstdCodec(dagCbor, { compressSync, decompressSync });\n * ```\n */\nexport function createDagCborZstdCodec(\n\tdagCbor: {\n\t\tencode: (value: unknown) => Uint8Array;\n\t\tdecode: (bytes: Uint8Array) => unknown;\n\t},\n\tzstd: {\n\t\tcompressSync: (data: Uint8Array) => Uint8Array;\n\t\tdecompressSync: (data: Uint8Array) => Uint8Array;\n\t},\n): GraphCodec {\n\treturn {\n\t\tcontentType: \"application/dag-cbor+zstd\",\n\t\tname: \"dag-cbor-zstd\",\n\t\tencode: (snapshot) => zstd.compressSync(dagCbor.encode(snapshot)),\n\t\tdecode: (buffer) => dagCbor.decode(zstd.decompressSync(buffer)) as GraphPersistSnapshot,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Codec negotiation (for peerGraph)\n// ---------------------------------------------------------------------------\n\n/**\n * Negotiate a common codec between two peers.\n *\n * Each peer advertises its supported codecs (ordered by preference).\n * Returns the first codec supported by both, or null if none.\n */\nexport function negotiateCodec(\n\tlocalPreference: readonly GraphCodec[],\n\tremoteContentTypes: readonly string[],\n): GraphCodec | null {\n\tconst remoteSet = new Set(remoteContentTypes);\n\tfor (const codec of localPreference) {\n\t\tif (remoteSet.has(codec.contentType)) return codec;\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// WAL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Reconstruct a snapshot from a WAL (full snapshot + sequence of deltas).\n *\n * Applies deltas in order on top of the base snapshot. Validates that\n * delta `baseSec` chains correctly.\n */\nexport function replayWAL(entries: readonly WALEntry[]): GraphPersistSnapshot {\n\tif (entries.length === 0) {\n\t\tthrow new Error(\"WAL is empty — need at least one full snapshot\");\n\t}\n\n\tconst first = entries[0]!;\n\tif (first.type !== \"full\") {\n\t\tthrow new Error(\"WAL must start with a full snapshot\");\n\t}\n\n\t// Deep clone the base snapshot so we can mutate it.\n\tconst result: GraphPersistSnapshot = JSON.parse(JSON.stringify(first.snapshot));\n\n\tfor (let i = 1; i < entries.length; i++) {\n\t\tconst entry = entries[i]!;\n\t\tif (entry.type === \"full\") {\n\t\t\t// A compaction point — replace the entire result.\n\t\t\tObject.assign(result, JSON.parse(JSON.stringify(entry.snapshot)));\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst delta = entry.delta;\n\n\t\t// Apply node changes.\n\t\tfor (const [name, patch] of Object.entries(delta.nodes)) {\n\t\t\tif (result.nodes[name]) {\n\t\t\t\tresult.nodes[name]!.value = patch.value;\n\t\t\t\tif (patch.meta) {\n\t\t\t\t\tresult.nodes[name]!.meta = patch.meta;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Apply removals.\n\t\tfor (const name of delta.removed) {\n\t\t\tdelete result.nodes[name];\n\t\t}\n\n\t\t// Apply edge changes.\n\t\tconst edges = [...result.edges];\n\t\tfor (const edge of delta.edgesRemoved) {\n\t\t\tconst idx = edges.findIndex((e) => e.from === edge.from && e.to === edge.to);\n\t\t\tif (idx !== -1) edges.splice(idx, 1);\n\t\t}\n\t\tfor (const edge of delta.edgesAdded) {\n\t\t\tedges.push(edge);\n\t\t}\n\t\t(result as unknown as { edges: typeof edges }).edges = edges;\n\t}\n\n\treturn result;\n}\n"],"mappings":";;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACgJO,IAAM,YAAwB;AAAA,EACpC,aAAa;AAAA,EACb,MAAM;AAAA,EAEN,OAAO,UAA4C;AAElD,UAAM,OAAO,KAAK,UAAU,QAAQ;AACpC,WAAO,IAAI,YAAY,EAAE,OAAO,IAAI;AAAA,EACrC;AAAA,EAEA,OAAO,QAA0C;AAChD,UAAM,OAAO,IAAI,YAAY,EAAE,OAAO,MAAM;AAC5C,WAAO,KAAK,MAAM,IAAI;AAAA,EACvB;AACD;AAmBO,SAAS,mBAAmB,SAGpB;AACd,SAAO;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,IACN,QAAQ,CAAC,aAAa,QAAQ,OAAO,QAAQ;AAAA,IAC7C,QAAQ,CAAC,WAAW,QAAQ,OAAO,MAAM;AAAA,EAC1C;AACD;AAeO,SAAS,uBACf,SAIA,MAIa;AACb,SAAO;AA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