@graphrefly/graphrefly 0.21.0 → 0.22.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.
- package/README.md +7 -5
- package/dist/chunk-44HD4BTA.js +47 -0
- package/dist/chunk-44HD4BTA.js.map +1 -0
- package/dist/chunk-7TAQJHQV.js +103 -0
- package/dist/chunk-7TAQJHQV.js.map +1 -0
- package/dist/chunk-BLD3IFYF.js +6827 -0
- package/dist/chunk-BLD3IFYF.js.map +1 -0
- package/dist/{chunk-ZTCDY5NQ.js → chunk-EQUZ5NLD.js} +34 -45
- package/dist/chunk-EQUZ5NLD.js.map +1 -0
- package/dist/{chunk-VOQFK7YN.js → chunk-IR3KMOLX.js} +358 -128
- package/dist/chunk-IR3KMOLX.js.map +1 -0
- package/dist/{chunk-XWBVAO2R.js → chunk-MQBQOFDS.js} +20 -11
- package/dist/chunk-MQBQOFDS.js.map +1 -0
- package/dist/chunk-NXC35KC5.js +2417 -0
- package/dist/chunk-NXC35KC5.js.map +1 -0
- package/dist/chunk-QA3RP5NH.js +2234 -0
- package/dist/chunk-QA3RP5NH.js.map +1 -0
- package/dist/chunk-RHI3GHZW.js +115 -0
- package/dist/chunk-RHI3GHZW.js.map +1 -0
- package/dist/{chunk-7IGHIFTT.js → chunk-TH6COGOP.js} +15 -26
- package/dist/chunk-TH6COGOP.js.map +1 -0
- package/dist/compat/nestjs/index.cjs +3366 -2259
- package/dist/compat/nestjs/index.cjs.map +1 -1
- package/dist/compat/nestjs/index.d.cts +6 -4
- package/dist/compat/nestjs/index.d.ts +6 -4
- package/dist/compat/nestjs/index.js +8 -8
- package/dist/core/index.cjs +1611 -1218
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +3 -2
- package/dist/core/index.d.ts +3 -2
- package/dist/core/index.js +37 -34
- package/dist/extra/index.cjs +7387 -6089
- package/dist/extra/index.cjs.map +1 -1
- package/dist/extra/index.d.cts +4 -4
- package/dist/extra/index.d.ts +4 -4
- package/dist/extra/index.js +57 -30
- package/dist/graph/index.cjs +3107 -2216
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +5 -3
- package/dist/graph/index.d.ts +5 -3
- package/dist/graph/index.js +24 -11
- package/dist/graph-DFr0diXB.d.ts +1128 -0
- package/dist/graph-ab1yPwIB.d.cts +1128 -0
- package/dist/{index-8a605sg9.d.ts → index-BHm3Ba5q.d.ts} +2 -2
- package/dist/{index-DuN3bhtm.d.ts → index-BbYZma8G.d.ts} +1697 -586
- package/dist/{index-SFzE_KTa.d.cts → index-BvWfZCTt.d.cts} +1697 -586
- package/dist/index-C9z6rU9P.d.cts +388 -0
- package/dist/{index-BjtlNirP.d.cts → index-D36MAQ3f.d.ts} +4 -4
- package/dist/{index-VHA43cGP.d.cts → index-DLE1Sp-L.d.cts} +2 -2
- package/dist/{index-CgSiUouz.d.ts → index-DrJq9B1T.d.cts} +4 -4
- package/dist/index-DsGxLfwL.d.ts +315 -0
- package/dist/index-Dy04P4W3.d.cts +315 -0
- package/dist/index-HdJx_BjO.d.ts +388 -0
- package/dist/index.cjs +9781 -7878
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +214 -37
- package/dist/index.d.ts +214 -37
- package/dist/index.js +905 -638
- package/dist/index.js.map +1 -1
- package/dist/meta--fr9sxRM.d.cts +41 -0
- package/dist/meta-n3FoVWML.d.ts +41 -0
- package/dist/node-C5UD5MGq.d.cts +1146 -0
- package/dist/node-C5UD5MGq.d.ts +1146 -0
- package/dist/{observable-DcBwQY7t.d.ts → observable-CQRBtEbq.d.ts} +1 -1
- package/dist/{observable-C8Kx_O6k.d.cts → observable-DWydVy5b.d.cts} +1 -1
- package/dist/patterns/reactive-layout/index.cjs +3102 -2132
- package/dist/patterns/reactive-layout/index.cjs.map +1 -1
- package/dist/patterns/reactive-layout/index.d.cts +5 -3
- package/dist/patterns/reactive-layout/index.d.ts +5 -3
- package/dist/patterns/reactive-layout/index.js +5 -4
- package/dist/storage-Bew05Xy6.d.cts +182 -0
- package/dist/storage-C9fZfMfM.d.ts +182 -0
- package/package.json +1 -1
- package/dist/chunk-2UDLYZHT.js +0 -2117
- package/dist/chunk-2UDLYZHT.js.map +0 -1
- package/dist/chunk-4MQ2J6IG.js +0 -1631
- package/dist/chunk-4MQ2J6IG.js.map +0 -1
- package/dist/chunk-7IGHIFTT.js.map +0 -1
- package/dist/chunk-DOSLSFKL.js +0 -162
- package/dist/chunk-DOSLSFKL.js.map +0 -1
- package/dist/chunk-ECN37NVS.js +0 -6227
- package/dist/chunk-ECN37NVS.js.map +0 -1
- package/dist/chunk-G66H6ZRK.js +0 -111
- package/dist/chunk-G66H6ZRK.js.map +0 -1
- package/dist/chunk-VOQFK7YN.js.map +0 -1
- package/dist/chunk-WZ2Z2CRV.js +0 -32
- package/dist/chunk-WZ2Z2CRV.js.map +0 -1
- package/dist/chunk-XWBVAO2R.js.map +0 -1
- package/dist/chunk-ZTCDY5NQ.js.map +0 -1
- package/dist/graph-KsTe57nI.d.cts +0 -750
- package/dist/graph-mILUUqW8.d.ts +0 -750
- package/dist/index-B2SvPEbc.d.ts +0 -257
- package/dist/index-BHfg_Ez3.d.ts +0 -629
- package/dist/index-Bc_diYYJ.d.cts +0 -629
- package/dist/index-UudxGnzc.d.cts +0 -257
- package/dist/meta-BnG7XAaE.d.cts +0 -778
- package/dist/meta-BnG7XAaE.d.ts +0 -778
package/dist/graph/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/graph/index.ts","../../src/graph/codec.ts","../../src/core/messages.ts","../../src/core/batch.ts","../../src/core/clock.ts","../../src/core/guard.ts","../../src/core/actor.ts","../../src/core/versioning.ts","../../src/core/node-base.ts","../../src/core/node.ts","../../src/core/dynamic-node.ts","../../src/core/meta.ts","../../src/core/sugar.ts","../../src/graph/sizeof.ts","../../src/graph/profile.ts","../../src/graph/graph.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 GraphDescribeOptions,\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 ObserveDetail,\n\ttype ObserveEvent,\n\ttype ObserveOptions,\n\ttype ObserveResult,\n\ttype ObserveTheme,\n\ttype ObserveThemeName,\n\ttype ReachableDirection,\n\ttype ReachableOptions,\n\treachable,\n\ttype TraceEntry,\n} from \"./graph.js\";\nexport {\n\ttype GraphProfileOptions,\n\ttype GraphProfileResult,\n\tgraphProfile,\n\ttype NodeProfile,\n} from \"./profile.js\";\nexport { sizeof } from \"./sizeof.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","/**\n * GraphReFly message protocol — §1 `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n * Emissions are always `[[Type, Data?], ...]` (no single-tuple shorthand).\n *\n * ## Canonical message ordering (within a composite batch)\n *\n * When multiple message types appear in a single `down()` call, the canonical\n * delivery order is determined by **signal tier**:\n *\n * | Tier | Signals | Role | Batch behavior |\n * |------|------------------------|-------------------|-------------------------------------|\n * | 0 | START | Subscribe handshake | Immediate (never deferred) |\n * | 1 | DIRTY, INVALIDATE | Notification | Immediate (never deferred) |\n * | 2 | PAUSE, RESUME | Flow control | Immediate (never deferred) |\n * | 3 | DATA, RESOLVED | Value settlement | Deferred inside `batch()` |\n * | 4 | COMPLETE, ERROR | Terminal lifecycle | Deferred to after phase-2 |\n * | 5 | TEARDOWN | Destruction | Immediate (usually sent alone) |\n *\n * **Rule:** Within `downWithBatch`, messages are partitioned by tier and delivered\n * in tier order. This ensures phase-2 values (DATA/RESOLVED) reach sinks before\n * terminal signals (COMPLETE/ERROR) mark the node as done, preventing the\n * \"COMPLETE-before-DATA\" class of bugs. Sources that emit in canonical order\n * naturally partition correctly with zero overhead.\n *\n * Unknown message types (forward-compat) are tier 1 (immediate).\n *\n * ## Meta node bypass rules (centralized — GRAPHREFLY-SPEC §2.3)\n *\n * - **INVALIDATE** via `graph.signal()` — no-op on meta nodes (cached values preserved).\n * - **COMPLETE / ERROR** — not propagated from parent to meta (meta outlives terminal\n * state for post-mortem writes like setting `meta.error` after ERROR).\n * - **TEARDOWN** — propagated from parent to meta, releasing meta resources.\n */\n\n/**\n * Subscribe-time handshake (`START`). Delivered to each new sink at the top of\n * `subscribe()` — `[[START]]` for a SENTINEL (no cached value) node or\n * `[[START], [DATA, cached]]` for a node with a cached value.\n *\n * Semantics: \"upstream connected and ready to flow.\" A new sink receiving\n * `[[START]]` alone knows the upstream is alive but has no current value; a\n * sink receiving `[[START], [DATA, v]]` knows the upstream is ready\n * with value `v`. Absence of `START` before any other message means the\n * subscription was either never established or the node is terminal.\n *\n * Tier 0 — immediate, delivered before any DIRTY/DATA in the same batch.\n * Not forwarded through nodes — each node emits its own `START` to its own\n * new sinks.\n */\nexport const START = Symbol.for(\"graphrefly/START\");\n/** Value delivery (`DATA`, value). Tier 3 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 1 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 3 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 1 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 2 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 2 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 5 — immediate (usually sent alone). */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 4 — delivered after phase-2 in the same batch. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 4 — delivered after phase-2 in the same batch. */\nexport const ERROR = Symbol.for(\"graphrefly/ERROR\");\n\n/** Known protocol type symbols (open set — other symbols are valid and forward). */\nexport const knownMessageTypes: readonly symbol[] = [\n\tSTART,\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tINVALIDATE,\n\tPAUSE,\n\tRESUME,\n\tTEARDOWN,\n\tCOMPLETE,\n\tERROR,\n];\n\n/** O(1) lookup for {@link isKnownMessageType} and {@link isLocalOnly}. */\nconst knownMessageSet: ReadonlySet<symbol> = new Set(knownMessageTypes);\n\n/** One protocol tuple: `[Type, optional payload]`. */\nexport type Message = readonly [symbol, unknown?];\n\n/**\n * A batch of tuples — the wire shape for `node.down()` / `node.up()`.\n */\nexport type Messages = readonly Message[];\n\n/**\n * Whether `t` is one of the built-in protocol symbols in this module.\n *\n * @param t — Message type symbol (unknown types are still valid; they must forward).\n * @returns `true` for `DATA`, `DIRTY`, `RESOLVED`, etc.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, isKnownMessageType } from \"@graphrefly/graphrefly-ts\";\n *\n * isKnownMessageType(DATA); // true\n * isKnownMessageType(Symbol(\"custom\")); // false\n * ```\n */\nexport function isKnownMessageType(t: symbol): boolean {\n\treturn knownMessageSet.has(t);\n}\n\n/**\n * Returns the signal tier for a message type (see module-level ordering table).\n *\n * - 0: subscribe handshake (START) — immediate, first in canonical order\n * - 1: notification (DIRTY, INVALIDATE) — immediate\n * - 2: flow control (PAUSE, RESUME) — immediate\n * - 3: value (DATA, RESOLVED) — deferred inside `batch()`\n * - 4: terminal (COMPLETE, ERROR) — delivered after phase-3\n * - 5: destruction (TEARDOWN) — immediate, usually alone\n * - 1 for unknown types (forward-compat: immediate)\n *\n * @param t — Message type symbol.\n * @returns Tier number (0–5).\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, TEARDOWN, messageTier, START } from \"@graphrefly/graphrefly-ts\";\n *\n * messageTier(START); // 0\n * messageTier(DIRTY); // 1\n * messageTier(DATA); // 3\n * messageTier(COMPLETE); // 4\n * messageTier(TEARDOWN); // 5\n * ```\n */\nexport function messageTier(t: symbol): number {\n\tif (t === START) return 0;\n\tif (t === DIRTY || t === INVALIDATE) return 1;\n\tif (t === PAUSE || t === RESUME) return 2;\n\tif (t === DATA || t === RESOLVED) return 3;\n\tif (t === COMPLETE || t === ERROR) return 4;\n\tif (t === TEARDOWN) return 5;\n\treturn 1; // unknown → immediate (after START)\n}\n\n/**\n * Returns whether this tuple is deferred by `batch()` (phase 2: `DATA` or `RESOLVED`).\n *\n * @param msg — Single message tuple.\n * @returns `true` if `msg` is `DATA` or `RESOLVED`.\n *\n * @example\n * ```ts\n * import { DATA, RESOLVED, DIRTY, isPhase2Message } from \"@graphrefly/graphrefly-ts\";\n *\n * isPhase2Message([DATA, 42]); // true\n * isPhase2Message([RESOLVED]); // true\n * isPhase2Message([DIRTY]); // false\n * ```\n */\nexport function isPhase2Message(msg: Message): boolean {\n\tconst t = msg[0];\n\treturn t === DATA || t === RESOLVED;\n}\n\n/**\n * Returns whether this message type is terminal (COMPLETE or ERROR).\n * Terminal messages are delivered after phase-2 in the same batch to prevent\n * the node from becoming terminal before value messages reach sinks.\n *\n * @param t — Message type symbol.\n * @returns `true` for `COMPLETE` or `ERROR`.\n *\n * @example\n * ```ts\n * import { COMPLETE, ERROR, DATA, isTerminalMessage } from \"@graphrefly/graphrefly-ts\";\n *\n * isTerminalMessage(COMPLETE); // true\n * isTerminalMessage(ERROR); // true\n * isTerminalMessage(DATA); // false\n * ```\n */\nexport function isTerminalMessage(t: symbol): boolean {\n\treturn t === COMPLETE || t === ERROR;\n}\n\n/**\n * Whether `t` is a graph-local signal that should NOT cross a wire/transport\n * boundary (SSE, WebSocket, worker bridge, persistence sinks).\n *\n * Local-only signals (tier 0–2): START, DIRTY, INVALIDATE, PAUSE, RESUME.\n * These are internal to the reactive graph — subscribe handshakes,\n * notification phases, and flow control have no semantics for remote consumers.\n *\n * Wire-crossing signals (tier 3+): DATA, RESOLVED, COMPLETE, ERROR, TEARDOWN.\n * Unknown message types (spec §1.3.6 forward-compat) also cross the wire.\n *\n * Individual adapters may further opt-in to local signals for observability\n * (e.g. SSE `includeDirty`, `includeResolved` options). Storage/persistence\n * adapters that need INVALIDATE for remote cache-clear should explicitly\n * forward it despite `isLocalOnly(INVALIDATE) === true`. The default is to\n * skip all local-only signals at the boundary.\n *\n * @param t — Message type symbol.\n * @returns `true` if the message should be kept local (not sent over wire).\n *\n * @example\n * ```ts\n * import { START, DIRTY, DATA, COMPLETE, isLocalOnly } from \"@graphrefly/graphrefly-ts\";\n *\n * isLocalOnly(START); // true — subscribe handshake\n * isLocalOnly(DIRTY); // true — notification phase\n * isLocalOnly(RESOLVED); // false — value settlement crosses wire\n * isLocalOnly(DATA); // false — value crosses wire\n * isLocalOnly(COMPLETE); // false — terminal crosses wire\n * ```\n *\n * @category core\n */\nexport function isLocalOnly(t: symbol): boolean {\n\t// Unknown types always cross the wire (spec §1.3.6 forward-compat).\n\t// messageTier returns 1 for unknowns, but unknowns are NOT local-only.\n\tif (!knownMessageSet.has(t)) return false;\n\treturn messageTier(t) < 3;\n}\n\n/**\n * Whether `t` should be propagated from a parent node to its companion meta nodes.\n * Only TEARDOWN propagates; COMPLETE/ERROR/INVALIDATE do not (meta outlives parent\n * terminal state for post-mortem writes).\n *\n * @param t — Message type symbol.\n * @returns `true` if the signal should reach meta nodes.\n *\n * @example\n * ```ts\n * import { TEARDOWN, COMPLETE, ERROR, propagatesToMeta } from \"@graphrefly/graphrefly-ts\";\n *\n * propagatesToMeta(TEARDOWN); // true\n * propagatesToMeta(COMPLETE); // false\n * propagatesToMeta(ERROR); // false\n * ```\n */\nexport function propagatesToMeta(t: symbol): boolean {\n\treturn t === TEARDOWN;\n}\n","import {\n\tDATA,\n\tisPhase2Message,\n\tisTerminalMessage,\n\ttype Message,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n} from \"./messages.js\";\n\n/**\n * §1.3.7 — Inside a batch, DIRTY propagates immediately; DATA and RESOLVED are\n * deferred until the outermost `batch()` callback returns. Terminal signals\n * (COMPLETE, ERROR) are delivered after phase-2 messages in the same batch\n * (see canonical ordering in `messages.ts`).\n */\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\nconst pendingPhase2: Array<() => void> = [];\nconst pendingPhase3: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * deferred phase-2 work is draining.\n *\n * Matching Python's `is_batching()` semantics: nested emissions during drain\n * are deferred until the current drain pass completes, preventing ordering\n * bugs when callbacks trigger further DATA/RESOLVED.\n *\n * @returns `true` while inside `batch()` or while the drain loop is running.\n *\n * @example\n * ```ts\n * import { batch, isBatching } from \"@graphrefly/graphrefly-ts\";\n *\n * batch(() => {\n * console.log(isBatching()); // true\n * });\n * ```\n *\n * @category core\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral queue.\n * If `fn` throws (including from a nested `batch`), deferred DATA/RESOLVED for\n * that **outer** `batch` frame are discarded — phase-2 is not flushed after an\n * error. While the drain loop is running (`flushInProgress`), a nested `batch`\n * that throws must **not** clear the global queue (cross-language decision A4).\n *\n * During the drain loop, `isBatching()` remains true so nested `downWithBatch`\n * calls still defer phase-2 messages. The drain loop runs until the queue is\n * quiescent (no pending work remains). Per-emission try/catch ensures one\n * throwing callback does not orphan remaining emissions; the first error is\n * re-thrown after all emissions drain. Callbacks that ran before the throw may\n * have applied phase-2 — partial graph state is intentional (decision C1).\n *\n * @param fn — Synchronous work that may call `downWithBatch` / `node.down()`.\n * @returns `void` — all side-effects happen through `downWithBatch` and the\n * phase-2 drain that runs after `fn` returns.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.batch(() => {\n * core.downWithBatch(sink, [[core.DATA, 1]]);\n * });\n * ```\n *\n * @category core\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\t// Do not wipe the outer drain's queue (decision A4).\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) {\n\t\tflushInProgress = true;\n\t}\n\tconst errors: unknown[] = [];\n\ttry {\n\t\tlet iterations = 0;\n\t\t// Drain phase-2 first, then phase-3. If phase-3 callbacks enqueue new\n\t\t// phase-2 work, the outer loop catches it and drains phase-2 again\n\t\t// before re-entering phase-3.\n\t\twhile (pendingPhase2.length > 0 || pendingPhase3.length > 0) {\n\t\t\t// Phase-2 (DATA/RESOLVED) — parent node values settle here.\n\t\t\twhile (pendingPhase2.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase2.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Phase-3 — meta companion emissions that must follow parent settlement.\n\t\t\tif (pendingPhase3.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase3.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) {\n\t\t\tflushInProgress = false;\n\t\t}\n\t}\n\tif (errors.length === 1) {\n\t\tthrow errors[0];\n\t}\n\tif (errors.length > 1) {\n\t\tthrow new AggregateError(errors, \"batch drain: multiple callbacks threw\");\n\t}\n}\n\n/**\n * Splits a message array into three groups by signal tier (see `messages.ts`):\n *\n * - **immediate** — tier 0–2, 5: START, DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN, unknown\n * - **deferred** — tier 3: DATA, RESOLVED (phase-2, deferred inside `batch()`)\n * - **terminal** — tier 4: COMPLETE, ERROR (delivered after phase-2)\n *\n * Order within each group is preserved.\n *\n * @param messages — One `down()` payload.\n * @returns Three groups in canonical delivery order.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, partitionForBatch } from \"@graphrefly/graphrefly-ts\";\n *\n * partitionForBatch([[DIRTY], [DATA, 1], [COMPLETE]]);\n * // { immediate: [[DIRTY]], deferred: [[DATA, 1]], terminal: [[COMPLETE]] }\n * ```\n *\n * @category core\n */\nexport function partitionForBatch(messages: Messages): {\n\timmediate: Messages;\n\tdeferred: Messages;\n\tterminal: Messages;\n} {\n\tconst immediate: Message[] = [];\n\tconst deferred: Message[] = [];\n\tconst terminal: Message[] = [];\n\tfor (const m of messages) {\n\t\tif (isPhase2Message(m)) {\n\t\t\tdeferred.push(m);\n\t\t} else if (isTerminalMessage(m[0])) {\n\t\t\tterminal.push(m);\n\t\t} else {\n\t\t\timmediate.push(m);\n\t\t}\n\t}\n\treturn { immediate, deferred, terminal };\n}\n\n/**\n * Delivers messages downstream through `sink`, applying batch semantics and\n * canonical tier-based ordering (see `messages.ts`):\n *\n * 1. **Immediate** (tier 0–2, 5): START, DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN,\n * unknown — delivered synchronously.\n * 2. **Phase-2** (tier 3): DATA, RESOLVED — deferred while `isBatching()`.\n * 3. **Terminal** (tier 4): COMPLETE, ERROR — always delivered after phase-2.\n * When batching, terminal is queued after deferred phase-2 in the pending list.\n * When not batching, terminal is delivered after phase-2 synchronously.\n *\n * This ordering prevents the \"COMPLETE-before-DATA\" class of bugs: terminal\n * signals never make a node terminal before phase-2 values reach sinks,\n * regardless of how the source assembled the message array.\n *\n * @param sink — Sink callback. May be called up to three times per invocation\n * (immediate, deferred, terminal) when not batching.\n * @param messages — Full `[[Type, Data?], ...]` array for one downstream delivery.\n * @param phase — Starting delivery phase (`2` = data, `3` = terminal). Default `2`.\n * @param options - Optional configuration.\n * @option strategy | `\"partition\"` or `\"sequential\"` | `\"partition\"` | `\"partition\"` groups by tier; `\"sequential\"` preserves message order within each tier using `messageTier()` classification.\n * @returns `void` — delivery is performed through `sink` callbacks, synchronously\n * or deferred into the active batch queue.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.downWithBatch((msgs) => console.log(msgs), [[core.DIRTY], [core.DATA, 42]]);\n * ```\n *\n * @category core\n */\n/** Delivery strategy for {@link downWithBatch}. Mirrors Python `DownStrategy`. */\nexport type DownStrategy = \"partition\" | \"sequential\";\n\nexport function downWithBatch(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n\toptions?: { strategy?: DownStrategy },\n): void {\n\tif (messages.length === 0) {\n\t\treturn;\n\t}\n\n\tif (options?.strategy === \"sequential\") {\n\t\t_downSequential(sink, messages, phase);\n\t\treturn;\n\t}\n\n\tconst queue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\n\t// Fast path: single-message batches (most common in graph-internal propagation)\n\t// skip partitionForBatch allocation entirely.\n\tif (messages.length === 1) {\n\t\tconst t = messages[0][0];\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else if (isTerminalMessage(t)) {\n\t\t\t// Terminal single message: defer when batching so any preceding\n\t\t\t// phase-2 in the queue flushes first.\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate: deliver synchronously.\n\t\t\tsink(messages);\n\t\t}\n\t\treturn;\n\t}\n\t// Multi-message: three-way partition by tier.\n\tconst { immediate, deferred, terminal } = partitionForBatch(messages);\n\n\t// 1. Immediate signals (tier 0–2, 5) — deliver synchronously now.\n\tif (immediate.length > 0) {\n\t\tsink(immediate);\n\t}\n\n\t// 2. Deferred (tier 3) + Terminal (tier 4) — canonical order preserved.\n\tif (isBatching()) {\n\t\tif (deferred.length > 0) {\n\t\t\tqueue.push(() => sink(deferred));\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tqueue.push(() => sink(terminal));\n\t\t}\n\t} else {\n\t\tif (deferred.length > 0) {\n\t\t\tsink(deferred);\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tsink(terminal);\n\t\t}\n\t}\n}\n\n/**\n * Sequential strategy: walk messages one at a time. Phase-2 (DATA/RESOLVED) and\n * terminal (COMPLETE/ERROR) messages are deferred while batching; immediate\n * messages deliver synchronously. Matches graphrefly-py `_down_sequential`.\n *\n * Tier legend (after START introduction):\n * 0 = START — immediate, delivered before other tiers\n * 1 = DIRTY, INVALIDATE — immediate\n * 2 = PAUSE, RESUME — immediate\n * 3 = DATA, RESOLVED — deferred inside batch\n * 4 = COMPLETE, ERROR — deferred to phase-3 queue (drains after data)\n * 5 = TEARDOWN — deferred to phase-3 queue (drains after data)\n */\nfunction _downSequential(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n): void {\n\tconst dataQueue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\tfor (const msg of messages) {\n\t\tconst tier = messageTier(msg[0]);\n\t\tif (tier === 3) {\n\t\t\t// Phase-2 (DATA/RESOLVED): defer while batching.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tdataQueue.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else if (tier >= 4) {\n\t\t\t// Terminal + destruction (COMPLETE/ERROR/TEARDOWN): always route to\n\t\t\t// phase-3 queue — terminals and teardown must drain after all phase-2\n\t\t\t// work to prevent premature termination or early resource release.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tpendingPhase3.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate (START, DIRTY, INVALIDATE, PAUSE, RESUME):\n\t\t\t// deliver synchronously.\n\t\t\tsink([msg]);\n\t\t}\n\t}\n}\n","/**\n * Centralised timestamp utilities.\n *\n * Convention: all graphrefly-ts timestamps use nanoseconds (`_ns` suffix).\n *\n * - {@link monotonicNs} — monotonic clock (ordering, durations, timeline events).\n * - {@link wallClockNs} — wall-clock (mutation attribution, cron emission).\n *\n * **Precision limits (JS platform):**\n *\n * - `monotonicNs`: effective ~microsecond precision. `performance.now()` returns\n * milliseconds with ~5µs resolution; the last 3 digits of the nanosecond value\n * are always zero. Python's `time.monotonic_ns()` gives true nanoseconds.\n *\n * - `wallClockNs`: ~256ns precision loss at current epoch. `Date.now() * 1e6`\n * produces values around 1.8×10¹⁸ which exceed IEEE 754's 2⁵³ safe integer\n * limit. Python's `time.time_ns()` (arbitrary-precision `int`) has no loss.\n * In practice this is irrelevant — JS is single-threaded, so sub-microsecond\n * timestamp collisions cannot occur.\n */\n\n/** Monotonic nanosecond timestamp via `performance.now()`. */\nexport function monotonicNs(): number {\n\treturn Math.trunc(performance.now() * 1_000_000);\n}\n\n/** Wall-clock nanosecond timestamp via `Date.now()`. */\nexport function wallClockNs(): number {\n\treturn Date.now() * 1_000_000;\n}\n","import type { Actor } from \"./actor.js\";\n\n/**\n * Actions checked by {@link NodeGuard}. `write` covers both {@link Node.down} and\n * {@link Node.up} today; finer-grained strings may be added later (e.g. `\"write.data\"`).\n */\nexport type GuardAction = \"write\" | \"signal\" | \"observe\" | (string & {});\n\nexport type NodeGuard = (actor: Actor, action: GuardAction) => boolean;\n\nexport type GuardDeniedDetails = {\n\tactor: Actor;\n\taction: GuardAction;\n\t/** Registry or options name when known */\n\tnodeName?: string;\n};\n\n/**\n * Thrown when a {@link NodeGuard} denies an action for a given actor.\n *\n * Carries the rejected `actor`, `action`, and optional `nodeName` for diagnostic\n * messages and middleware error handling.\n *\n * @example\n * ```ts\n * import { GuardDenied, policy } from \"@graphrefly/graphrefly-ts\";\n *\n * const guard = policy((allow) => { allow(\"observe\"); });\n * try {\n * if (!guard({ type: \"llm\", id: \"agent-1\" }, \"write\")) {\n * throw new GuardDenied(\n * { actor: { type: \"llm\", id: \"agent-1\" }, action: \"write\", nodeName: \"userInput\" },\n * );\n * }\n * } catch (e) {\n * if (e instanceof GuardDenied) console.error(e.action, e.actor.type); // \"write\" \"llm\"\n * }\n * ```\n */\nexport class GuardDenied extends Error {\n\treadonly actor: Actor;\n\treadonly action: GuardAction;\n\treadonly nodeName?: string;\n\n\t/**\n\t * @param details - Actor, action, and optional node name for the denial.\n\t * @param message - Optional override for the default error message.\n\t */\n\tconstructor(details: GuardDeniedDetails, message?: string) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\t`GuardDenied: action \"${String(details.action)}\" denied for actor type \"${String(details.actor.type)}\"`,\n\t\t);\n\t\tthis.name = \"GuardDenied\";\n\t\tthis.actor = details.actor;\n\t\tthis.action = details.action;\n\t\tthis.nodeName = details.nodeName;\n\t}\n\n\t/** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */\n\tget node(): string | undefined {\n\t\treturn this.nodeName;\n\t}\n}\n\ntype Where = (actor: Actor) => boolean;\n\ntype Rule = {\n\tkind: \"allow\" | \"deny\";\n\tactions: Set<GuardAction>;\n\twhere: Where;\n};\n\nfunction normalizeActions(action: GuardAction | readonly GuardAction[]): GuardAction[] {\n\tif (Array.isArray(action)) {\n\t\treturn [...action];\n\t}\n\treturn [action as GuardAction];\n}\n\nfunction matchesActions(set: Set<GuardAction>, action: GuardAction): boolean {\n\treturn set.has(action) || set.has(\"*\" as GuardAction);\n}\n\nexport type PolicyAllow = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyDeny = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyRuleData = {\n\teffect: \"allow\" | \"deny\";\n\taction: GuardAction | readonly GuardAction[];\n\tactorType?: string | readonly string[];\n\tactorId?: string | readonly string[];\n\tclaims?: Record<string, unknown>;\n};\n\n/**\n * Declarative guard builder. Precedence: any matching **deny** blocks even if an allow also matches.\n * If no rule matches, the guard returns `false` (deny-by-default). Aligned with graphrefly-py `policy()`.\n *\n * @param build - Callback that registers `allow(...)` / `deny(...)` rules in order.\n * @returns A `NodeGuard` for use as `node({ guard })`.\n *\n * @example\n * ```ts\n * const guard = policy((allow, deny) => {\n * allow(\"observe\");\n * deny(\"write\", { where: (a) => a.type === \"llm\" });\n * });\n * ```\n */\nexport function policy(build: (allow: PolicyAllow, deny: PolicyDeny) => void): NodeGuard {\n\tconst rules: Rule[] = [];\n\tconst allow: PolicyAllow = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"allow\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tconst deny: PolicyDeny = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"deny\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tbuild(allow, deny);\n\treturn (actor, action) => {\n\t\tlet denied = false;\n\t\tlet allowed = false;\n\t\tfor (const r of rules) {\n\t\t\tif (!matchesActions(r.actions, action)) continue;\n\t\t\tif (!r.where(actor)) continue;\n\t\t\tif (r.kind === \"deny\") {\n\t\t\t\tdenied = true;\n\t\t\t} else {\n\t\t\t\tallowed = true;\n\t\t\t}\n\t\t}\n\t\tif (denied) return false;\n\t\treturn allowed;\n\t};\n}\n\n/**\n * Rebuild a declarative guard from persisted policy data (snapshot-safe).\n *\n * Rules are deny-overrides, same semantics as {@link policy}.\n */\nexport function policyFromRules(rules: readonly PolicyRuleData[]): NodeGuard {\n\treturn policy((allow, deny) => {\n\t\tfor (const rule of rules) {\n\t\t\tconst actorTypes =\n\t\t\t\trule.actorType == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);\n\t\t\tconst actorIds =\n\t\t\t\trule.actorId == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);\n\t\t\tconst claimEntries = Object.entries(rule.claims ?? {});\n\t\t\tconst where: Where = (actor) => {\n\t\t\t\tif (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;\n\t\t\t\tif (actorIds !== null && !actorIds.has(String(actor.id ?? \"\"))) return false;\n\t\t\t\tfor (const [key, value] of claimEntries) {\n\t\t\t\t\tif ((actor as Record<string, unknown>)[key] !== value) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tif (rule.effect === \"deny\") {\n\t\t\t\tdeny(rule.action, { where });\n\t\t\t} else {\n\t\t\t\tallow(rule.action, { where });\n\t\t\t}\n\t\t}\n\t});\n}\n\nconst STANDARD_WRITE_TYPES = [\"human\", \"llm\", \"wallet\", \"system\"] as const;\n\n/**\n * Derives a best-effort `meta.access` hint string by probing `guard` with the\n * standard actor types `human`, `llm`, `wallet`, `system` for the `\"write\"` action\n * (roadmap 1.5). Aligned with graphrefly-py `access_hint_for_guard`.\n *\n * @param guard - Guard function to probe (typically from {@link policy}).\n * @returns `\"restricted\"` when no standard type is allowed; `\"both\"` when both\n * `human` and `llm` are allowed (plus optionally `system`); the single allowed\n * type name when only one passes; or a `\"+\"` joined list otherwise.\n *\n * @example\n * ```ts\n * import { policy, accessHintForGuard } from \"@graphrefly/graphrefly-ts\";\n *\n * const guardBoth = policy((allow) => { allow(\"write\"); });\n * accessHintForGuard(guardBoth); // \"both\"\n *\n * const guardHuman = policy((allow) => {\n * allow(\"write\", { where: (a) => a.type === \"human\" });\n * });\n * accessHintForGuard(guardHuman); // \"human\"\n * ```\n */\nexport function accessHintForGuard(guard: NodeGuard): string {\n\tconst allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: \"\" }, \"write\"));\n\tif (allowed.length === 0) return \"restricted\";\n\tif (\n\t\tallowed.includes(\"human\") &&\n\t\tallowed.includes(\"llm\") &&\n\t\tallowed.every((t) => t === \"human\" || t === \"llm\" || t === \"system\")\n\t) {\n\t\treturn \"both\";\n\t}\n\tif (allowed.length === 1) return allowed[0];\n\treturn allowed.join(\"+\");\n}\n","/**\n * Who is performing an operation (attribution + ABAC input).\n *\n * @see GRAPHREFLY-SPEC — roadmap Phase 1.5 (Actor & Guard).\n */\nexport type Actor = {\n\ttype: \"human\" | \"llm\" | \"wallet\" | \"system\" | string;\n\tid: string;\n} & Record<string, unknown>;\n\n/** Default actor when none is passed ({@link normalizeActor}). */\nexport const DEFAULT_ACTOR: Actor = { type: \"system\", id: \"\" };\n\n/**\n * Fills missing `type` / `id` on an actor and returns {@link DEFAULT_ACTOR} when input is undefined.\n *\n * @param actor - Optional partial actor from a transport hint.\n * @returns A normalized `Actor` safe to pass to guards and graph APIs.\n *\n * @example\n * ```ts\n * import { normalizeActor } from \"@graphrefly/graphrefly-ts\";\n *\n * normalizeActor({ type: \"human\", id: \"u1\" });\n * ```\n */\nexport function normalizeActor(actor?: Actor): Actor {\n\tif (actor == null) return DEFAULT_ACTOR;\n\tconst { type, id, ...rest } = actor;\n\treturn {\n\t\ttype: type ?? \"system\",\n\t\tid: id ?? \"\",\n\t\t...rest,\n\t} as Actor;\n}\n","/**\n * Node versioning — GRAPHREFLY-SPEC §7.\n *\n * Progressive, optional versioning for node identity and change tracking.\n *\n * - **V0**: `id` + `version` — identity & change detection (~16 bytes overhead)\n * - **V1**: + `cid` + `prev` — content addressing & linked history (~60 bytes overhead)\n *\n * **Lifecycle notes:**\n * - Version advances only on DATA (not RESOLVED, INVALIDATE, or TEARDOWN).\n * - `resetOnTeardown` clears the cached value but does NOT reset versioning state.\n * After teardown, `v.cid` still reflects the last DATA value, not the cleared cache.\n * The invariant `hash(node.get()) === v.cid` only holds in `settled`/`resolved` status.\n * - Resubscribable nodes preserve versioning across subscription lifetimes (monotonic counter).\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** V0: identity + monotonic version counter. */\nexport type V0 = {\n\treadonly id: string;\n\tversion: number;\n};\n\n/** V1: V0 + content-addressed identifier + previous cid link. */\nexport type V1 = V0 & {\n\tcid: string;\n\tprev: string | null;\n};\n\n/** Union of all versioning info shapes. */\nexport type NodeVersionInfo = V0 | V1;\n\n/** Supported versioning levels (extensible to 2, 3 later). */\nexport type VersioningLevel = 0 | 1;\n\n/** Function that hashes a value to a hex string (for V1 cid). */\nexport type HashFn = (value: unknown) => string;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface VersioningOptions {\n\t/** Override auto-generated id. */\n\tid?: string;\n\t/** Custom hash function for V1 cid (default: SHA-256 truncated to 16 hex chars). */\n\thash?: HashFn;\n}\n\n// ---------------------------------------------------------------------------\n// Default hash\n// ---------------------------------------------------------------------------\n\n/**\n * Canonicalize a value for deterministic cross-language hashing.\n *\n * - Integer-valued floats normalize to integer strings (`1.0` → `1`).\n * - `NaN`, `Infinity`, `-Infinity` are rejected (no JSON equivalent).\n * - `undefined` normalizes to `null`.\n * - Object keys are sorted lexicographically.\n *\n * This ensures TS `JSON.stringify` and Python `json.dumps(sort_keys=True)`\n * produce identical output for the same logical value.\n */\nexport function canonicalizeForHash(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow new TypeError(`Cannot hash non-finite number: ${value}`);\n\t\t}\n\t\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. ` +\n\t\t\t\t\t\"Cross-language cid parity is not guaranteed for unsafe integers.\",\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\" || typeof value === \"boolean\" || value === null) {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalizeForHash);\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst sorted: Record<string, unknown> = {};\n\t\tfor (const k of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tsorted[k] = canonicalizeForHash((value as Record<string, unknown>)[k]);\n\t\t}\n\t\treturn sorted;\n\t}\n\t// Fallback: coerce to null (bigint, symbol, function)\n\treturn null;\n}\n\n/**\n * Default content hash: SHA-256 of deterministic JSON, truncated to 16 hex chars (~64-bit).\n * Uses {@link canonicalizeForHash} for cross-language parity with Python `default_hash`.\n */\nexport function defaultHash(value: unknown): string {\n\tconst canonical = canonicalizeForHash(value ?? null);\n\tconst json = JSON.stringify(canonical);\n\treturn createHash(\"sha256\").update(json).digest(\"hex\").slice(0, 16);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create initial versioning state for a node.\n *\n * @param level - 0 for V0, 1 for V1.\n * @param initialValue - The node's initial cached value (used for V1 cid).\n * @param opts - Optional overrides (id, hash).\n */\nexport function createVersioning(\n\tlevel: VersioningLevel,\n\tinitialValue: unknown,\n\topts?: VersioningOptions,\n): NodeVersionInfo {\n\tconst id = opts?.id ?? randomUUID();\n\tif (level === 0) {\n\t\treturn { id, version: 0 } satisfies V0;\n\t}\n\tconst hash = opts?.hash ?? defaultHash;\n\tconst cid = hash(initialValue);\n\treturn { id, version: 0, cid, prev: null } satisfies V1;\n}\n\n// ---------------------------------------------------------------------------\n// Advance\n// ---------------------------------------------------------------------------\n\n/**\n * Advance versioning state after a DATA emission (value changed).\n *\n * Mutates `info` in place for performance (called on every DATA).\n * Only call when the cached value has actually changed (not on RESOLVED).\n *\n * @param info - The node's current versioning state.\n * @param newValue - The new cached value.\n * @param hashFn - Hash function (only used for V1).\n */\nexport function advanceVersion(info: NodeVersionInfo, newValue: unknown, hashFn: HashFn): void {\n\tinfo.version += 1;\n\tif (\"cid\" in info) {\n\t\t(info as V1).prev = (info as V1).cid;\n\t\t(info as V1).cid = hashFn(newValue);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this V1 versioning info? */\nexport function isV1(info: NodeVersionInfo): info is V1 {\n\treturn \"cid\" in info;\n}\n","/**\n * `NodeBase` — abstract class implementing the {@link Node} protocol with\n * lifecycle machinery shared between {@link NodeImpl} (static deps) and\n * {@link DynamicNodeImpl} (runtime-tracked deps).\n *\n * **Responsibilities (shared):**\n * - Identity (name, describeKind, meta, guard, versioning)\n * - Cache + status lifecycle (`_cached`, `_status`, `_terminal`)\n * - Sink storage (null / single / Set fast paths)\n * - `subscribe()` with START handshake + first-subscriber activation\n * - `_downInternal` → `_downToSinks` delivery pipeline (via `downWithBatch`)\n * - `_downAutoValue` (value → protocol framing with equals)\n * - `_handleLocalLifecycle` (cached/status/terminal updates + meta propagation)\n *\n * **Subclass hooks (abstract):**\n * - `_onActivate()` — called when sinkCount transitions 0 → 1\n * - `_doDeactivate()` — cleanup on deactivation (at-most-once, guarded by `_onDeactivate`)\n * - `up()` / `unsubscribe()` / `_upInternal()` — dep-iteration specifics\n * - `_createMetaNode()` — meta companion factory (avoids circular imports)\n *\n * See GRAPHREFLY-SPEC §2 and COMPOSITION-GUIDE §1 for protocol contracts.\n */\n\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, NodeVersionInfo, VersioningLevel } from \"./versioning.js\";\nimport { advanceVersion, createVersioning, defaultHash } from \"./versioning.js\";\n\n// ---------------------------------------------------------------------------\n// Symbols\n// ---------------------------------------------------------------------------\n\n/**\n * Internal sentinel value: \"no cached value has been set or emitted.\"\n * Used instead of `undefined` so that `undefined` can be a valid emitted value.\n */\nexport const NO_VALUE: unique symbol = Symbol.for(\"graphrefly/NO_VALUE\");\n\n/**\n * Branded symbol that marks a {@link CleanupResult} wrapper — prevents\n * duck-type collisions with domain objects that happen to have a `cleanup`\n * property.\n */\nexport const CLEANUP_RESULT: unique symbol = Symbol.for(\"graphrefly/CLEANUP_RESULT\");\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Lifecycle status of a node (GRAPHREFLY-SPEC §2.2). */\nexport type NodeStatus =\n\t| \"disconnected\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\n/** Callback that receives downstream message batches. */\nexport type NodeSink = (messages: Messages) => void;\n\n/** Imperative actions available inside a node's compute function. */\nexport interface NodeActions {\n\t/** Emit raw messages downstream. */\n\tdown(messages: Messages): void;\n\t/** Emit a single value (auto-wraps in DIRTY/DATA or DIRTY/RESOLVED). */\n\temit(value: unknown): void;\n\t/** Send messages upstream toward sources. */\n\tup(messages: Messages): void;\n}\n\n/**\n * Callback for intercepting messages before the default dispatch (§2.6).\n *\n * Called for every message from every dep. Return `true` to consume\n * (skip default handling), or `false` to let default dispatch run.\n */\nexport type OnMessageHandler = (msg: Message, depIndex: number, actions: NodeActions) => boolean;\n\n/**\n * Internal inspector hook (opt-in): emits dependency message and run events\n * for graph-level observability features (`observe(..., { causal|derived })`).\n */\nexport type NodeInspectorHookEvent =\n\t| { kind: \"dep_message\"; depIndex: number; message: Message }\n\t| { kind: \"run\"; depValues: readonly unknown[] };\n\nexport type NodeInspectorHook = (event: NodeInspectorHookEvent) => void;\n\n/** Explicit describe `type` for {@link Graph.describe} (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\n/** Options accepted by every node constructor. */\nexport interface NodeOptions {\n\tname?: string;\n\t/**\n\t * Overrides inferred `type` in describe output. Sugar constructors set this;\n\t * omit to infer from deps / fn / manual emit usage.\n\t */\n\tdescribeKind?: NodeDescribeKind;\n\t/** Equality check for RESOLVED detection. Defaults to `Object.is`. */\n\tequals?: (a: unknown, b: unknown) => boolean;\n\tinitial?: unknown;\n\t/**\n\t * Each key becomes an independently subscribable companion node.\n\t * Meta nodes outlive the parent's subscription lifecycle: when all sinks\n\t * unsubscribe the parent deactivates but meta nodes stay alive.\n\t * Send `[[TEARDOWN]]` to the parent to release meta node resources.\n\t */\n\tmeta?: Record<string, unknown>;\n\t/** Allow fresh subscriptions after COMPLETE/ERROR. */\n\tresubscribable?: boolean;\n\t/**\n\t * Invoked when a new {@link Node.subscribe} clears a terminal state on a\n\t * resubscribable node — reset operator-local counters/accumulators here.\n\t */\n\tonResubscribe?: () => void;\n\t/** Clear cached value on TEARDOWN. */\n\tresetOnTeardown?: boolean;\n\t/**\n\t * When `true` (default), auto-emit `[[COMPLETE]]` when all deps complete\n\t * (spec §1.3.5). Set `false` for derived/operator nodes that should not\n\t * auto-complete.\n\t */\n\tcompleteWhenDepsComplete?: boolean;\n\t/**\n\t * Intercept messages before the default dispatch (spec §2.6).\n\t *\n\t * Return `true` to consume the message (skip default handling),\n\t * or `false` to let the default dispatch run.\n\t */\n\tonMessage?: OnMessageHandler;\n\t/**\n\t * ABAC: `(actor, action) => boolean`. `write` applies to both {@link Node.down} and {@link Node.up}.\n\t * Companion {@link NodeOptions.meta | meta} nodes inherit this guard from the primary.\n\t */\n\tguard?: NodeGuard;\n\t/** Opt-in versioning level (GRAPHREFLY-SPEC §7). */\n\tversioning?: VersioningLevel;\n\t/** Override auto-generated versioning id. */\n\tversioningId?: string;\n\t/** Custom hash function for V1 cid computation. */\n\tversioningHash?: HashFn;\n}\n\n/** Actor/delivery context for {@link Node.down} and {@link Node.up}. */\nexport type NodeTransportOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips guard checks (reactive internals, graph lifecycle TEARDOWN, etc.).\n\t * Not for untrusted call sites.\n\t */\n\tinternal?: boolean;\n\t/**\n\t * `signal` for {@link Graph.signal} deliveries; default `write` for {@link Graph.set}\n\t * and direct `down`.\n\t */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/** Optional hints passed to {@link Node.subscribe}. */\nexport interface SubscribeHints {\n\t/**\n\t * Subscriber has exactly one dep with `fn` — the source may skip DIRTY\n\t * dispatch when this is the sole subscriber. The subscriber synthesizes\n\t * dirty state locally.\n\t */\n\tsingleDep?: boolean;\n\t/**\n\t * Actor to check against the node's `observe` guard. When set,\n\t * `subscribe()` throws {@link GuardDenied} if the actor is not permitted\n\t * to observe this node.\n\t */\n\tactor?: Actor;\n}\n\n/** A reactive node in the GraphReFly protocol. */\nexport interface Node<T = unknown> {\n\treadonly name?: string;\n\treadonly status: NodeStatus;\n\treadonly meta: Record<string, Node>;\n\t/** Returns the current cached value. */\n\tget(): T | undefined;\n\t/** Push messages downstream. */\n\tdown(messages: Messages, options?: NodeTransportOptions): void;\n\t/**\n\t * Registers a sink to receive downstream messages.\n\t *\n\t * @param sink - Callback receiving message batches.\n\t * @param hints - Optional optimization hints (e.g. `{ singleDep: true }`).\n\t * @returns An unsubscribe function (idempotent).\n\t */\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void;\n\t/** Send messages upstream (present on nodes with deps). */\n\tup?: (messages: Messages, options?: NodeTransportOptions) => void;\n\t/** Disconnect from upstream deps (present on nodes with deps). */\n\tunsubscribe?: () => void;\n\t/** Last successful guarded `down` / `up` (not set for `internal` deliveries). */\n\treadonly lastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/** Whether `actor` may {@link Graph.observe} this node. */\n\tallowsObserve(actor: Actor): boolean;\n\t/** Whether a {@link NodeOptions.guard | guard} is installed. */\n\thasGuard(): boolean;\n\t/** Versioning info (GRAPHREFLY-SPEC §7). `undefined` when versioning is not enabled. */\n\treadonly v: Readonly<NodeVersionInfo> | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Cleanup result wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Explicit cleanup wrapper. When a node fn returns `{ cleanup, value? }`,\n * `cleanup` is registered as the teardown/recompute cleanup and `value`\n * (if present) is emitted as data. This avoids the ambiguity where returning\n * a plain function is silently consumed as cleanup instead of emitted as data.\n */\nexport type CleanupResult<T = unknown> = {\n\treadonly [CLEANUP_RESULT]: true;\n\tcleanup: () => void;\n\tvalue?: T;\n};\n\n/** Create a branded {@link CleanupResult}. */\nexport function cleanupResult<T>(cleanup: () => void): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, value: T): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, ...args: [] | [T]): CleanupResult<T> {\n\tconst r: CleanupResult<T> = { [CLEANUP_RESULT]: true, cleanup };\n\tif (args.length > 0) r.value = args[0];\n\treturn r;\n}\n\nexport const isCleanupResult = (value: unknown): value is CleanupResult =>\n\ttypeof value === \"object\" && value !== null && CLEANUP_RESULT in value;\n\nexport const isCleanupFn = (value: unknown): value is () => void => typeof value === \"function\";\n\n// ---------------------------------------------------------------------------\n// Status transitions\n// ---------------------------------------------------------------------------\n\n/**\n * Returns the post-message status for `status` after processing `msg`.\n * START is informational and does not transition status.\n */\nexport function statusAfterMessage(status: NodeStatus, msg: Message): NodeStatus {\n\tconst t = msg[0];\n\tif (t === DIRTY) return \"dirty\";\n\tif (t === DATA) return \"settled\";\n\tif (t === RESOLVED) return \"resolved\";\n\tif (t === COMPLETE) return \"completed\";\n\tif (t === ERROR) return \"errored\";\n\tif (t === INVALIDATE) return \"dirty\";\n\tif (t === TEARDOWN) return \"disconnected\";\n\treturn status;\n}\n\n// ---------------------------------------------------------------------------\n// BitSet — dep mask helper (int fast path for ≤31 deps, array for more)\n// ---------------------------------------------------------------------------\n\n/**\n * Dep settlement tracker. IMPORTANT: `covers()` requires both operands to be\n * the same concrete type (both IntBitSet or both ArrayBitSet). Within a node,\n * all masks share the same `createBitSet(deps.length)` factory, so this is\n * always satisfied.\n */\nexport interface BitSet {\n\tset(index: number): void;\n\tclear(index: number): void;\n\thas(index: number): boolean;\n\t/** True when all bits in `other` are also set in `this`. */\n\tcovers(other: BitSet): boolean;\n\t/** True when at least one bit is set. */\n\tany(): boolean;\n\treset(): void;\n\t/** Set all bits in [0, size) — used for the pre-set-dirty wave trick. */\n\tsetAll(): void;\n}\n\nfunction createIntBitSet(size: number): BitSet {\n\tconst fullMask = size >= 32 ? -1 : ~(-1 << size);\n\tlet bits = 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\tbits |= 1 << i;\n\t\t},\n\t\tclear(i: number) {\n\t\t\tbits &= ~(1 << i);\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (bits & (1 << i)) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst otherBits = (other as unknown as { _bits(): number })._bits();\n\t\t\treturn (bits & otherBits) === otherBits;\n\t\t},\n\t\tany() {\n\t\t\treturn bits !== 0;\n\t\t},\n\t\treset() {\n\t\t\tbits = 0;\n\t\t},\n\t\tsetAll() {\n\t\t\tbits = fullMask;\n\t\t},\n\t\t_bits() {\n\t\t\treturn bits;\n\t\t},\n\t} as BitSet & { _bits(): number };\n}\n\nfunction createArrayBitSet(size: number): BitSet {\n\tconst words = new Uint32Array(Math.ceil(size / 32));\n\tconst lastBits = size % 32;\n\tconst lastWordMask = lastBits === 0 ? 0xffffffff : ((1 << lastBits) - 1) >>> 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\twords[i >>> 5] |= 1 << (i & 31);\n\t\t},\n\t\tclear(i: number) {\n\t\t\twords[i >>> 5] &= ~(1 << (i & 31));\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (words[i >>> 5] & (1 << (i & 31))) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst ow = (other as unknown as { _words: Uint32Array })._words;\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif ((words[w] & ow[w]) >>> 0 !== ow[w]) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\t\tany() {\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif (words[w] !== 0) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\treset() {\n\t\t\twords.fill(0);\n\t\t},\n\t\tsetAll() {\n\t\t\tfor (let w = 0; w < words.length - 1; w++) words[w] = 0xffffffff;\n\t\t\tif (words.length > 0) words[words.length - 1] = lastWordMask;\n\t\t},\n\t\t_words: words,\n\t} as unknown as BitSet;\n}\n\n/** Create a BitSet sized for `size` bits (≤31 uses fast int path). */\nexport function createBitSet(size: number): BitSet {\n\treturn size <= 31 ? createIntBitSet(size) : createArrayBitSet(size);\n}\n\n// ---------------------------------------------------------------------------\n// NodeBase\n// ---------------------------------------------------------------------------\n\n/**\n * Abstract base class for every node in the graph. Both {@link NodeImpl}\n * (static deps) and {@link DynamicNodeImpl} (runtime-tracked deps) extend\n * this to share subscribe/sink/lifecycle machinery.\n *\n * Invariants (see GRAPHREFLY-SPEC §2.2):\n * - `_sinkCount` always reflects the size of `_sinks`.\n * - `_cached === NO_VALUE` iff the node has never produced a value (SENTINEL).\n * - `_terminal` is set exactly once (per subscription cycle for resubscribable).\n * - `_onActivate` runs exactly once per activation cycle; `_doDeactivate`\n * runs at most once per deactivation (guarded by `_active` flag).\n *\n * ROM/RAM rule (GRAPHREFLY-SPEC §2.2): state nodes (no fn) preserve `_cached`\n * across disconnect — intrinsic, non-volatile. Compute nodes (derived,\n * producer, dynamic) clear `_cached` on disconnect in their subclass\n * `_doDeactivate` — their value is a function of live subscriptions.\n */\nexport abstract class NodeBase<T = unknown> implements Node<T> {\n\t// --- Identity (set once) ---\n\tprotected readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\t/** @internal Read by `describeNode` before inference. */\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\n\t// --- Options ---\n\tprotected readonly _equals: (a: unknown, b: unknown) => boolean;\n\tprotected readonly _resubscribable: boolean;\n\tprotected readonly _resetOnTeardown: boolean;\n\tprotected readonly _onResubscribe: (() => void) | undefined;\n\tprotected readonly _onMessage: OnMessageHandler | undefined;\n\t/** @internal Read by `describeNode` for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\t/** @internal Subclasses update this through {@link _recordMutation}. */\n\tprotected _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\n\t// --- Versioning ---\n\tprotected _hashFn: HashFn;\n\tprivate _versioning: NodeVersionInfo | undefined;\n\n\t// --- Lifecycle state ---\n\t/** @internal Read by `describeNode` and `graph.ts`. */\n\t_cached: T | typeof NO_VALUE;\n\t/** @internal Read externally via `get status()`. */\n\t_status: NodeStatus;\n\tprotected _terminal = false;\n\tprivate _active = false;\n\n\t// --- Sink storage ---\n\t/** @internal Read by `graph/profile.ts` for subscriber counts. */\n\t_sinkCount = 0;\n\tprotected _singleDepSinkCount = 0;\n\tprotected _singleDepSinks = new WeakSet<NodeSink>();\n\tprotected _sinks: NodeSink | Set<NodeSink> | null = null;\n\n\t// --- Actions + bound helpers ---\n\tprotected readonly _actions: NodeActions;\n\tprotected readonly _boundDownToSinks: (messages: Messages) => void;\n\n\t// --- Inspector hook (Graph observability) ---\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\n\tconstructor(opts: NodeOptions) {\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._resubscribable = opts.resubscribable ?? false;\n\t\tthis._resetOnTeardown = opts.resetOnTeardown ?? false;\n\t\tthis._onResubscribe = opts.onResubscribe;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._guard = opts.guard;\n\n\t\t// Cache pre-populated from `initial`, or SENTINEL.\n\t\tthis._cached = \"initial\" in opts ? (opts.initial as T) : NO_VALUE;\n\t\t// Initial status: state with value starts settled, otherwise disconnected.\n\t\tthis._status = \"disconnected\";\n\n\t\t// Versioning (GRAPHREFLY-SPEC §7)\n\t\tthis._hashFn = opts.versioningHash ?? defaultHash;\n\t\tthis._versioning =\n\t\t\topts.versioning != null\n\t\t\t\t? createVersioning(opts.versioning, this._cached === NO_VALUE ? undefined : this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\t// Build companion meta nodes — dispatched to subclass to avoid\n\t\t// circular imports (node-base → node → node-base).\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = this._createMetaNode(k, v, opts);\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions captured once — references `this` via an arrow/closure so\n\t\t// subclass hooks (e.g. `_onManualEmit`) fire on the right instance.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._onManualEmit();\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._onManualEmit();\n\t\t\t\tself._downAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tself._upInternal(messages);\n\t\t\t},\n\t\t};\n\n\t\tthis._boundDownToSinks = this._downToSinks.bind(this);\n\t}\n\n\t/**\n\t * Subclass hook invoked by `actions.down` / `actions.emit`. Default no-op;\n\t * {@link NodeImpl} overrides to set `_manualEmitUsed`.\n\t */\n\tprotected _onManualEmit(): void {\n\t\t/* no-op */\n\t}\n\n\t/**\n\t * Create a companion meta node. Called from the base constructor; must\n\t * not touch subclass fields that haven't been initialized yet (safe to\n\t * read from `opts`).\n\t */\n\tprotected abstract _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node;\n\n\t// --- Identity getters ---\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/** @internal Assigned by `Graph.add` when registered without an options `name`. */\n\t_assignRegistryName(localName: string): void {\n\t\tif (this._optsName !== undefined || this._registryName !== undefined) return;\n\t\tthis._registryName = localName;\n\t}\n\n\t/**\n\t * @internal Attach/remove inspector hook for graph-level observability.\n\t * Returns a disposer that restores the previous hook.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tconst prev = this._inspectorHook;\n\t\tthis._inspectorHook = hook;\n\t\treturn () => {\n\t\t\tif (this._inspectorHook === hook) {\n\t\t\t\tthis._inspectorHook = prev;\n\t\t\t}\n\t\t};\n\t}\n\n\t/** @internal Used by subclasses to surface inspector events. */\n\tprotected _emitInspectorHook(event: NodeInspectorHookEvent): void {\n\t\tthis._inspectorHook?.(event);\n\t}\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\tget v(): Readonly<NodeVersionInfo> | undefined {\n\t\treturn this._versioning;\n\t}\n\n\t/** @internal Used by `Graph.setVersioning` to retroactively apply versioning. */\n\t_applyVersioning(level: VersioningLevel, opts?: { id?: string; hash?: HashFn }): void {\n\t\tif (this._versioning != null) return;\n\t\tthis._hashFn = opts?.hash ?? this._hashFn;\n\t\tthis._versioning = createVersioning(\n\t\t\tlevel,\n\t\t\tthis._cached === NO_VALUE ? undefined : this._cached,\n\t\t\t{\n\t\t\t\tid: opts?.id,\n\t\t\t\thash: this._hashFn,\n\t\t\t},\n\t\t);\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\t// --- Public transport ---\n\n\tget(): T | undefined {\n\t\treturn this._cached === NO_VALUE ? undefined : this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\t/** @internal Record a successful guarded mutation (called by `down` and subclass `up`). */\n\tprotected _recordMutation(actor: Actor): void {\n\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t}\n\n\t/** Abstract — subclasses forward messages to dependencies (or no-op for sources). */\n\tabstract up(messages: Messages, options?: NodeTransportOptions): void;\n\n\t/** Abstract — subclasses release upstream subscriptions (or no-op for sources). */\n\tabstract unsubscribe(): void;\n\n\t/** Internal upstream-send used by `actions.up`. */\n\tprotected abstract _upInternal(messages: Messages): void;\n\n\t/** Called when `_sinkCount` transitions 0 → 1. */\n\tprotected abstract _onActivate(): void;\n\n\t/**\n\t * At-most-once deactivation guard. Both TEARDOWN (eager) and\n\t * unsubscribe-body (lazy) call this. The `_active` flag ensures\n\t * `_doDeactivate` runs exactly once per activation cycle.\n\t */\n\tprotected _onDeactivate(): void {\n\t\tif (!this._active) return;\n\t\tthis._active = false;\n\t\tthis._doDeactivate();\n\t}\n\n\t/** Subclass hook: cleanup on deactivation (called at most once). */\n\tprotected abstract _doDeactivate(): void;\n\n\t// --- Subscribe (uniform across node shapes) ---\n\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void {\n\t\tif (hints?.actor != null && this._guard != null) {\n\t\t\tconst actor = normalizeActor(hints.actor);\n\t\t\tif (!this._guard(actor, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\t// Resubscribable terminal reset — clear terminal + cache, fire hook.\n\t\tif (this._terminal && this._resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._status = \"disconnected\";\n\t\t\tthis._onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\t// §2.2 START handshake — delivered BEFORE registering sink in\n\t\t// `_sinks` so that re-entrant `_downToSinks` calls during\n\t\t// activation cannot reach the new sink before it receives START\n\t\t// (spec §1.3.8: START precedes any other message on a subscription).\n\t\t//\n\t\t// Wire shape:\n\t\t// SENTINEL cache → [[START]]\n\t\t// cached value → [[START], [DATA, cached]]\n\t\t//\n\t\t// DIRTY is intentionally NOT part of the handshake: nothing is\n\t\t// transitioning here, we're simply delivering the current state.\n\t\t// Downstream derived nodes mark both dirty+settled on DATA-without-\n\t\t// prior-DIRTY (spec §1.3.1 compat path), so wave tracking still\n\t\t// works without polluting observers with a spurious DIRTY.\n\t\t// §2.2 handshake: START (+ cached DATA if available). Terminal nodes\n\t\t// skip entirely — absence of START tells the subscriber the stream is\n\t\t// over (spec §2.2: \"absence of START means the subscription was never\n\t\t// established or the node is terminal\"). This is intentional: terminal\n\t\t// nodes release resources; replaying COMPLETE/ERROR to late subscribers\n\t\t// would require retaining the terminal cause indefinitely.\n\t\tif (!this._terminal) {\n\t\t\tconst startMessages: Messages =\n\t\t\t\tthis._cached === NO_VALUE ? [[START]] : [[START], [DATA, this._cached]];\n\t\t\tdownWithBatch(sink, startMessages);\n\t\t}\n\n\t\t// Register sink in the singleton / set storage — AFTER START so\n\t\t// re-entrant `_downToSinks` during `_onActivate` can reach it.\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\t// First subscriber triggers activation. May cause fn to run and emit\n\t\t// via `_downInternal` → `_downToSinks` to the new sink.\n\t\tif (this._sinkCount === 1 && !this._terminal) {\n\t\t\tthis._active = true;\n\t\t\tthis._onActivate();\n\t\t}\n\n\t\t// If activation did not produce a value (compute node blocked on\n\t\t// SENTINEL deps, or a source with no initial), surface \"pending\".\n\t\tif (!this._terminal && this._status === \"disconnected\" && this._cached === NO_VALUE) {\n\t\t\tthis._status = \"pending\";\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tif (this._singleDepSinks.has(sink)) {\n\t\t\t\tthis._singleDepSinkCount -= 1;\n\t\t\t\tthis._singleDepSinks.delete(sink);\n\t\t\t}\n\t\t\tif (this._sinks == null) return;\n\t\t\tif (typeof this._sinks === \"function\") {\n\t\t\t\tif (this._sinks === sink) this._sinks = null;\n\t\t\t} else {\n\t\t\t\tthis._sinks.delete(sink);\n\t\t\t\tif (this._sinks.size === 1) {\n\t\t\t\t\tconst [only] = this._sinks;\n\t\t\t\t\tthis._sinks = only;\n\t\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\t\tthis._sinks = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._sinks == null) {\n\t\t\t\tthis._onDeactivate();\n\t\t\t}\n\t\t};\n\t}\n\n\t// --- Down pipeline ---\n\n\t/**\n\t * Core outgoing dispatch. Applies terminal filter + local lifecycle\n\t * update, then hands messages to `downWithBatch` for tier-aware delivery.\n\t */\n\tprotected _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._resubscribable) {\n\t\t\t// After terminal, only TEARDOWN / INVALIDATE still propagate\n\t\t\t// (so graph teardown and cache-clear still work).\n\t\t\tconst pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (pass.length === 0) return;\n\t\t\tsinkMessages = pass as Messages;\n\t\t}\n\t\tthis._handleLocalLifecycle(sinkMessages);\n\t\t// Single-dep DIRTY-skip optimization: when this node's only sink is\n\t\t// single-dep AND the batch contains a phase-2 message (DATA/RESOLVED),\n\t\t// strip DIRTY from the outgoing batch. The downstream learns of the\n\t\t// value via the phase-2 message directly.\n\t\tif (this._canSkipDirty()) {\n\t\t\tlet hasPhase2 = false;\n\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\tconst t = sinkMessages[i][0];\n\t\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\t\thasPhase2 = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPhase2) {\n\t\t\t\tconst filtered: Message[] = [];\n\t\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\t\tif (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);\n\t\t\t\t}\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tdownWithBatch(this._boundDownToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tdownWithBatch(this._boundDownToSinks, sinkMessages);\n\t}\n\n\tprotected _canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\tprotected _downToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others mid-iteration.\n\t\t// Iterating the live Set would skip not-yet-visited sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\t/**\n\t * Update `_cached`, `_status`, `_terminal` from message batch before\n\t * delivery. Subclass hooks `_onInvalidate` / `_onTeardown` let\n\t * {@link NodeImpl} clear `_lastDepValues` and invoke cleanup fns.\n\t */\n\tprotected _handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (m.length < 2) {\n\t\t\t\t\t// §1.2: bare [DATA] without payload is a protocol violation.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\tthis._onInvalidate();\n\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t}\n\t\t\tthis._status = statusAfterMessage(this._status, m);\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._resetOnTeardown) {\n\t\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t\t}\n\t\t\t\tthis._onTeardown();\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\t// Force upstream disconnect immediately — don't wait for\n\t\t\t\t\t// downstream to unsubscribe. _onDeactivate's _active\n\t\t\t\t\t// guard ensures _doDeactivate runs at most once.\n\t\t\t\t\tthis._onDeactivate();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t !== TEARDOWN && propagatesToMeta(t)) {\n\t\t\t\tthis._propagateToMeta(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Subclass hook: invoked when INVALIDATE arrives (before `_cached` is\n\t * cleared). {@link NodeImpl} uses this to run the fn cleanup fn and\n\t * drop `_lastDepValues` so the next wave re-runs fn.\n\t */\n\tprotected _onInvalidate(): void {\n\t\t/* no-op default */\n\t}\n\n\t/**\n\t * Subclass hook: invoked when TEARDOWN arrives, before `_onDeactivate`.\n\t * {@link NodeImpl} uses this to run any pending cleanup fn.\n\t */\n\tprotected _onTeardown(): void {\n\t\t/* no-op default */\n\t}\n\n\t/** Forward a signal to all companion meta nodes (best-effort). */\n\tprotected _propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\t// Direct access through NodeBase — meta nodes are always NodeBase instances.\n\t\t\t\t(metaNode as NodeBase)._downInternal([[t]]);\n\t\t\t} catch {\n\t\t\t\t/* best-effort — other meta nodes still receive the signal */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Frame a computed value into the right protocol messages and dispatch\n\t * via `_downInternal`. Used by `_runFn` and `actions.emit`.\n\t */\n\tprotected _downAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tlet unchanged: boolean;\n\t\ttry {\n\t\t\tunchanged = this._cached !== NO_VALUE && this._equals(this._cached, value);\n\t\t} catch (eqErr) {\n\t\t\tconst eqMsg = eqErr instanceof Error ? eqErr.message : String(eqErr);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": equals threw: ${eqMsg}`, {\n\t\t\t\tcause: eqErr,\n\t\t\t});\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\treturn;\n\t\t}\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n}\n","/**\n * `NodeImpl` — the canonical node primitive for static (compile-time known)\n * dependency graphs. Covers state, producer, derived, effect, operator, and\n * passthrough shapes from a single class.\n *\n * Lifecycle machinery (subscribe + START handshake + `_downInternal` pipeline)\n * lives in {@link NodeBase}. This file only adds:\n * - Dep-wave tracking via pre-set dirty masks (first run and subsequent waves\n * share the same code path — see `_connectUpstream` + `_handleDepMessages`)\n * - `_runFn` with identity-skip optimization on `_lastDepValues`\n * - Producer start/stop tied to sink count\n * - ROM/RAM cache semantics: compute nodes clear `_cached` on disconnect,\n * state sources preserve it (see `_onDeactivate`).\n *\n * See GRAPHREFLY-SPEC §§2.1–2.8 and COMPOSITION-GUIDE §§1, 9.\n */\n\nimport { normalizeActor } from \"./actor.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport {\n\ttype BitSet,\n\tcreateBitSet,\n\tisCleanupFn,\n\tisCleanupResult,\n\tNO_VALUE,\n\ttype Node,\n\ttype NodeActions,\n\tNodeBase,\n\ttype NodeOptions,\n\ttype NodeTransportOptions,\n\ttype SubscribeHints,\n} from \"./node-base.js\";\n\n// Re-exports so downstream files keep importing from \"./node.js\".\nexport {\n\tCLEANUP_RESULT,\n\ttype CleanupResult,\n\tcleanupResult,\n\tNO_VALUE,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeInspectorHook,\n\ttype NodeInspectorHookEvent,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node-base.js\";\n\n/**\n * Compute function passed to `node(deps, fn, opts?)`.\n *\n * @returns A value to emit, `undefined` to skip emission, or a cleanup\n * function invoked before the next run or on teardown.\n */\nexport type NodeFn<T = unknown> = (\n\tdeps: readonly unknown[],\n\tactions: NodeActions,\n) => T | undefined | (() => void);\n\n// ---------------------------------------------------------------------------\n// NodeImpl\n// ---------------------------------------------------------------------------\n\n/**\n * Class-based implementation of the {@link Node} interface for static deps.\n *\n * All internal state is exposed as package-visible fields so introspection\n * (e.g. `describeNode`) can read them via `instanceof NodeImpl`.\n */\nexport class NodeImpl<T = unknown> extends NodeBase<T> {\n\t// --- Dep configuration (set once) ---\n\t_deps: readonly Node[];\n\t_fn: NodeFn<T> | undefined;\n\t_opts: NodeOptions;\n\t_hasDeps: boolean;\n\t_isSingleDep: boolean;\n\t_autoComplete: boolean;\n\n\t// --- Wave tracking masks ---\n\tprivate _depDirtyMask: BitSet;\n\tprivate _depSettledMask: BitSet;\n\tprivate _depCompleteMask: BitSet;\n\tprivate _allDepsCompleteMask: BitSet;\n\n\t// --- Identity-skip optimization ---\n\tprivate _lastDepValues: readonly unknown[] | undefined;\n\tprivate _cleanup: (() => void) | undefined;\n\n\t// --- Upstream bookkeeping ---\n\tprivate _upstreamUnsubs: Array<() => void> = [];\n\n\t// --- Fn behavior flag ---\n\t/** @internal Read by `describeNode` to infer `\"operator\"` label. */\n\t_manualEmitUsed = false;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn<T> | undefined, opts: NodeOptions) {\n\t\tsuper(opts);\n\t\tthis._deps = deps;\n\t\tthis._fn = fn;\n\t\tthis._opts = opts;\n\t\tthis._hasDeps = deps.length > 0;\n\t\tthis._isSingleDep = deps.length === 1 && fn != null;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\n\t\t// State-with-initial-value starts `settled`; everything else starts\n\t\t// `disconnected` and flips to `pending` at first subscribe if fn\n\t\t// hasn't produced a value yet.\n\t\tif (!this._hasDeps && fn == null && this._cached !== NO_VALUE) {\n\t\t\tthis._status = \"settled\";\n\t\t}\n\n\t\tthis._depDirtyMask = createBitSet(deps.length);\n\t\tthis._depSettledMask = createBitSet(deps.length);\n\t\tthis._depCompleteMask = createBitSet(deps.length);\n\t\tthis._allDepsCompleteMask = createBitSet(deps.length);\n\t\tfor (let i = 0; i < deps.length; i++) this._allDepsCompleteMask.set(i);\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\t// --- Meta node factory (called from base constructor) ---\n\n\tprotected _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node {\n\t\treturn node({\n\t\t\tinitial: initialValue,\n\t\t\tname: `${opts.name ?? \"node\"}:meta:${key}`,\n\t\t\tdescribeKind: \"state\",\n\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t});\n\t}\n\n\t// --- Manual emit tracker (set by actions.down / actions.emit) ---\n\n\tprotected override _onManualEmit(): void {\n\t\tthis._manualEmitUsed = true;\n\t}\n\n\t// --- Up / unsubscribe ---\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tif (options === undefined) {\n\t\t\t\tdep.up?.(messages);\n\t\t\t} else {\n\t\t\t\tdep.up?.(messages, options);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected _upInternal(messages: Messages): void {\n\t\tif (!this._hasDeps) return;\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tif (!this._hasDeps) return;\n\t\tthis._disconnectUpstream();\n\t}\n\n\t// --- Activation (first-subscriber / last-subscriber hooks) ---\n\n\tprotected _onActivate(): void {\n\t\tif (this._hasDeps) {\n\t\t\tthis._connectUpstream();\n\t\t\treturn;\n\t\t}\n\t\tif (this._fn) {\n\t\t\tthis._runFn();\n\t\t\treturn;\n\t\t}\n\t\t// Pure state node: no-op. Cached value (if any) is already delivered\n\t\t// through the subscribe-time START handshake.\n\t}\n\n\tprotected _doDeactivate(): void {\n\t\t// Release upstream subscriptions (for compute nodes with deps).\n\t\tthis._disconnectUpstream();\n\t\t// Flush pending cleanup fn (producers + derived both use `_cleanup`).\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\n\t\t// ROM/RAM rule (GRAPHREFLY-SPEC §2.2): compute nodes (anything with\n\t\t// `fn`) clear their cache on disconnect because their value is a\n\t\t// function of live subscriptions. State nodes (no fn) preserve\n\t\t// `_cached` — runtime writes survive across disconnect.\n\t\tif (this._fn != null) {\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._lastDepValues = undefined;\n\t\t}\n\n\t\t// Status: only transition to \"disconnected\" for compute nodes.\n\t\t// Pure state nodes remain in whatever status they were (usually\n\t\t// \"settled\" if they hold a value).\n\t\tif (this._hasDeps || this._fn != null) {\n\t\t\tthis._status = \"disconnected\";\n\t\t}\n\t}\n\n\t// --- INVALIDATE / TEARDOWN hooks (clear fn state) ---\n\n\tprotected override _onInvalidate(): void {\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\t\tthis._lastDepValues = undefined;\n\t}\n\n\tprotected override _onTeardown(): void {\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\t}\n\n\t// --- Upstream connect / disconnect ---\n\n\tprivate _connectUpstream(): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (this._upstreamUnsubs.length > 0) return; // already connected\n\n\t\t// Pre-set dirty mask to all-ones — wave completes when every dep\n\t\t// has settled at least once (spec §2.7, first-run gating).\n\t\tthis._depDirtyMask.setAll();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\t// Stay in \"disconnected\" until fn runs and updates status via\n\t\t// `_handleLocalLifecycle`. `subscribe()` will flip to \"pending\"\n\t\t// if fn did not run before returning.\n\n\t\tconst depValuesBefore = this._lastDepValues;\n\t\tconst subHints: SubscribeHints | undefined = this._isSingleDep\n\t\t\t? { singleDep: true }\n\t\t\t: undefined;\n\t\tfor (let i = 0; i < this._deps.length; i += 1) {\n\t\t\tconst dep = this._deps[i];\n\t\t\tthis._upstreamUnsubs.push(\n\t\t\t\tdep.subscribe((msgs) => this._handleDepMessages(i, msgs), subHints),\n\t\t\t);\n\t\t}\n\t\t// Fallback for `onMessage`-driven operators: if the subscribe loop\n\t\t// did not drive a wave completion (e.g. `switchMap`, `sample` —\n\t\t// operators whose `onMessage` consumes every dep message without\n\t\t// letting the mask-based wave progress), still run fn once so the\n\t\t// operator can initialize side-effect state (inner subscriptions,\n\t\t// cleanup fns, etc.). The fn-is-identity-check guards against\n\t\t// double runs when the normal wave path already fired.\n\t\tif (this._fn && this._onMessage && !this._terminal && this._lastDepValues === depValuesBefore) {\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\tprivate _disconnectUpstream(): void {\n\t\tif (this._upstreamUnsubs.length === 0) return;\n\t\tfor (const unsub of this._upstreamUnsubs.splice(0)) {\n\t\t\tunsub();\n\t\t}\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t}\n\n\t// --- Wave handling ---\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\tfor (const msg of messages) {\n\t\t\tthis._emitInspectorHook({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\t\t\t// User-defined message handler gets first look (spec §2.6).\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tconst consumed = this._onMessage(msg, index, this._actions);\n\t\t\t\t\tif (consumed) {\n\t\t\t\t\t\t// Clear the dep's pre-set dirty bit when onMessage\n\t\t\t\t\t\t// consumes a protocol-significant message:\n\t\t\t\t\t\t// - START: dep is fully user-managed (takeUntil notifier)\n\t\t\t\t\t\t// - DATA/RESOLVED: dep delivered real data via onMessage\n\t\t\t\t\t\t// instead of the normal wave path\n\t\t\t\t\t\t// This ensures the first-run gate tracks dep readiness\n\t\t\t\t\t\t// correctly even when onMessage bypasses wave tracking.\n\t\t\t\t\t\tif (t === START || t === DATA || t === RESOLVED) {\n\t\t\t\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\t\t\t\tthis._runFn();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Tier-0 (START) from a dep is informational — it's the dep's\n\t\t\t// subscribe handshake. It carries no wave-state implication: the\n\t\t\t// paired DATA (if present) is handled by the DATA branch.\n\t\t\tif (messageTier(t) < 1) continue;\n\n\t\t\tif (!this._fn) {\n\t\t\t\t// Passthrough: forward everything except COMPLETE when multi-dep\n\t\t\t\t// (multi-dep passthrough waits for all deps to complete, §1.3.5).\n\t\t\t\tif (t === COMPLETE && this._deps.length > 1) {\n\t\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._onDepDirty(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._onDepSettled(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\tthis._depSettledMask.clear(index);\n\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t} else if (!this._depDirtyMask.any() && this._status === \"dirty\") {\n\t\t\t\t\t// D2: dep went DIRTY→COMPLETE without DATA — the node is\n\t\t\t\t\t// stuck in \"dirty\" with no pending wave to resolve it.\n\t\t\t\t\t// Recompute so downstream sees RESOLVED (unchanged) or\n\t\t\t\t\t// DATA (changed).\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Forward unknown message types.\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\tprivate _onDepDirty(index: number): void {\n\t\t// Track wave transition: propagate DIRTY to our downstream ONLY on\n\t\t// the first dirty of a wave. During the initial wave, the dirty mask\n\t\t// is pre-set to all-ones by `_connectUpstream` so this branch never\n\t\t// fires — our own `_downAutoValue` emits `[[DIRTY],[DATA,v]]` to\n\t\t// downstream when fn completes.\n\t\tconst wasDirty = this._depDirtyMask.has(index);\n\t\tthis._depDirtyMask.set(index);\n\t\tthis._depSettledMask.clear(index);\n\t\tif (!wasDirty) {\n\t\t\tthis._downInternal([[DIRTY]]);\n\t\t}\n\t}\n\n\tprivate _onDepSettled(index: number): void {\n\t\t// Ensure dep is marked dirty. If the dep settled without a prior\n\t\t// DIRTY (spec §1.3.1 compat path for raw external sources), route\n\t\t// through `_onDepDirty` so that our own downstream sees DIRTY\n\t\t// before the resulting DATA/RESOLVED — preserving the two-phase\n\t\t// invariant from our node's perspective.\n\t\tif (!this._depDirtyMask.has(index)) {\n\t\t\tthis._onDepDirty(index);\n\t\t}\n\t\tthis._depSettledMask.set(index);\n\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\tthis._depDirtyMask.reset();\n\t\t\tthis._depSettledMask.reset();\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\tprivate _maybeCompleteFromDeps(): void {\n\t\tif (\n\t\t\tthis._autoComplete &&\n\t\t\tthis._deps.length > 0 &&\n\t\t\tthis._depCompleteMask.covers(this._allDepsCompleteMask)\n\t\t) {\n\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t}\n\t}\n\n\t// --- Fn execution ---\n\n\tprivate _runFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._terminal && !this._resubscribable) return;\n\n\t\ttry {\n\t\t\tconst n = this._deps.length;\n\t\t\tconst depValues = new Array(n);\n\t\t\tfor (let i = 0; i < n; i++) depValues[i] = this._deps[i].get();\n\n\t\t\t// Identity skip BEFORE cleanup: if all dep values are unchanged,\n\t\t\t// skip cleanup+fn so effect nodes don't teardown/restart on no-op.\n\t\t\tconst prev = this._lastDepValues;\n\t\t\tif (n > 0 && prev != null && prev.length === n) {\n\t\t\t\tlet allSame = true;\n\t\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\t\tif (!Object.is(depValues[i], prev[i])) {\n\t\t\t\t\t\tallSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (allSame) {\n\t\t\t\t\tif (this._status === \"dirty\") {\n\t\t\t\t\t\tthis._downInternal([[RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prevCleanup = this._cleanup;\n\t\t\tthis._cleanup = undefined;\n\t\t\tprevCleanup?.();\n\n\t\t\tthis._manualEmitUsed = false;\n\t\t\tthis._lastDepValues = depValues;\n\t\t\tthis._emitInspectorHook({ kind: \"run\", depValues });\n\n\t\t\tconst out = this._fn(depValues, this._actions);\n\n\t\t\t// Explicit cleanup wrapper: { cleanup, value? }\n\t\t\tif (isCleanupResult(out)) {\n\t\t\t\tthis._cleanup = out.cleanup;\n\t\t\t\tif (this._manualEmitUsed) return;\n\t\t\t\tif (\"value\" in out) {\n\t\t\t\t\tthis._downAutoValue(out.value);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Legacy: plain function return → cleanup.\n\t\t\tif (isCleanupFn(out)) {\n\t\t\t\tthis._cleanup = out;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this._manualEmitUsed) return;\n\t\t\tif (out === undefined) return;\n\t\t\tthis._downAutoValue(out);\n\t\t} catch (err) {\n\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, { cause: err });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nconst isNodeArray = (value: unknown): value is readonly Node[] => Array.isArray(value);\n\nconst isNodeOptions = (value: unknown): value is NodeOptions =>\n\ttypeof value === \"object\" && value != null && !Array.isArray(value);\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (§2).\n *\n * Typical shapes: `node([])` / `node([], opts)` for a manual source;\n * `node(producerFn, opts)` for a producer; `node(deps, computeFn, opts)` for\n * derived nodes and operators.\n *\n * @param depsOrFn - Dependency nodes, a {@link NodeFn} (producer), or {@link NodeOptions} alone.\n * @param fnOrOpts - With deps: compute function or options. Omitted for producer-only form.\n * @param optsArg - Options when both `deps` and `fn` are provided.\n * @returns `Node<T>` — lazy until subscribed.\n *\n * @remarks\n * **Protocol:** START handshake, DIRTY / DATA / RESOLVED ordering, completion,\n * and batch deferral follow `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n *\n * **`equals` and mutable values:** The default `Object.is` identity check is\n * correct for the common immutable-value case. If your node produces mutable\n * objects, provide a custom `equals` — otherwise `Object.is` always returns\n * `true` for the same reference and the node emits `RESOLVED` instead of `DATA`.\n *\n * **ROM/RAM (§2.2):** State nodes (no fn) preserve their cache across\n * disconnect — runtime writes survive. Compute nodes (derived, producer)\n * clear their cache on disconnect; reconnect re-runs fn.\n *\n * @example\n * ```ts\n * import { node, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = node([a], ([x]) => (x as number) + 1);\n * ```\n *\n * @category core\n */\nexport function node<T = unknown>(\n\tdepsOrFn?: readonly Node[] | NodeFn<T> | NodeOptions,\n\tfnOrOpts?: NodeFn<T> | NodeOptions,\n\toptsArg?: NodeOptions,\n): Node<T> {\n\tconst deps: readonly Node[] = isNodeArray(depsOrFn) ? depsOrFn : [];\n\tconst fn: NodeFn<T> | undefined =\n\t\ttypeof depsOrFn === \"function\"\n\t\t\t? depsOrFn\n\t\t\t: typeof fnOrOpts === \"function\"\n\t\t\t\t? fnOrOpts\n\t\t\t\t: undefined;\n\tlet opts: NodeOptions = {};\n\tif (isNodeArray(depsOrFn)) {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t} else if (isNodeOptions(depsOrFn)) {\n\t\topts = depsOrFn;\n\t} else {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t}\n\n\treturn new NodeImpl<T>(deps, fn, opts);\n}\n","/**\n * `dynamicNode` — runtime dep tracking with diamond resolution (Phase 0.3b).\n *\n * Unlike `node()` where deps are fixed at construction, `dynamicNode`\n * discovers deps at runtime via a tracking `get()` proxy. After each\n * recompute, deps are diffed: new deps are connected, removed deps are\n * disconnected, and bitmasks are rebuilt.\n *\n * Shares subscribe / sink / lifecycle machinery with {@link NodeImpl} via\n * {@link NodeBase}. The only things that diverge from static nodes:\n * - deps are discovered inside `_runFn` via a tracking `get` proxy\n * - `_rewire` installs subscriptions lazily during `_runFn`\n * - during rewire, new dep messages are **buffered** (option C from the\n * Apr-2026 refactor); after rewire we scan the buffer for DATA values\n * that differ from what fn tracked, and re-run fn if any found\n * (bounded by `MAX_RERUN`)\n */\n\nimport { normalizeActor } from \"./actor.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport { node as createNode } from \"./node.js\";\nimport {\n\tNO_VALUE,\n\ttype Node,\n\tNodeBase,\n\ttype NodeOptions,\n\ttype NodeTransportOptions,\n} from \"./node-base.js\";\n\n/**\n * The tracking `get` function passed to `dynamicNode`'s compute function.\n * Each call to `get(dep)` reads the dep's current value and records it as a dependency.\n */\nexport type DynGet = <V>(dep: Node<V>) => V | undefined;\n\n/**\n * Compute function for `dynamicNode`. Receives a tracking `get` proxy.\n * Deps are discovered by which nodes are passed to `get()` during execution.\n */\nexport type DynamicNodeFn<T> = (get: DynGet) => T;\n\n/** Options for `dynamicNode`. */\nexport type DynamicNodeOptions = Pick<\n\tNodeOptions,\n\t| \"name\"\n\t| \"equals\"\n\t| \"meta\"\n\t| \"resubscribable\"\n\t| \"resetOnTeardown\"\n\t| \"guard\"\n\t| \"onMessage\"\n\t| \"onResubscribe\"\n\t| \"completeWhenDepsComplete\"\n\t| \"describeKind\"\n>;\n\n/** Bounded rerun cap for dynamic fn activation loop (lazy-dep stabilization). */\nconst MAX_RERUN = 16;\n\n/**\n * Creates a node with runtime dep tracking. Deps are discovered each time the\n * compute function runs by tracking which nodes are passed to the `get()` proxy.\n *\n * After each recompute:\n * - New deps (not in previous set) are subscribed\n * - Removed deps (not in current set) are unsubscribed\n * - Kept deps retain their existing subscriptions\n *\n * The node participates in diamond resolution via the pre-set dirty mask\n * (shared with {@link NodeImpl}).\n *\n * **Lazy-dep composition:** when a tracked dep is itself a lazy compute node\n * whose first subscribe causes a fresh value to arrive, the rewire buffer\n * detects the discrepancy and re-runs fn once so it observes the real value.\n * Capped at {@link MAX_RERUN} iterations.\n *\n * @param fn - Compute function receiving a tracking `get` proxy.\n * @param opts - Optional configuration.\n * @returns `Node<T>` with dynamic dep tracking.\n *\n * @example\n * ```ts\n * import { dynamicNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const cond = state(true);\n * const a = state(1);\n * const b = state(2);\n *\n * const d = dynamicNode((get) => {\n * const useA = get(cond);\n * return useA ? get(a) : get(b);\n * });\n * ```\n *\n * @category core\n */\nexport function dynamicNode<T = unknown>(fn: DynamicNodeFn<T>, opts?: DynamicNodeOptions): Node<T> {\n\treturn new DynamicNodeImpl<T>(fn, opts ?? {});\n}\n\n/** Pending buffer entry during `_rewire`. */\ntype PendingEntry = { index: number; msgs: Messages };\n\n/** @internal — exported for {@link describeNode} `instanceof` check. */\nexport class DynamicNodeImpl<T = unknown> extends NodeBase<T> {\n\tprivate readonly _fn: DynamicNodeFn<T>;\n\tprivate readonly _autoComplete: boolean;\n\n\t// Dynamic deps tracking\n\t/** @internal Read by `describeNode`. */\n\t_deps: Node[] = [];\n\tprivate _depUnsubs: Array<() => void> = [];\n\tprivate _depIndexMap = new Map<Node, number>();\n\tprivate _depDirtyBits = new Set<number>();\n\tprivate _depSettledBits = new Set<number>();\n\tprivate _depCompleteBits = new Set<number>();\n\n\t// Execution state\n\tprivate _running = false;\n\tprivate _rewiring = false;\n\tprivate _bufferedDepMessages: PendingEntry[] = [];\n\tprivate _trackedValues: Map<Node, unknown> = new Map();\n\tprivate _rerunCount = 0;\n\n\tconstructor(fn: DynamicNodeFn<T>, opts: DynamicNodeOptions) {\n\t\tsuper(opts);\n\t\tthis._fn = fn;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\tprotected _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node {\n\t\treturn createNode({\n\t\t\tinitial: initialValue,\n\t\t\tname: `${opts.name ?? \"dynamicNode\"}:meta:${key}`,\n\t\t\tdescribeKind: \"state\",\n\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t});\n\t}\n\n\t/** Versioning not supported on DynamicNodeImpl (override base). */\n\toverride get v(): undefined {\n\t\treturn undefined;\n\t}\n\n\t// --- Up / unsubscribe ---\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, options);\n\t\t}\n\t}\n\n\tprotected _upInternal(messages: Messages): void {\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tthis._disconnect();\n\t}\n\n\t// --- Activation hooks ---\n\n\tprotected _onActivate(): void {\n\t\tthis._runFn();\n\t}\n\n\tprotected _doDeactivate(): void {\n\t\tthis._disconnect();\n\t}\n\n\tprivate _disconnect(): void {\n\t\tfor (const unsub of this._depUnsubs) unsub();\n\t\tthis._depUnsubs = [];\n\t\tthis._deps = [];\n\t\tthis._depIndexMap.clear();\n\t\tthis._depDirtyBits.clear();\n\t\tthis._depSettledBits.clear();\n\t\tthis._depCompleteBits.clear();\n\n\t\t// ROM/RAM rule (GRAPHREFLY-SPEC §2.2): compute node clears cache on\n\t\t// disconnect — dynamic nodes are always compute nodes.\n\t\tthis._cached = NO_VALUE;\n\t\tthis._status = \"disconnected\";\n\t}\n\n\t// --- Fn execution with rewire buffer ---\n\n\tprivate _runFn(): void {\n\t\tif (this._terminal && !this._resubscribable) return;\n\t\tif (this._running) return;\n\n\t\tthis._running = true;\n\t\tthis._rerunCount = 0;\n\t\tlet result: T | undefined;\n\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\t// --- Phase 1: execute fn with tracking `get`. ---\n\t\t\t\tconst trackedDeps: Node[] = [];\n\t\t\t\tconst trackedValuesMap = new Map<Node, unknown>();\n\t\t\t\tconst trackedSet = new Set<Node>();\n\n\t\t\t\tconst get: DynGet = <V>(dep: Node<V>): V | undefined => {\n\t\t\t\t\tif (!trackedSet.has(dep)) {\n\t\t\t\t\t\ttrackedSet.add(dep);\n\t\t\t\t\t\ttrackedDeps.push(dep);\n\t\t\t\t\t\t// Spec §2.2: `get()` never triggers computation. If the\n\t\t\t\t\t\t// dep is a disconnected lazy node, this returns\n\t\t\t\t\t\t// undefined — the rewire buffer will detect the\n\t\t\t\t\t\t// discrepancy once the lazy dep's real value arrives\n\t\t\t\t\t\t// via subscribe-time push.\n\t\t\t\t\t\ttrackedValuesMap.set(dep, dep.get());\n\t\t\t\t\t}\n\t\t\t\t\treturn dep.get() as V | undefined;\n\t\t\t\t};\n\n\t\t\t\tthis._trackedValues = trackedValuesMap;\n\n\t\t\t\t// Collect dep values for inspector hook\n\t\t\t\tconst depValues: unknown[] = [];\n\t\t\t\tfor (const dep of this._deps) depValues.push(dep.get());\n\t\t\t\tthis._emitInspectorHook({ kind: \"run\", depValues });\n\n\t\t\t\ttry {\n\t\t\t\t\tresult = this._fn(get);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 2: rewire. ---\n\t\t\t\tthis._rewiring = true;\n\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\ttry {\n\t\t\t\t\tthis._rewire(trackedDeps);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._rewiring = false;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 3: scan buffer for discrepancies that require re-run. ---\n\t\t\t\tlet needsRerun = false;\n\t\t\t\tfor (const entry of this._bufferedDepMessages) {\n\t\t\t\t\tfor (const msg of entry.msgs) {\n\t\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\t\tconst dep = this._deps[entry.index];\n\t\t\t\t\t\t\tconst trackedValue = dep != null ? this._trackedValues.get(dep) : undefined;\n\t\t\t\t\t\t\tconst actualValue = msg[1];\n\t\t\t\t\t\t\tif (!this._equals(trackedValue, actualValue)) {\n\t\t\t\t\t\t\t\tneedsRerun = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (needsRerun) break;\n\t\t\t\t}\n\n\t\t\t\tif (needsRerun) {\n\t\t\t\t\tthis._rerunCount += 1;\n\t\t\t\t\tif (this._rerunCount > MAX_RERUN) {\n\t\t\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\t\t\tthis._downInternal([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\tERROR,\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t`dynamicNode \"${this.name ?? \"anonymous\"}\": rewire did not stabilize within ${MAX_RERUN} iterations`,\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\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Discard this iteration's buffer and loop.\n\t\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 4: drain buffer — update masks only, no _runFn. ---\n\t\t\t\t//\n\t\t\t\t// Buffered activation-cascade messages are already reflected\n\t\t\t\t// in `_trackedValues` (fn saw the same values). We update\n\t\t\t\t// the wave masks so subsequent dep updates start from a\n\t\t\t\t// consistent state, then clear both masks so the node\n\t\t\t\t// enters post-rewire with clean wave tracking.\n\t\t\t\tconst drain = this._bufferedDepMessages;\n\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\tfor (const entry of drain) {\n\t\t\t\t\tfor (const msg of entry.msgs) {\n\t\t\t\t\t\tthis._updateMasksForMessage(entry.index, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Clear wave masks — the activation cascade is fully\n\t\t\t\t// consumed; subsequent dep updates should start fresh.\n\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._running = false;\n\t\t}\n\n\t\tthis._downAutoValue(result);\n\t}\n\n\tprivate _rewire(newDeps: Node[]): void {\n\t\tconst oldMap = this._depIndexMap;\n\t\tconst newMap = new Map<Node, number>();\n\t\tconst newUnsubs: Array<() => void> = [];\n\n\t\t// Subscribe to new deps (or reuse existing subscriptions).\n\t\tfor (let i = 0; i < newDeps.length; i++) {\n\t\t\tconst dep = newDeps[i];\n\t\t\tnewMap.set(dep, i);\n\t\t\tconst oldIdx = oldMap.get(dep);\n\t\t\tif (oldIdx !== undefined) {\n\t\t\t\t// Kept dep — reuse subscription.\n\t\t\t\tnewUnsubs.push(this._depUnsubs[oldIdx]);\n\t\t\t\tthis._depUnsubs[oldIdx] = () => {};\n\t\t\t} else {\n\t\t\t\t// New dep — subscribe. Its subscribe-time handshake +\n\t\t\t\t// activation cascade will land in `_handleDepMessages`,\n\t\t\t\t// which routes to the buffer while `_rewiring` is true.\n\t\t\t\tconst idx = i;\n\t\t\t\tconst unsub = dep.subscribe((msgs) => this._handleDepMessages(idx, msgs));\n\t\t\t\tnewUnsubs.push(unsub);\n\t\t\t}\n\t\t}\n\n\t\t// Disconnect removed deps.\n\t\tfor (const [dep, oldIdx] of oldMap) {\n\t\t\tif (!newMap.has(dep)) {\n\t\t\t\tthis._depUnsubs[oldIdx]();\n\t\t\t}\n\t\t}\n\n\t\tthis._deps = newDeps;\n\t\tthis._depUnsubs = newUnsubs;\n\t\tthis._depIndexMap = newMap;\n\t\tthis._depDirtyBits.clear();\n\t\tthis._depSettledBits.clear();\n\n\t\t// Preserve complete bits for deps that are still present (re-indexed).\n\t\tconst newCompleteBits = new Set<number>();\n\t\tfor (const oldIdx of this._depCompleteBits) {\n\t\t\tfor (const [dep, idx] of oldMap) {\n\t\t\t\tif (idx === oldIdx && newMap.has(dep)) {\n\t\t\t\t\tnewCompleteBits.add(newMap.get(dep)!);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis._depCompleteBits = newCompleteBits;\n\t}\n\n\t// --- Dep message handling ---\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\t// During rewire, buffer messages for post-rewire scan.\n\t\tif (this._rewiring) {\n\t\t\tthis._bufferedDepMessages.push({ index, msgs: messages });\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const msg of messages) {\n\t\t\tthis._emitInspectorHook({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\n\t\t\t// Note: unlike NodeImpl, we do NOT clear dirty bits when onMessage\n\t\t\t// consumes START. NodeImpl pre-sets all dirty bits in _connectUpstream\n\t\t\t// and must clear them for consumed-START deps (notifier pattern).\n\t\t\t// DynamicNodeImpl never pre-sets dirty bits — deps are discovered\n\t\t\t// lazily during _runFn — so there are no bits to clear.\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Tier-0 (START) from a dep is informational — see NodeImpl for rationale.\n\t\t\tif (messageTier(t) < 1) continue;\n\n\t\t\tif (t === DIRTY) {\n\t\t\t\tconst wasEmpty = this._depDirtyBits.size === 0;\n\t\t\t\tthis._depDirtyBits.add(index);\n\t\t\t\tthis._depSettledBits.delete(index);\n\t\t\t\tif (wasEmpty) {\n\t\t\t\t\tthis._downInternal([[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tif (!this._depDirtyBits.has(index)) {\n\t\t\t\t\t// DATA-without-prior-DIRTY — propagate DIRTY for the two-phase\n\t\t\t\t\t// invariant (§1.3.1 compat path).\n\t\t\t\t\tconst wasEmpty = this._depDirtyBits.size === 0;\n\t\t\t\t\tthis._depDirtyBits.add(index);\n\t\t\t\t\tif (wasEmpty) {\n\t\t\t\t\t\tthis._downInternal([[DIRTY]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._depSettledBits.add(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\t\tif (!this._running) {\n\t\t\t\t\t\t// Identity check against the values fn already saw — if\n\t\t\t\t\t\t// nothing has actually changed, skip the run. This\n\t\t\t\t\t\t// guards against deferred handshake DATA (arriving\n\t\t\t\t\t\t// after `_rewire` finishes inside an open batch)\n\t\t\t\t\t\t// from triggering a redundant re-run.\n\t\t\t\t\t\tif (this._depValuesDifferFromTracked()) {\n\t\t\t\t\t\t\tthis._runFn();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteBits.add(index);\n\t\t\t\tthis._depDirtyBits.delete(index);\n\t\t\t\tthis._depSettledBits.delete(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\t\tif (!this._running) this._runFn();\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tthis._autoComplete &&\n\t\t\t\t\tthis._depCompleteBits.size >= this._deps.length &&\n\t\t\t\t\tthis._deps.length > 0\n\t\t\t\t) {\n\t\t\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\t/**\n\t * Update dep masks for a message without triggering `_runFn` — used\n\t * during post-rewire drain so the wave state is consistent with the\n\t * buffered activation cascade without recursing.\n\t */\n\tprivate _updateMasksForMessage(index: number, msg: Messages[number]): void {\n\t\tconst t = msg[0];\n\t\tif (t === DIRTY) {\n\t\t\tthis._depDirtyBits.add(index);\n\t\t\tthis._depSettledBits.delete(index);\n\t\t} else if (t === DATA || t === RESOLVED) {\n\t\t\tthis._depDirtyBits.add(index);\n\t\t\tthis._depSettledBits.add(index);\n\t\t} else if (t === COMPLETE) {\n\t\t\tthis._depCompleteBits.add(index);\n\t\t\tthis._depDirtyBits.delete(index);\n\t\t\tthis._depSettledBits.delete(index);\n\t\t}\n\t}\n\n\tprivate _allDirtySettled(): boolean {\n\t\tif (this._depDirtyBits.size === 0) return false;\n\t\tfor (const idx of this._depDirtyBits) {\n\t\t\tif (!this._depSettledBits.has(idx)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * True if any current dep value differs from what the last `_runFn`\n\t * saw via `get()`. Used to suppress redundant re-runs when deferred\n\t * handshake messages arrive after `_rewire` for a dep whose value\n\t * already matches `_trackedValues`.\n\t */\n\tprivate _depValuesDifferFromTracked(): boolean {\n\t\tfor (const dep of this._deps) {\n\t\t\tconst current = dep.get();\n\t\t\tconst tracked = this._trackedValues.get(dep);\n\t\t\tif (!this._equals(current, tracked)) return true;\n\t\t}\n\t\treturn false;\n\t}\n}\n","import type { Actor } from \"./actor.js\";\nimport { DynamicNodeImpl } from \"./dynamic-node.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { NO_VALUE, type Node, NodeImpl } from \"./node.js\";\n\n/** JSON-shaped slice of a node for Phase 1 `Graph.describe()` (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type DescribeNodeOutput = {\n\ttype: \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\tstatus?: Node[\"status\"];\n\tdeps: string[];\n\tmeta?: Record<string, unknown>;\n\tname?: string;\n\tvalue?: unknown;\n\t/** True when the node has never received or been initialized with a value (cache holds SENTINEL). */\n\tsentinel?: boolean;\n\t/** Node versioning info (GRAPHREFLY-SPEC §7). Present only when versioning is enabled. */\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\n\t/** Guard info (full detail). */\n\tguard?: string;\n\t/** Last mutation attribution (full detail). */\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n};\n\n/**\n * Detail level for `describe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — type + deps only (default). LLM-friendly.\n * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`).\n * - `\"full\"` — standard + guard, lastMutation.\n */\nexport type DescribeDetail = \"minimal\" | \"standard\" | \"full\";\n\n/**\n * Valid field names for `describe({ fields: [...] })` (Phase 3.3b).\n * Dotted paths like `\"meta.label\"` select specific meta keys.\n */\nexport type DescribeField =\n\t| \"type\"\n\t| \"status\"\n\t| \"value\"\n\t| \"deps\"\n\t| \"meta\"\n\t| \"v\"\n\t| \"guard\"\n\t| \"lastMutation\"\n\t| `meta.${string}`;\n\n/** Resolve which fields to include based on detail level or explicit field list. */\nexport function resolveDescribeFields(\n\tdetail?: DescribeDetail,\n\tfields?: readonly DescribeField[],\n): Set<string> | null {\n\t// Explicit fields override detail level\n\tif (fields != null && fields.length > 0) return new Set(fields);\n\tswitch (detail) {\n\t\tcase \"standard\":\n\t\t\treturn new Set([\"type\", \"status\", \"value\", \"deps\", \"meta\", \"v\"]);\n\t\tcase \"full\":\n\t\t\treturn null; // null = include everything\n\t\tdefault:\n\t\t\treturn new Set([\"type\", \"deps\"]);\n\t}\n}\n\nfunction inferDescribeType(n: NodeImpl): DescribeNodeOutput[\"type\"] {\n\tif (n._describeKind != null) return n._describeKind;\n\tif (!n._hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\tif (n._fn == null) return \"derived\";\n\tif (n._manualEmitUsed) return \"operator\";\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON (GRAPHREFLY-SPEC §2.3, §3.6).\n *\n * @remarks\n * Values come from {@link Node.get}, which returns the **last settled** cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status` when\n * freshness matters. Avoid calling mid-batch for the same reason.\n *\n * Meta nodes are **not** terminated when their parent receives COMPLETE or\n * ERROR — they remain writable so callers can record post-mortem metadata\n * (e.g. `meta.error`). They *are* torn down when the parent receives TEARDOWN.\n *\n * @param node - The node whose meta fields to snapshot.\n * @returns Plain object of `{ key: value }` pairs (empty if no meta defined).\n * Keys whose companion node's {@link Node.get} throws are omitted.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = core.node({ initial: 0, meta: { tag: \"a\" } });\n * core.metaSnapshot(n); // { tag: \"a\" }\n * ```\n */\n/** @internal Used by {@link describeNode} — not part of the public API. */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.get();\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta` snapshot).\n * Parity with graphrefly-py `describe_node`.\n *\n * `type` is inferred from factory configuration, optional `describeKind` in node options,\n * and the last `manualEmitUsed` hint (operator vs derived). {@link effect} sets\n * `describeKind: \"effect\"`. Nodes not created by {@link node} fall back to `type: \"state\"` and empty `deps`.\n *\n * @param node - Any `Node` to introspect.\n * @returns `DescribeNodeOutput` suitable for merging into graph describe maps.\n *\n * @example\n * ```ts\n * import { describeNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * describeNode(state(0));\n * ```\n */\n/**\n * Builds a single-node slice for `Graph.describe()`.\n *\n * @param node - Node to introspect.\n * @param includeFields - Set of fields to include, or `null` for all. When omitted, all fields are included (legacy behavior).\n */\n/** @internal Used by {@link Graph.describe} — not part of the public API. */\nexport function describeNode(node: Node, includeFields?: Set<string> | null): DescribeNodeOutput {\n\tconst all = includeFields == null; // null or undefined → include everything\n\n\t// Specific meta keys requested via dotted paths (e.g. \"meta.label\")\n\tconst metaKeys: string[] | null =\n\t\t!all && includeFields != null\n\t\t\t? [...includeFields].filter((f) => f.startsWith(\"meta.\")).map((f) => f.slice(5))\n\t\t\t: null;\n\tconst wantsMeta = all || includeFields!.has(\"meta\") || (metaKeys != null && metaKeys.length > 0);\n\n\tlet type: DescribeNodeOutput[\"type\"] = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.name ?? \"\");\n\t} else if (node instanceof DynamicNodeImpl) {\n\t\ttype = node._describeKind ?? \"derived\";\n\t\tdeps = [];\n\t}\n\n\tconst out: DescribeNodeOutput = { type, deps };\n\n\t// status\n\tif (all || includeFields!.has(\"status\")) {\n\t\tout.status = node.status;\n\t}\n\n\t// Resolve guard once — used by both meta.access hint and standalone guard field\n\tconst guard =\n\t\t(node instanceof NodeImpl && node._guard) ||\n\t\t(node instanceof DynamicNodeImpl && node._guard) ||\n\t\tundefined;\n\n\t// meta\n\tif (wantsMeta) {\n\t\tconst rawMeta: Record<string, unknown> = { ...metaSnapshot(node) };\n\t\tif (guard != null && rawMeta.access === undefined) {\n\t\t\trawMeta.access = accessHintForGuard(guard);\n\t\t}\n\n\t\tif (metaKeys != null && metaKeys.length > 0 && !includeFields!.has(\"meta\")) {\n\t\t\t// Only specific meta keys\n\t\t\tconst filtered: Record<string, unknown> = {};\n\t\t\tfor (const k of metaKeys) {\n\t\t\t\tif (k in rawMeta) filtered[k] = rawMeta[k];\n\t\t\t}\n\t\t\tout.meta = filtered;\n\t\t} else {\n\t\t\tout.meta = rawMeta;\n\t\t}\n\t}\n\n\t// name (always include when present — it's identity, not detail)\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\t// value + sentinel indicator\n\tif (all || includeFields!.has(\"value\")) {\n\t\tconst isSentinel =\n\t\t\t(node instanceof NodeImpl && node._cached === NO_VALUE) ||\n\t\t\t(node instanceof DynamicNodeImpl && node._cached === NO_VALUE);\n\t\tif (isSentinel) {\n\t\t\tout.sentinel = true;\n\t\t}\n\t\ttry {\n\t\t\tout.value = node.get();\n\t\t} catch {\n\t\t\t/* omit value */\n\t\t}\n\t}\n\n\t// Versioning (GRAPHREFLY-SPEC §7)\n\tif ((all || includeFields!.has(\"v\")) && node.v != null) {\n\t\tconst vInfo: DescribeNodeOutput[\"v\"] = { id: node.v.id, version: node.v.version };\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo!.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo!.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\t// Guard info (full detail)\n\tif (all || includeFields!.has(\"guard\")) {\n\t\tif (guard != null) {\n\t\t\tout.guard = accessHintForGuard(guard);\n\t\t}\n\t}\n\n\t// Last mutation attribution (full detail)\n\tif (all || includeFields!.has(\"lastMutation\")) {\n\t\tif (node.lastMutation != null) {\n\t\t\tout.lastMutation = node.lastMutation;\n\t\t}\n\t}\n\n\treturn out;\n}\n","import { type Node, type NodeFn, type NodeOptions, node } from \"./node.js\";\n\n/**\n * Creates a manual source with no upstream deps. Emit values with {@link Node.down}.\n *\n * Spec: `state(initial, opts?)` is `node([], { initial, ...opts })` (GRAPHREFLY-SPEC §2.7).\n *\n * @param initial - Initial cached value. Because `initial` is provided, `equals` is\n * called on the first {@link Node.down | down()} emission — if the value matches\n * `initial`, the node emits `RESOLVED` instead of `DATA` (spec §2.5).\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n * @returns `Node<T>` - Stateful node you drive imperatively.\n *\n * @example\n * ```ts\n * import { DATA, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(0);\n * n.down([[DATA, 1]]);\n * ```\n *\n * @category core\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n/**\n * Creates a producer node with no deps; `fn` runs when the first subscriber connects.\n *\n * @param fn - Receives deps (empty) and {@link NodeActions}; use `emit` / `down` to push.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Producer node.\n *\n * @example\n * ```ts\n * import { producer } from \"@graphrefly/graphrefly-ts\";\n *\n * const tick = producer((_d, a) => {\n * a.emit(1);\n * });\n * ```\n *\n * @category core\n */\nexport function producer<T = unknown>(fn: NodeFn<T>, opts?: NodeOptions): Node<T> {\n\treturn node<T>(fn, { describeKind: \"producer\", ...opts });\n}\n\n/**\n * Creates a derived node from dependencies and a compute function (same primitive as operators).\n *\n * @param deps - Upstream nodes.\n * @param fn - Compute function; return value is emitted, or use `actions` explicitly.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Derived node.\n *\n * @example\n * ```ts\n * import { derived, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n *\n * @category core\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: NodeFn<T>,\n\topts?: NodeOptions,\n): Node<T> {\n\treturn node<T>(deps, fn, { describeKind: \"derived\", ...opts });\n}\n\n/**\n * Runs a side-effect when deps settle; return value is not auto-emitted.\n *\n * @param deps - Nodes to watch.\n * @param fn - Side-effect body.\n * @returns `Node<unknown>` - Effect node.\n *\n * @example\n * ```ts\n * import { effect, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(1);\n * effect([n], ([v]) => {\n * console.log(v);\n * });\n * ```\n *\n * @category core\n */\nexport function effect(\n\tdeps: readonly Node[],\n\tfn: NodeFn<unknown>,\n\topts?: NodeOptions,\n): Node<unknown> {\n\treturn node(deps, fn, { describeKind: \"effect\", ...opts });\n}\n\n/** Unary transform used by {@link pipe} (typically returns a new node wrapping `n`). */\nexport type PipeOperator = (n: Node) => Node;\n\n/**\n * Composes unary operators left-to-right; returns the final node. Does not register a {@link Graph}.\n *\n * @param source - Starting node.\n * @param ops - Each operator maps `Node` to `Node` (curried operators from `extra` use a factory pattern — wrap or use direct calls).\n * @returns `Node` - Result of the last operator.\n *\n * @example\n * ```ts\n * import { filter, map, pipe, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state(1);\n * const out = pipe(\n * src,\n * (n) => map(n, (x) => x + 1),\n * (n) => filter(n, (x) => x > 0),\n * );\n * ```\n *\n * @category core\n */\nexport function pipe(source: Node, ...ops: PipeOperator[]): Node {\n\tlet current = source;\n\tfor (const op of ops) {\n\t\tcurrent = op(current);\n\t}\n\treturn current;\n}\n","/**\n * Approximate in-memory size estimation for arbitrary JS values.\n *\n * Uses a recursive walk with cycle detection. Not exact — provides a\n * reasonable approximation for profiling and hotspot detection.\n *\n * @module\n * @internal\n */\n\n/** Approximate per-type overhead in bytes (V8 heuristics). */\nconst OVERHEAD = {\n\tobject: 56,\n\tarray: 64,\n\tstring: 40, // header; content added separately\n\tnumber: 8,\n\tboolean: 4,\n\tnull: 0,\n\tundefined: 0,\n\tsymbol: 40,\n\tbigint: 16,\n\tfunction: 120,\n\tmap: 72,\n\tset: 72,\n\tmapEntry: 40,\n\tsetEntry: 24,\n} as const;\n\n/**\n * Estimate the approximate retained memory (in bytes) of a JS value.\n *\n * Handles primitives, plain objects, arrays, Maps, Sets, and nested\n * combinations. Uses a `WeakSet` for cycle detection — cyclic refs\n * are counted once.\n *\n * @param value - The value to measure.\n * @returns Approximate size in bytes.\n */\nexport function sizeof(value: unknown): number {\n\tconst seen = new WeakSet();\n\treturn _sizeof(value, seen);\n}\n\nfunction _sizeof(value: unknown, seen: WeakSet<WeakKey>): number {\n\tif (value == null) return 0;\n\n\tconst t = typeof value;\n\n\tswitch (t) {\n\t\tcase \"number\":\n\t\t\treturn OVERHEAD.number;\n\t\tcase \"boolean\":\n\t\t\treturn OVERHEAD.boolean;\n\t\tcase \"string\":\n\t\t\treturn OVERHEAD.string + (value as string).length * 2; // UTF-16\n\t\tcase \"bigint\":\n\t\t\treturn OVERHEAD.bigint;\n\t\tcase \"symbol\":\n\t\t\treturn OVERHEAD.symbol;\n\t\tcase \"function\":\n\t\t\tif (seen.has(value as object)) return 0;\n\t\t\tseen.add(value as object);\n\t\t\treturn OVERHEAD.function;\n\t\tcase \"undefined\":\n\t\t\treturn 0;\n\t}\n\n\t// Object types — cycle detection\n\tconst obj = value as object;\n\tif (seen.has(obj)) return 0;\n\tseen.add(obj);\n\n\tif (obj instanceof Map) {\n\t\tlet size = OVERHEAD.map;\n\t\tfor (const [k, v] of obj) {\n\t\t\tsize += OVERHEAD.mapEntry + _sizeof(k, seen) + _sizeof(v, seen);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (obj instanceof Set) {\n\t\tlet size = OVERHEAD.set;\n\t\tfor (const v of obj) {\n\t\t\tsize += OVERHEAD.setEntry + _sizeof(v, seen);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\tlet size = OVERHEAD.array + obj.length * 8; // pointer slots\n\t\tfor (const item of obj) {\n\t\t\tsize += _sizeof(item, seen);\n\t\t}\n\t\treturn size;\n\t}\n\n\t// ArrayBuffer / TypedArray\n\tif (obj instanceof ArrayBuffer) return obj.byteLength;\n\tif (ArrayBuffer.isView(obj)) return (obj as { byteLength: number }).byteLength;\n\n\t// Plain object\n\tlet size = OVERHEAD.object;\n\tconst keys = Object.keys(obj);\n\tfor (const key of keys) {\n\t\tsize += OVERHEAD.string + key.length * 2; // key\n\t\tsize += _sizeof((obj as Record<string, unknown>)[key], seen);\n\t}\n\treturn size;\n}\n","/**\n * Graph profiling and inspection utilities.\n *\n * Provides per-node memory estimation, connectivity stats, and hotspot\n * detection. Non-invasive — reads from `describe()` and node internals\n * without modifying state.\n *\n * @module\n */\n\nimport { NodeImpl } from \"../core/node.js\";\nimport type { Graph, GraphDescribeOutput } from \"./graph.js\";\nimport { sizeof } from \"./sizeof.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Per-node profile entry. */\nexport interface NodeProfile {\n\t/** Qualified path within the graph. */\n\tpath: string;\n\t/** Node type (state, derived, producer, effect). */\n\ttype: string;\n\t/** Node status (disconnected, dirty, settled, errored, completed). */\n\tstatus: string;\n\t/** Approximate retained bytes for the node's cached value. */\n\tvalueSizeBytes: number;\n\t/** Number of downstream subscribers (sinks). */\n\tsubscriberCount: number;\n\t/** Number of upstream dependencies. */\n\tdepCount: number;\n\t/** True if this is an effect node with no external subscribers (potential leak). */\n\tisOrphanEffect: boolean;\n}\n\n/** Aggregate graph profile. */\nexport interface GraphProfileResult {\n\t/** Total node count. */\n\tnodeCount: number;\n\t/** Total edge count. */\n\tedgeCount: number;\n\t/** Subgraph count. */\n\tsubgraphCount: number;\n\t/** All node profiles. */\n\tnodes: NodeProfile[];\n\t/** Total approximate value memory across all nodes. */\n\ttotalValueSizeBytes: number;\n\t/** Nodes sorted by valueSizeBytes descending (top N). */\n\thotspots: NodeProfile[];\n\t/** Effect nodes with no external subscribers (potential leaks). */\n\torphanEffects: NodeProfile[];\n}\n\n/** Options for {@link graphProfile}. */\nexport interface GraphProfileOptions {\n\t/** Limit hotspot list (default 10). */\n\ttopN?: number;\n\t/** Include subgraph nodes recursively (default true). */\n\trecursive?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Profile a graph's memory and connectivity characteristics.\n *\n * Uses `describe({ detail: \"standard\" })` for node metadata and direct\n * `NodeImpl` access for subscriber counts and cached values.\n *\n * @param graph - The graph to profile.\n * @param opts - Optional configuration.\n * @returns Aggregate profile with per-node details and hotspots.\n */\nexport function graphProfile(graph: Graph, opts?: GraphProfileOptions): GraphProfileResult {\n\tconst topN = opts?.topN ?? 10;\n\n\tconst desc: GraphDescribeOutput = graph.describe({ detail: \"standard\" });\n\n\t// Build path→Node lookup via _collectObserveTargets (same as describe uses).\n\t// Runtime guard: if the internal method is missing (refactored), degrade\n\t// gracefully — profiles will show 0 for valueSizeBytes and subscriberCount.\n\tconst targets: [string, import(\"../core/node.js\").Node][] = [];\n\tif (typeof (graph as any)._collectObserveTargets === \"function\") {\n\t\t(graph as any)._collectObserveTargets(\"\", targets);\n\t}\n\tconst pathToNode = new Map<string, import(\"../core/node.js\").Node>();\n\tfor (const [p, n] of targets) {\n\t\tpathToNode.set(p, n);\n\t}\n\n\tconst profiles: NodeProfile[] = [];\n\n\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\tconst nd = pathToNode.get(path);\n\t\tconst impl = nd instanceof NodeImpl ? nd : null;\n\n\t\tconst valueSizeBytes = impl ? sizeof(impl.get()) : 0;\n\t\tconst subscriberCount = impl ? impl._sinkCount : 0;\n\t\tconst depCount = nodeDesc.deps?.length ?? 0;\n\n\t\tconst isOrphanEffect = nodeDesc.type === \"effect\" && subscriberCount === 0;\n\n\t\tprofiles.push({\n\t\t\tpath,\n\t\t\ttype: nodeDesc.type,\n\t\t\tstatus: nodeDesc.status ?? \"unknown\",\n\t\t\tvalueSizeBytes,\n\t\t\tsubscriberCount,\n\t\t\tdepCount,\n\t\t\tisOrphanEffect,\n\t\t});\n\t}\n\n\tconst totalValueSizeBytes = profiles.reduce((sum, p) => sum + p.valueSizeBytes, 0);\n\n\tconst hotspots = [...profiles].sort((a, b) => b.valueSizeBytes - a.valueSizeBytes).slice(0, topN);\n\n\tconst orphanEffects = profiles.filter((p) => p.isOrphanEffect);\n\n\treturn {\n\t\tnodeCount: profiles.length,\n\t\tedgeCount: desc.edges.length,\n\t\tsubgraphCount: desc.subgraphs.length,\n\t\tnodes: profiles,\n\t\ttotalValueSizeBytes,\n\t\thotspots,\n\t\torphanEffects,\n\t};\n}\n","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 {\n\ttype DescribeDetail,\n\ttype DescribeField,\n\ttype DescribeNodeOutput,\n\tdescribeNode,\n\tresolveDescribeFields,\n} 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\";\nimport { type GraphProfileOptions, type GraphProfileResult, graphProfile } from \"./profile.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/** Options for {@link Graph.describe} (Phase 3.3b progressive disclosure). */\nexport type GraphDescribeOptions = {\n\tactor?: Actor;\n\t/**\n\t * Node filter. Filters operate on whatever fields the chosen `detail` level\n\t * provides. For `metaHas` and `status` filters, use `detail: \"standard\"` or\n\t * higher — at `\"minimal\"` those fields are absent and the filter silently\n\t * excludes all nodes.\n\t */\n\tfilter?: DescribeFilter;\n\t/**\n\t * Detail level (Phase 3.3b). Default: `\"minimal\"`.\n\t * - `\"minimal\"` — type + deps only\n\t * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`)\n\t * - `\"full\"` — standard + guard, lastMutation\n\t */\n\tdetail?: DescribeDetail;\n\t/**\n\t * Explicit field selection (GraphQL-style). Overrides `detail` when provided.\n\t * Dotted paths like `\"meta.label\"` select specific meta keys.\n\t */\n\tfields?: DescribeField[];\n\t/**\n\t * Output format (Phase 3.3b).\n\t * - `undefined` — normal describe output\n\t * - `\"spec\"` — GraphSpec input format (no status, no value, deps as edges, type labels)\n\t */\n\tformat?: \"spec\";\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\t/**\n\t * Re-read the live graph with higher detail (Phase 3.3b).\n\t * Returns a new `GraphDescribeOutput`; the original remains a snapshot.\n\t * Present on live describe results; absent on deserialized snapshots.\n\t */\n\texpand?: (detailOrFields: DescribeDetail | DescribeField[]) => GraphDescribeOutput;\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.toObject},\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\n/** @deprecated Use `CheckpointAdapter` from `extra/checkpoint` instead. */\nexport type AutoCheckpointAdapter = {\n\tsave(key: string, 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 OBSERVE_ANSI_THEME: Required<ObserveTheme> = {\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 OBSERVE_NO_COLOR_THEME: Required<ObserveTheme> = {\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 resolveObserveTheme(theme: ObserveOptions[\"theme\"]): Required<ObserveTheme> {\n\tif (theme === \"none\") return OBSERVE_NO_COLOR_THEME;\n\tif (theme === \"ansi\" || theme == null) return OBSERVE_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/** Resolve observe `detail` level into effective boolean flags. */\nfunction resolveObserveDetail(opts?: ObserveOptions): ObserveOptions {\n\tif (opts == null) return {};\n\tconst detail = opts.detail;\n\tif (detail === \"full\") {\n\t\treturn {\n\t\t\t...opts,\n\t\t\tstructured: opts.structured ?? true,\n\t\t\ttimeline: opts.timeline ?? true,\n\t\t\tcausal: opts.causal ?? true,\n\t\t\tderived: opts.derived ?? true,\n\t\t};\n\t}\n\tif (detail === \"minimal\") {\n\t\treturn { ...opts, structured: opts.structured ?? true };\n\t}\n\treturn opts;\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/**\n * Detail level for `observe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — DATA events only, no timestamps, no causal info.\n * - `\"standard\"` — all message types (DATA, DIRTY, RESOLVED, COMPLETE, ERROR).\n * - `\"full\"` — standard + timeline + causal + derived.\n */\nexport type ObserveDetail = \"minimal\" | \"standard\" | \"full\";\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\t/**\n\t * Detail level (Phase 3.3b). Individual flags (`causal`, `timeline`, `derived`)\n\t * override. `\"full\"` implies all three plus structured.\n\t * `\"minimal\"` filters to DATA-only events.\n\t */\n\tdetail?: ObserveDetail;\n\n\t// ——— Format / logging (merged from spy) ———\n\n\t/**\n\t * When set, auto-enables structured mode and attaches a logger.\n\t * `\"pretty\"` renders colored one-line output; `\"json\"` emits one JSON object per event.\n\t */\n\tformat?: \"pretty\" | \"json\";\n\t/** Sink for rendered lines (`console.log` by default). Only used when `format` is set. */\n\tlogger?: (line: string, event: ObserveEvent) => void;\n\t/** Keep only these event types in formatted output. Only used when `format` is set. */\n\tincludeTypes?: ObserveEvent[\"type\"][];\n\t/** Exclude these event types from formatted output. Only used when `format` is set. */\n\texcludeTypes?: ObserveEvent[\"type\"][];\n\t/** Built-in color preset (`ansi` default) or explicit color tokens. Only used when `format` is set. */\n\ttheme?: ObserveThemeName | ObserveTheme;\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 any observed node sent COMPLETE without prior ERROR on that node. */\n\treadonly anyCompletedCleanly: boolean;\n\t/** True if any observed node sent ERROR. */\n\treadonly anyErrored: boolean;\n\t/** True if at least one COMPLETE received and no ERROR from any observed node. */\n\treadonly completedWithoutErrors: boolean;\n\t/** Stop observing. */\n\tdispose(): void;\n\t/**\n\t * Resubscribe with higher detail (Phase 3.3b).\n\t * Disposes current observation, returns new `ObserveResult` with merged options.\n\t */\n\texpand(\n\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t): ObserveResult<T>;\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\t/** Monotonically increasing counter per subscribe-callback invocation. All events in one delivery share the same id. */\n\tbatch_id?: number;\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 preset names for observe `format` rendering. */\nexport type ObserveThemeName = \"none\" | \"ansi\";\n\n/** ANSI/style overrides for observe `format` event rendering. */\nexport type ObserveTheme = Partial<Record<ObserveEvent[\"type\"] | \"path\" | \"reset\", string>>;\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 readonly _disposers = 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\t// Auto-register edges from constructor deps (eliminates dual-bookkeeping).\n\t\t\t// Forward: this node's deps → already-registered nodes.\n\t\t\tif (node._deps.length > 0) {\n\t\t\t\tfor (const dep of node._deps) {\n\t\t\t\t\tfor (const [depName, depNode] of this._nodes) {\n\t\t\t\t\t\tif (depNode === dep) {\n\t\t\t\t\t\t\tthis._edges.add(edgeKey(depName, name));\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}\n\t\t\t}\n\t\t\t// Reverse: already-registered nodes that depend on this newly added node.\n\t\t\tfor (const [otherName, otherNode] of this._nodes) {\n\t\t\t\tif (otherName === name) continue;\n\t\t\t\tif (otherNode instanceof NodeImpl && otherNode._deps.includes(node)) {\n\t\t\t\t\tthis._edges.add(edgeKey(name, otherName));\n\t\t\t\t}\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?: GraphDescribeOptions): GraphDescribeOutput {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst includeFields = resolveDescribeFields(options?.detail, options?.fields);\n\t\tconst isSpec = options?.format === \"spec\";\n\t\t// For spec format, force minimal fields (type + deps only, no status/value)\n\t\tconst effectiveFields = isSpec ? resolveDescribeFields(\"minimal\") : includeFields;\n\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, effectiveFields);\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\n\t\t// Capture graph ref and base options for expand()\n\t\tconst graph = this;\n\t\tconst baseOpts = options;\n\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t\texpand(detailOrFields: DescribeDetail | DescribeField[]): GraphDescribeOutput {\n\t\t\t\tconst merged: GraphDescribeOptions = { ...baseOpts, format: undefined };\n\t\t\t\tif (Array.isArray(detailOrFields)) {\n\t\t\t\t\tmerged.fields = detailOrFields;\n\t\t\t\t\tmerged.detail = undefined;\n\t\t\t\t} else {\n\t\t\t\t\tmerged.detail = detailOrFields;\n\t\t\t\t\tmerged.fields = undefined;\n\t\t\t\t}\n\t\t\t\treturn graph.describe(merged);\n\t\t\t},\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\t/**\n\t * Snapshot-based resource profile: per-node stats, orphan effect detection,\n\t * memory hotspots. Zero runtime overhead — walks nodes on demand.\n\t *\n\t * @param opts - Optional `topN` for hotspot limit (default 10).\n\t * @returns Aggregate profile with per-node details, hotspots, and orphan effects.\n\t */\n\tresourceProfile(opts?: GraphProfileOptions): GraphProfileResult {\n\t\treturn graphProfile(this, opts);\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 & { format: \"pretty\" | \"json\" }): 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 & { format: \"pretty\" | \"json\" }): 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 resolved = resolveObserveDetail(options);\n\t\t\tconst actor = resolved.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\tresolved.structured === true ||\n\t\t\t\tresolved.timeline === true ||\n\t\t\t\tresolved.causal === true ||\n\t\t\t\tresolved.derived === true ||\n\t\t\t\tresolved.detail === \"minimal\" ||\n\t\t\t\tresolved.detail === \"full\" ||\n\t\t\t\tresolved.format != null;\n\t\t\tif (wantsStructured) {\n\t\t\t\tconst result = Graph.inspectorEnabled\n\t\t\t\t\t? this._createObserveResult(path, target, resolved)\n\t\t\t\t\t: this._createFallbackObserveResult(path, resolved);\n\t\t\t\tif (resolved.format != null) {\n\t\t\t\t\tthis._attachFormatLogger(result, resolved);\n\t\t\t\t}\n\t\t\t\treturn result;\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 = resolveObserveDetail(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\t\topts.detail === \"minimal\" ||\n\t\t\topts.detail === \"full\" ||\n\t\t\topts.format != null;\n\t\tif (wantsStructured) {\n\t\t\tconst result = Graph.inspectorEnabled\n\t\t\t\t? this._createObserveResultForAll(opts)\n\t\t\t\t: this._createFallbackObserveResultForAll(opts);\n\t\t\tif (opts.format != null) {\n\t\t\t\tthis._attachFormatLogger(result, opts);\n\t\t\t}\n\t\t\treturn result;\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 minimal = options.detail === \"minimal\";\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\tanyCompletedCleanly: boolean;\n\t\t\tanyErrored: 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\tanyCompletedCleanly: false,\n\t\t\tanyErrored: 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\tlet batchSeq = 0;\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\n\t\t\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t\t\t: {}),\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\tbatchSeq++;\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst t = m[0];\n\t\t\t\tconst base = timeline\n\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t: {};\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 (minimal) {\n\t\t\t\t\t// minimal: track state but don't push non-DATA events\n\t\t\t\t\tif (t === DIRTY) result.dirtyCount++;\n\t\t\t\t\telse if (t === RESOLVED) result.resolvedCount++;\n\t\t\t\t\telse if (t === COMPLETE && !result.anyErrored) result.anyCompletedCleanly = true;\n\t\t\t\t\telse if (t === ERROR) result.anyErrored = true;\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.anyErrored) result.anyCompletedCleanly = 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.anyErrored = 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\tconst graph = this;\n\t\tconst basePath = path;\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 anyCompletedCleanly() {\n\t\t\t\treturn result.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn result.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn result.anyCompletedCleanly && !result.anyErrored;\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\texpand(\n\t\t\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t\t\t): ObserveResult<T> {\n\t\t\t\tunsub();\n\t\t\t\tdetachInspectorHook?.();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\tconst resolvedTarget = graph.resolve(basePath);\n\t\t\t\tconst expanded = graph._createObserveResult<T>(\n\t\t\t\t\tbasePath,\n\t\t\t\t\tresolvedTarget as Node<T>,\n\t\t\t\t\tresolveObserveDetail(merged),\n\t\t\t\t);\n\t\t\t\tif (merged.format != null) {\n\t\t\t\t\tgraph._attachFormatLogger(expanded, merged);\n\t\t\t\t}\n\t\t\t\treturn expanded;\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 minimal = options.detail === \"minimal\";\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\tanyCompletedCleanly: boolean;\n\t\t\tanyErrored: 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\tanyCompletedCleanly: false,\n\t\t\tanyErrored: false,\n\t\t};\n\t\t/** Per-node terminal state for allCompletedCleanly computation. */\n\t\tconst nodeErrored = new Set<string>();\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\tlet batchSeq = 0;\n\t\tconst unsubs = picked.map(([path, nd]) =>\n\t\t\tnd.subscribe((msgs) => {\n\t\t\t\tbatchSeq++;\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\n\t\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t\t: {};\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 (minimal) {\n\t\t\t\t\t\tif (t === DIRTY) result.dirtyCount++;\n\t\t\t\t\t\telse if (t === RESOLVED) result.resolvedCount++;\n\t\t\t\t\t\telse if (t === COMPLETE && !nodeErrored.has(path)) result.anyCompletedCleanly = true;\n\t\t\t\t\t\telse if (t === ERROR) {\n\t\t\t\t\t\t\tresult.anyErrored = true;\n\t\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\t}\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 (!nodeErrored.has(path)) result.anyCompletedCleanly = 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.anyErrored = true;\n\t\t\t\t\t\tnodeErrored.add(path);\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\n\t\tconst graph = this;\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 anyCompletedCleanly() {\n\t\t\t\treturn result.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn result.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn result.anyCompletedCleanly && !result.anyErrored;\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\texpand(\n\t\t\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t\t\t): ObserveResult {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\tconst expanded = graph._createObserveResultForAll(resolveObserveDetail(merged));\n\t\t\t\tif (merged.format != null) {\n\t\t\t\t\tgraph._attachFormatLogger(expanded, merged);\n\t\t\t\t}\n\t\t\t\treturn expanded;\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Fallback ObserveResult for single-node when inspector is disabled but `format` is requested.\n\t * Subscribes to raw messages and accumulates events with timeline info.\n\t */\n\tprivate _createFallbackObserveResult(path: string, options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline !== false;\n\t\tconst acc = {\n\t\t\tvalues: {} as Record<string, unknown>,\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [] as ObserveEvent[],\n\t\t\tanyCompletedCleanly: false,\n\t\t\tanyErrored: false,\n\t\t};\n\t\tconst target = this.resolve(path);\n\t\tlet batchSeq = 0;\n\t\tconst unsub = target.subscribe((msgs) => {\n\t\t\tbatchSeq++;\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst t = m[0];\n\t\t\t\tconst base = timeline\n\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t: {};\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tacc.values[path] = m[1];\n\t\t\t\t\tacc.events.push({ type: \"data\", path, data: m[1], ...base });\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tacc.dirtyCount++;\n\t\t\t\t\tacc.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tacc.resolvedCount++;\n\t\t\t\t\tacc.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!acc.anyErrored) acc.anyCompletedCleanly = true;\n\t\t\t\t\tacc.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tacc.anyErrored = true;\n\t\t\t\t\tacc.events.push({ type: \"error\", path, data: m[1], ...base });\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 acc.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn acc.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn acc.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn acc.events;\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn acc.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn acc.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn acc.anyCompletedCleanly && !acc.anyErrored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tunsub();\n\t\t\t},\n\t\t\texpand() {\n\t\t\t\tthrow new Error(\"expand() requires inspector mode (Graph.inspectorEnabled = true)\");\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Fallback ObserveResult for graph-wide when inspector is disabled but `format` is requested.\n\t */\n\tprivate _createFallbackObserveResultForAll(options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline !== false;\n\t\tconst actor = options.actor;\n\t\tconst acc = {\n\t\t\tvalues: {} as Record<string, unknown>,\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [] as ObserveEvent[],\n\t\t\tanyCompletedCleanly: false,\n\t\t\tanyErrored: false,\n\t\t};\n\t\tconst nodeErrored = new Set<string>();\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\tlet batchSeq = 0;\n\t\tconst unsubs = picked.map(([path, nd]) =>\n\t\t\tnd.subscribe((msgs) => {\n\t\t\t\tbatchSeq++;\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\n\t\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t\t: {};\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tacc.values[path] = m[1];\n\t\t\t\t\t\tacc.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\tacc.dirtyCount++;\n\t\t\t\t\t\tacc.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\tacc.resolvedCount++;\n\t\t\t\t\t\tacc.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\tif (!nodeErrored.has(path)) acc.anyCompletedCleanly = true;\n\t\t\t\t\t\tacc.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tacc.anyErrored = true;\n\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\tacc.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 acc.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn acc.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn acc.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn acc.events;\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn acc.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn acc.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn acc.anyCompletedCleanly && !acc.anyErrored;\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\texpand() {\n\t\t\t\tthrow new Error(\"expand() requires inspector mode (Graph.inspectorEnabled = true)\");\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Attaches a format logger to an ObserveResult, rendering events as they arrive.\n\t * Wraps the result's dispose to flush pending events.\n\t */\n\tprivate _attachFormatLogger(result: ObserveResult, options: ObserveOptions): void {\n\t\tconst format = options.format!;\n\t\tconst logger = options.logger ?? ((line: string) => console.log(line));\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 = resolveObserveTheme(options.theme);\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\t// Poll-free event flushing: watch the events array length via a cursor.\n\t\t// The fallback ObserveResult pushes events synchronously during subscribe callbacks,\n\t\t// so we use Object.defineProperty to intercept event pushes.\n\t\tlet cursor = 0;\n\t\tconst flush = () => {\n\t\t\tconst events = result.events;\n\t\t\twhile (cursor < events.length) {\n\t\t\t\tconst event = events[cursor++];\n\t\t\t\tif (shouldLog(event.type)) {\n\t\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Wrap the events array's push to flush on each new event.\n\t\tconst origPush = (result.events as ObserveEvent[]).push;\n\t\t(result.events as ObserveEvent[]).push = function (...items: ObserveEvent[]) {\n\t\t\tconst ret = origPush.apply(this, items);\n\t\t\tflush();\n\t\t\treturn ret;\n\t\t};\n\n\t\t// Wrap dispose to flush any remaining events.\n\t\tconst origDispose = result.dispose.bind(result);\n\t\t(result as { dispose(): void }).dispose = () => {\n\t\t\torigDispose();\n\t\t\tflush();\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 { expand: _, ...described } = this.describe({\n\t\t\tactor: options.actor,\n\t\t\tfilter: options.filter,\n\t\t\tdetail: \"standard\",\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\t...described,\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 * Register a cleanup function to be called on {@link Graph.destroy}.\n\t *\n\t * Factories use this to attach teardown logic for internal nodes, keepalive\n\t * subscriptions, or other resources that are not registered on the graph and\n\t * would otherwise leak on repeated create/destroy cycles.\n\t *\n\t * Returns a removal function — call it to unregister the disposer early.\n\t */\n\taddDisposer(fn: () => void): () => void {\n\t\tthis._disposers.add(fn);\n\t\treturn () => {\n\t\t\tthis._disposers.delete(fn);\n\t\t};\n\t}\n\n\t/**\n\t * Drains disposers (registered via {@link addDisposer}), then sends `[[TEARDOWN]]` to all\n\t * nodes and clears registries on this graph and every mounted subgraph (§3.7).\n\t * The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\t// Drain disposers (keepalive unsubs etc.) BEFORE TEARDOWN so that\n\t\t// internal effect nodes are disconnected before the cascade fires.\n\t\tfor (const dispose of [...this._disposers]) {\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._disposers.clear();\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 { expand: _, ...d } = this.describe({ detail: \"full\" });\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\t// Strip non-restorable fields (runtime attribution) so snapshot → restore → snapshot\n\t\t// is idempotent. Use describe({ detail: \"full\" }) for audit snapshots instead.\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = d.nodes[key]!;\n\t\t\tsortedNodes[key] = node;\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 object with **recursively sorted object keys** for deterministic serialization (§3.8).\n\t *\n\t * @remarks\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\ttoObject(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * ECMAScript `JSON.stringify` hook — delegates to {@link Graph.toObject}.\n\t *\n\t * @remarks\n\t * Must return a plain object (not a string) so `JSON.stringify(graph)` works correctly\n\t * without double-encoding.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.toObject();\n\t}\n\n\t/**\n\t * Deterministic JSON **text**: `JSON.stringify` of {@link Graph.toObject} 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 >= 3 messages\n\t * schedule a save (`DATA`/`RESOLVED`/terminal/destruction), never pure tier-0/1/2 control\n\t * waves (`START`/`DIRTY`/`INVALIDATE`/`PAUSE`/`RESUME`).\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 { expand: _expand, ...raw } = this.describe({ detail: \"full\" });\n\t\t\t\t// Strip non-restorable fields for persistence idempotency\n\t\t\t\tconst cleanNodes: Record<string, DescribeNodeOutput> = {};\n\t\t\t\tfor (const [p, n] of Object.entries(raw.nodes)) {\n\t\t\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = n!;\n\t\t\t\t\tcleanNodes[p] = node;\n\t\t\t\t}\n\t\t\t\tconst described = { ...raw, nodes: cleanNodes };\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(this.name, { 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(this.name, {\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]) >= 3);\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst nd = this.resolve(path);\n\t\t\t\tif (nd == null) return;\n\t\t\t\tconst described = describeNode(nd, resolveDescribeFields(\"standard\"));\n\t\t\t\tif (!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 * and `trace()` writes 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 * Unified reasoning trace: write annotations or read the ring buffer.\n\t *\n\t * Write: `graph.trace(\"path\", \"reason\")` — attaches a reasoning annotation\n\t * to a node, capturing *why* an AI agent set a value.\n\t * No-op when {@link Graph.inspectorEnabled} is `false`.\n\t *\n\t * Read: `graph.trace()` — returns a chronological log of all annotations.\n\t * Returns `[]` when {@link Graph.inspectorEnabled} is `false`.\n\t */\n\ttrace(path: string, reason: string): void;\n\ttrace(): readonly TraceEntry[];\n\ttrace(path?: string, reason?: string): undefined | readonly TraceEntry[] {\n\t\tif (path != null && reason != null) {\n\t\t\tif (!Graph.inspectorEnabled) return;\n\t\t\tthis.resolve(path); // validate path exists\n\t\t\tthis._annotations.set(path, reason);\n\t\t\tthis._traceRing.push({ path, reason, timestamp_ns: monotonicNs() });\n\t\t\treturn;\n\t\t}\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({ path: nb, depth: next.depth + 1 });\n\t\t}\n\t}\n\n\treturn [...out].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACgJO,IAAM,YAAwB;AAAA,EACpC,aAAa;AAAA,EACb,MAAM;AAAA,EAEN,OAAO,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B,CAAC,GAAI,cAAc,IAAI,IAAI,KAAK,CAAC,CAAE;AACzD,aAAO,CAAC,GAAGD,eAAc,GAAGC,cAAa;AAAA,IAC1C;AACA,UAAM,eAAe,CAAC,GAAI,YAAY,IAAI,IAAI,KAAK,CAAC,CAAE;AACtD,UAAM,gBAAgB,CAAC,GAAI,cAAc,IAAI,IAAI,KAAK,CAAC,CAAE;AACzD,WAAO,CAAC,GAAG,cAAc,GAAG,aAAa;AAAA,EAC1C;AAEA,QAAM,UAAU,oBAAI,IAAY,CAAC,IAAI,CAAC;AACtC,QAAM,MAAM,oBAAI,IAAY;AAC5B,QAAM,QAAgD,CAAC,EAAE,MAAM,MAAM,OAAO,EAAE,CAAC;AAC/E,SAAO,MAAM,SAAS,GAAG;AACxB,UAAM,OAAO,MAAM,MAAM;AACzB,QAAI,YAAY,QAAQ,KAAK,SAAS,SAAU;AAChD,eAAW,MAAM,UAAU,KAAK,IAAI,GAAG;AACtC,UAAI,CAAC,MAAM,QAAQ,IAAI,EAAE,EAAG;AAC5B,cAAQ,IAAI,EAAE;AACd,UAAI,IAAI,EAAE;AACV,YAAM,KAAK,EAAE,MAAM,IAAI,OAAO,KAAK,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":["node","size","node","actor","wantsStructured","text","edgeKey","depNeighbors","edgeNeighbors"]}
|
|
1
|
+
{"version":3,"sources":["../../src/graph/index.ts","../../src/extra/utils/sizeof.ts","../../src/graph/codec.ts","../../src/core/batch.ts","../../src/core/clock.ts","../../src/core/guard.ts","../../src/core/messages.ts","../../src/core/actor.ts","../../src/core/config.ts","../../src/core/versioning.ts","../../src/core/node.ts","../../src/core/meta.ts","../../src/core/sugar.ts","../../src/extra/timer.ts","../../src/extra/utils/ring-buffer.ts","../../src/graph/profile.ts","../../src/graph/graph.ts"],"sourcesContent":["/**\n * Graph container: registry, wiring, introspection (Phase 1).\n */\n\nexport { OVERHEAD as SIZEOF_OVERHEAD, SIZEOF_SYMBOL, sizeof } from \"../extra/utils/sizeof.js\";\nexport {\n\tcreateDagCborCodec,\n\tcreateDagCborZstdCodec,\n\tdecodeEnvelope,\n\tENVELOPE_VERSION,\n\ttype EvictedSubgraphInfo,\n\ttype EvictionPolicy,\n\tencodeEnvelope,\n\ttype GraphCodec,\n\tJsonCodec,\n\ttype LazyGraphCodec,\n\tregisterBuiltinCodecs,\n\treplayWAL,\n\ttype WALEntry,\n} from \"./codec.js\";\nexport {\n\ttype DescribeFilter,\n\tdiffForWAL,\n\tGRAPH_META_SEGMENT,\n\tGraph,\n\ttype GraphActorOptions,\n\ttype GraphAttachStorageOptions,\n\ttype GraphCheckpointRecord,\n\ttype GraphDescribeOptions,\n\ttype GraphDescribeOutput,\n\ttype GraphDiagramDirection,\n\ttype GraphDiagramOptions,\n\ttype GraphDiffChange,\n\ttype GraphDiffResult,\n\ttype GraphFactoryContext,\n\ttype GraphNodeFactory,\n\ttype GraphObserveAll,\n\ttype GraphObserveOne,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n\ttype GraphVersionChange,\n\ttype GraphWALDiff,\n\ttype ObserveDetail,\n\ttype ObserveEvent,\n\ttype ObserveOptions,\n\ttype ObserveResult,\n\ttype ObserveTheme,\n\ttype ObserveThemeName,\n\ttype ReachableDirection,\n\ttype ReachableOptions,\n\treachable,\n\ttype TraceEntry,\n} from \"./graph.js\";\nexport {\n\ttype GraphProfileOptions,\n\ttype GraphProfileResult,\n\tgraphProfile,\n\ttype NodeProfile,\n} from \"./profile.js\";\n","/**\n * Approximate in-memory size estimation for arbitrary JS values.\n *\n * Iterative walk with cycle detection via `WeakSet`. V8-tuned overhead\n * heuristics. Not exact — approximate enough for profiling and hotspot\n * detection.\n *\n * Use cases: `graphProfile` (per-node value size), reactive data structure\n * memory audits, heuristic cache admission.\n *\n * @module\n */\n\n/** Approximate per-type overhead in bytes (V8 heuristics). */\nexport const OVERHEAD = {\n\tobject: 56,\n\tarray: 64,\n\tstring: 40, // header; content added separately\n\tnumber: 8,\n\tboolean: 4,\n\tnull: 0,\n\tundefined: 0,\n\tsymbol: 40,\n\tbigint: 16, // base; scales with digit count (see `_bigintSize`)\n\tfunction: 120,\n\tmap: 72,\n\tset: 72,\n\tmapEntry: 40,\n\tsetEntry: 24,\n\tdate: 24,\n\tregexp: 48,\n\terror: 64,\n\turl: 80,\n\tpromise: 48,\n\tweakmap: 40,\n\tweakset: 40,\n} as const;\n\n/**\n * Optional user hook. Declare a `sizeof` symbol key on any object to return\n * a precomputed size (in bytes); the walker will honor it and skip recursion.\n *\n * @example\n * ```ts\n * const SIZEOF = Symbol.for(\"sizeof\");\n * class MyCache { [SIZEOF]() { return this.bytes; } }\n * ```\n */\nexport const SIZEOF_SYMBOL = Symbol.for(\"sizeof\");\n\n/**\n * Estimate the approximate retained memory (in bytes) of a JS value.\n *\n * Handles primitives, plain objects, arrays, Maps, Sets, ArrayBuffers +\n * TypedArrays (shared-buffer dedup), Date, RegExp, Error, URL, Promise,\n * WeakMap, WeakSet, nested combinations. Cyclic refs are counted once.\n *\n * @param value - The value to measure.\n * @returns Approximate size in bytes.\n */\nexport function sizeof(value: unknown): number {\n\tconst seen = new WeakSet<object>();\n\tconst seenBuffers = new WeakSet<ArrayBufferLike>();\n\t// Iterative walk via explicit stack — avoids blowing the call stack on\n\t// deeply nested values (linked lists, AST nodes, deep JSON).\n\tconst stack: unknown[] = [value];\n\tlet total = 0;\n\twhile (stack.length > 0) {\n\t\tconst v = stack.pop();\n\t\ttotal += _shallowSize(v, seen, seenBuffers, stack);\n\t}\n\treturn total;\n}\n\n/** Shallow size of `v`; pushes children onto `stack` for iterative traversal. */\nfunction _shallowSize(\n\tvalue: unknown,\n\tseen: WeakSet<object>,\n\tseenBuffers: WeakSet<ArrayBufferLike>,\n\tstack: unknown[],\n): number {\n\tif (value === null || value === undefined) return 0;\n\n\tconst t = typeof value;\n\tswitch (t) {\n\t\tcase \"number\":\n\t\t\treturn OVERHEAD.number;\n\t\tcase \"boolean\":\n\t\t\treturn OVERHEAD.boolean;\n\t\tcase \"string\":\n\t\t\treturn OVERHEAD.string + (value as string).length * 2;\n\t\tcase \"bigint\":\n\t\t\treturn OVERHEAD.bigint + _bigintSize(value as bigint);\n\t\tcase \"symbol\":\n\t\t\treturn OVERHEAD.symbol;\n\t\tcase \"function\":\n\t\t\tif (seen.has(value as object)) return 0;\n\t\t\tseen.add(value as object);\n\t\t\treturn OVERHEAD.function;\n\t\tcase \"undefined\":\n\t\t\treturn 0;\n\t}\n\n\tconst obj = value as object;\n\tif (seen.has(obj)) return 0;\n\tseen.add(obj);\n\n\t// User-supplied size hook wins — `Symbol.for(\"sizeof\")` method on the\n\t// object returns an exact byte count and we skip recursion.\n\tconst hook = (obj as Record<symbol, unknown>)[SIZEOF_SYMBOL];\n\tif (typeof hook === \"function\") {\n\t\ttry {\n\t\t\tconst reported = (hook as () => unknown).call(obj);\n\t\t\tif (typeof reported === \"number\" && Number.isFinite(reported)) return reported;\n\t\t} catch {\n\t\t\t/* ignore — fall through to default estimator */\n\t\t}\n\t}\n\n\tif (obj instanceof Date) return OVERHEAD.date;\n\tif (obj instanceof RegExp) return OVERHEAD.regexp + obj.source.length * 2;\n\tif (obj instanceof Error) {\n\t\tconst m = obj.message ? obj.message.length * 2 : 0;\n\t\tconst s = obj.stack ? obj.stack.length * 2 : 0;\n\t\treturn OVERHEAD.error + m + s;\n\t}\n\tif (typeof URL !== \"undefined\" && obj instanceof URL) {\n\t\treturn OVERHEAD.url + obj.href.length * 2;\n\t}\n\tif (typeof Promise !== \"undefined\" && obj instanceof Promise) {\n\t\treturn OVERHEAD.promise;\n\t}\n\tif (obj instanceof WeakMap) return OVERHEAD.weakmap;\n\tif (obj instanceof WeakSet) return OVERHEAD.weakset;\n\n\tif (obj instanceof Map) {\n\t\tlet size = OVERHEAD.map;\n\t\tfor (const [k, v] of obj) {\n\t\t\tsize += OVERHEAD.mapEntry;\n\t\t\tstack.push(k);\n\t\t\tstack.push(v);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (obj instanceof Set) {\n\t\tlet size = OVERHEAD.set;\n\t\tfor (const v of obj) {\n\t\t\tsize += OVERHEAD.setEntry;\n\t\t\tstack.push(v);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\tconst size = OVERHEAD.array + obj.length * 8;\n\t\tfor (const item of obj) stack.push(item);\n\t\treturn size;\n\t}\n\n\t// ArrayBuffer — count once per buffer (multi-view dedup via `seenBuffers`).\n\tif (obj instanceof ArrayBuffer) {\n\t\tif (seenBuffers.has(obj)) return 0;\n\t\tseenBuffers.add(obj);\n\t\treturn obj.byteLength;\n\t}\n\tif (ArrayBuffer.isView(obj)) {\n\t\tconst view = obj as { byteLength: number; buffer: ArrayBufferLike };\n\t\tif (seenBuffers.has(view.buffer)) return 48; // view header only\n\t\tseenBuffers.add(view.buffer);\n\t\t// Charge the full underlying buffer — a small view over a large\n\t\t// buffer still retains all of it. Add the view header on top.\n\t\treturn view.buffer.byteLength + 48;\n\t}\n\n\t// Plain object — sum key overhead + recurse into values.\n\tlet size = OVERHEAD.object;\n\tconst keys = Object.keys(obj);\n\tfor (const key of keys) {\n\t\tsize += OVERHEAD.string + key.length * 2;\n\t\ttry {\n\t\t\tstack.push((obj as Record<string, unknown>)[key]);\n\t\t} catch {\n\t\t\t/* getter throw — skip this key */\n\t\t}\n\t}\n\treturn size;\n}\n\n/** BigInt digit-count-based sizing: each ~32-bit limb ≈ 8 bytes. */\nfunction _bigintSize(n: bigint): number {\n\tconst abs = n < 0n ? -n : n;\n\tif (abs === 0n) return 0;\n\tconst bits = abs.toString(2).length;\n\treturn Math.ceil(bits / 32) * 8;\n}\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 * Wire-protocol envelope (v1):\n *\n * [envelope_v=1: u8][name_len: u8][name: utf8][codec_v: u16 BE][payload: rest]\n *\n * `graph.snapshot({format: \"bytes\", codec: name})` wraps the codec's\n * `encode` output in this envelope; `Graph.decode(bytes)` auto-dispatches\n * via the config's codec registry — no out-of-band content-type needed.\n */\n\nimport type { GraphReFlyConfig } from \"../core/config.js\";\nimport type { GraphCheckpointRecord, 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/** Human-readable name; used as the lookup key in the envelope and config registry. */\n\treadonly name: string;\n\n\t/**\n\t * Codec version. Bumps on breaking wire format changes; `decode` receives\n\t * this via the envelope so codecs can dispatch on historical layouts.\n\t * Must fit in a `u16` (0–65535).\n\t */\n\treadonly version: number;\n\n\t/** MIME-like content type identifier (e.g. `\"application/dag-cbor+zstd\"`). */\n\treadonly contentType: 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 * `codecVersion` is the version that produced `buffer` (read from the\n\t * envelope). Omit when the caller is sure of the version (tests, one-shot\n\t * round-trips). Codecs that support multiple historical layouts dispatch\n\t * on this value.\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, codecVersion?: number): 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, codecVersion?: number): GraphPersistSnapshot;\n}\n\n// ---------------------------------------------------------------------------\n// Delta checkpoint types (requires V0 — Phase 6.0)\n// ---------------------------------------------------------------------------\n\n/**\n * WAL entry. Unified with {@link GraphCheckpointRecord} — every record\n * already carries `mode` / `seq` / `timestamp_ns` / `format_version`, so the\n * WAL is just an ordered list of records. `replayWAL` walks this list.\n */\nexport type WALEntry = GraphCheckpointRecord;\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\tname: \"json\",\n\tversion: 1,\n\tcontentType: \"application/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, _codecVersion?: number): 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 (factory — requires @ipld/dag-cbor DI)\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 * config.registerCodec(codec);\n * const bytes = graph.snapshot({ format: \"bytes\", codec: \"dag-cbor\" });\n * ```\n */\nexport function createDagCborCodec(dagCbor: {\n\tencode: (value: unknown) => Uint8Array;\n\tdecode: (bytes: Uint8Array) => unknown;\n}): GraphCodec {\n\treturn {\n\t\tname: \"dag-cbor\",\n\t\tversion: 1,\n\t\tcontentType: \"application/dag-cbor\",\n\t\tencode: (snapshot) => dagCbor.encode(snapshot),\n\t\tdecode: (buffer, _codecVersion) => 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 * config.registerCodec(codec);\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\tname: \"dag-cbor-zstd\",\n\t\tversion: 1,\n\t\tcontentType: \"application/dag-cbor+zstd\",\n\t\tencode: (snapshot) => zstd.compressSync(dagCbor.encode(snapshot)),\n\t\tdecode: (buffer, _codecVersion) =>\n\t\t\tdagCbor.decode(zstd.decompressSync(buffer)) as GraphPersistSnapshot,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Envelope (v1) — self-describing codec metadata prepended to payload bytes\n// ---------------------------------------------------------------------------\n\n/** Current envelope format version. Bump on breaking layout changes. */\nexport const ENVELOPE_VERSION = 1;\n\nconst ENVELOPE_MIN_LEN = 4; // env_v(1) + name_len(1) + codec_v(2) + name/payload(≥0)\n\n/**\n * Prepend the v1 envelope to `payload` identifying `codec`. The resulting\n * bytes are self-describing — any caller with access to the registering\n * {@link GraphReFlyConfig} can {@link decodeEnvelope} without knowing the\n * codec up front.\n *\n * Layout:\n * `[envelope_v=1: u8][name_len: u8][name: utf8][codec_v: u16 BE][payload: rest]`\n *\n * @throws If `codec.name` encodes to more than 255 UTF-8 bytes or\n * `codec.version` doesn't fit in a u16.\n */\nexport function encodeEnvelope(\n\tcodec: Pick<GraphCodec, \"name\" | \"version\">,\n\tpayload: Uint8Array,\n): Uint8Array {\n\tconst nameBytes = new TextEncoder().encode(codec.name);\n\tif (nameBytes.length === 0 || nameBytes.length > 255) {\n\t\tthrow new Error(\n\t\t\t`encodeEnvelope: codec name \"${codec.name}\" encodes to ${nameBytes.length} bytes (must be 1–255)`,\n\t\t);\n\t}\n\tconst cv = codec.version;\n\tif (!Number.isInteger(cv) || cv < 0 || cv > 0xffff) {\n\t\tthrow new Error(\n\t\t\t`encodeEnvelope: codec.version ${cv} out of u16 range (expected integer 0–65535)`,\n\t\t);\n\t}\n\t// Guard against RangeError-on-alloc for very large payloads — we need\n\t// `Number.isSafeInteger` math on `1 + 1 + nameBytes.length + 2 +\n\t// payload.length` and the resulting Uint8Array must fit within the\n\t// platform limit (2³² − 1 bytes on 64-bit JS engines).\n\tconst totalLen = 1 + 1 + nameBytes.length + 2 + payload.length;\n\tif (totalLen > 0xffffffff) {\n\t\tthrow new Error(\n\t\t\t`encodeEnvelope: total envelope size ${totalLen} exceeds 2^32-1 bytes (payload ${payload.length} bytes)`,\n\t\t);\n\t}\n\tconst out = new Uint8Array(totalLen);\n\tlet i = 0;\n\tout[i++] = ENVELOPE_VERSION;\n\tout[i++] = nameBytes.length;\n\tout.set(nameBytes, i);\n\ti += nameBytes.length;\n\tout[i++] = (cv >>> 8) & 0xff;\n\tout[i++] = cv & 0xff;\n\tout.set(payload, i);\n\treturn out;\n}\n\n/**\n * Inverse of {@link encodeEnvelope}. Reads the header, resolves the codec\n * via `config.lookupCodec(name)`, and returns the codec + its version + the\n * inner payload slice. The caller feeds `payload` to `codec.decode(payload,\n * codecVersion)` — or uses {@link Graph.decode} which does both steps.\n *\n * @throws If the envelope is truncated, the version is unsupported, or the\n * named codec isn't registered on `config`.\n */\nexport function decodeEnvelope(\n\tbytes: Uint8Array,\n\tconfig: GraphReFlyConfig,\n): { codec: GraphCodec; codecVersion: number; payload: Uint8Array } {\n\tif (bytes.length < ENVELOPE_MIN_LEN) {\n\t\tthrow new Error(`decodeEnvelope: bytes too short (${bytes.length} < ${ENVELOPE_MIN_LEN})`);\n\t}\n\tlet i = 0;\n\tconst envVersion = bytes[i++]!;\n\tif (envVersion !== ENVELOPE_VERSION) {\n\t\tthrow new Error(\n\t\t\t`decodeEnvelope: unsupported envelope version ${envVersion} (expected ${ENVELOPE_VERSION})`,\n\t\t);\n\t}\n\tconst nameLen = bytes[i++]!;\n\tif (nameLen === 0) {\n\t\tthrow new Error(\"decodeEnvelope: name_len must be >= 1\");\n\t}\n\tif (i + nameLen + 2 > bytes.length) {\n\t\tthrow new Error(\n\t\t\t`decodeEnvelope: envelope truncated (need ${i + nameLen + 2} bytes, have ${bytes.length})`,\n\t\t);\n\t}\n\tconst name = new TextDecoder().decode(bytes.subarray(i, i + nameLen));\n\ti += nameLen;\n\tconst codecVersion = ((bytes[i]! << 8) | bytes[i + 1]!) >>> 0;\n\ti += 2;\n\tconst payload = bytes.subarray(i);\n\tconst codec = config.lookupCodec<GraphCodec>(name);\n\tif (codec == null) {\n\t\tthrow new Error(\n\t\t\t`decodeEnvelope: codec \"${name}\" not registered (envelope codec_v=${codecVersion})`,\n\t\t);\n\t}\n\treturn { codec, codecVersion, payload };\n}\n\n/**\n * Register the built-in {@link JsonCodec} on a config. Called once on\n * `defaultConfig` at module load so `graph.snapshot({format: \"bytes\", codec:\n * \"json\"})` works out of the box. Test / isolated configs should call this\n * manually before the first node is created.\n */\nexport function registerBuiltinCodecs(config: GraphReFlyConfig): void {\n\tconfig.registerCodec(JsonCodec);\n}\n\n// ---------------------------------------------------------------------------\n// WAL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Reconstruct a snapshot from a WAL (sequence of {@link GraphCheckpointRecord}s).\n *\n * - Must start with a `\"full\"` record carrying a baseline snapshot — that's\n * the anchor {@link Graph.attachStorage} always emits on the first flush\n * of any tier (and every `compactEvery`-th flush thereafter).\n * - Subsequent `\"full\"` entries (compaction points) **replace** the result\n * wholesale.\n * - `\"diff\"` entries roll forward by applying the structural diff —\n * added nodes (via `nodesAddedFull`), removed nodes, and changed fields\n * are reflected into the accumulated snapshot.\n *\n * Validates monotonic `seq` progression across entries.\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.mode !== \"full\") {\n\t\tthrow new Error(\"WAL must start with a full record carrying a baseline snapshot\");\n\t}\n\n\tlet result: GraphPersistSnapshot = JSON.parse(JSON.stringify(first.snapshot));\n\tlet prevSeq: number = first.seq;\n\n\tfor (let i = 1; i < entries.length; i++) {\n\t\tconst entry = entries[i]!;\n\t\tif (entry.seq <= prevSeq) {\n\t\t\tthrow new Error(\n\t\t\t\t`WAL chain broken at index ${i}: seq=${entry.seq} must exceed prev seq=${prevSeq}`,\n\t\t\t);\n\t\t}\n\n\t\tif (entry.mode === \"full\") {\n\t\t\t// Replace baseline wholesale (Unit 23 D fix — Object.assign left\n\t\t\t// stale keys from pre-compact state visible).\n\t\t\tresult = JSON.parse(JSON.stringify(entry.snapshot));\n\t\t\tprevSeq = entry.seq;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// mode === \"diff\": apply structural diff to the accumulated snapshot.\n\t\tconst diff = entry.diff;\n\t\t// Apply removes first so a path reused across a remove+add in a single\n\t\t// diff lands on the `nodesAddedFull` slice rather than being wiped.\n\t\tfor (const path of diff.nodesRemoved) {\n\t\t\tdelete result.nodes[path];\n\t\t}\n\t\t// Reinstate added nodes from the full-slice payload carried by\n\t\t// GraphWALDiff. Deep-clone so later mutations don't alias the WAL\n\t\t// entry's source slice.\n\t\tconst addedFull = diff.nodesAddedFull;\n\t\tif (addedFull != null) {\n\t\t\tfor (const [path, slice] of Object.entries(addedFull)) {\n\t\t\t\tresult.nodes[path] = JSON.parse(JSON.stringify(slice));\n\t\t\t}\n\t\t}\n\t\tfor (const change of diff.nodesChanged) {\n\t\t\tconst existing = result.nodes[change.path];\n\t\t\tif (existing == null) continue;\n\t\t\t(existing as Record<string, unknown>)[change.field] = change.to;\n\t\t}\n\n\t\t// Edges are derived from node `_deps` at restore time (Unit 7) — no\n\t\t// separate edge-patch pass.\n\t\tprevSeq = entry.seq;\n\t}\n\n\treturn result;\n}\n","/**\n * Batch deferral for tier-3+ messages.\n *\n * §1.3.7 — Inside a batch, tier 0–2 signals propagate immediately. Tier 3\n * (DATA/RESOLVED), tier 4 (COMPLETE/ERROR), and tier 5 (TEARDOWN) are queued\n * and drained in ascending phase order after the outermost `batch()` callback\n * returns.\n *\n * **Phase vocabulary:**\n * - Phase 1 = tiers 0–2 — immediate, never queued.\n * - Phase 2 = tier 3 — {@link drainPhase2}. Value settlements.\n * - Phase 3 = tier 4 — {@link drainPhase3}. Terminal signals.\n * - Phase 4 = tier 5 — {@link drainPhase4}. TEARDOWN (unified deferral).\n *\n * Drain rule: lowest non-empty phase first. Re-enqueues during drain bump the\n * loop back to the lowest non-empty phase, preserving \"earlier values settle\n * before later terminals/teardown\" across callback re-entry.\n *\n * **Pre-sorted input invariant.** `downWithBatch` assumes `messages` is\n * already sorted in ascending tier order (produced by `_frameBatch` in\n * `node.ts`). The walker exploits monotonicity for a single O(n) pass and\n * slices at phase boundaries without re-sorting.\n */\n\nimport type { Messages } from \"./messages.js\";\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\n\n/** Tier 3 (DATA/RESOLVED) deferral queue — drained first. */\nconst drainPhase2: Array<() => void> = [];\n/** Tier 4 (COMPLETE/ERROR) deferral queue — drained after phase 2. */\nconst drainPhase3: Array<() => void> = [];\n/** Tier 5 (TEARDOWN) deferral queue — drained last. */\nconst drainPhase4: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * a deferred drain is in progress. Nested `downWithBatch` calls during drain\n * still defer (they bump the drain loop).\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral\n * queue. If `fn` throws, deferred work for the outer frame is discarded\n * (unless a drain is already in progress — cross-language decision A4).\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\tdrainPhase2.length = 0;\n\t\t\t\t\tdrainPhase3.length = 0;\n\t\t\t\t\tdrainPhase4.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) flushInProgress = true;\n\n\tconst errors: unknown[] = [];\n\tlet iterations = 0;\n\ttry {\n\t\twhile (drainPhase2.length > 0 || drainPhase3.length > 0 || drainPhase4.length > 0) {\n\t\t\titerations += 1;\n\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\tdrainPhase2.length = 0;\n\t\t\t\tdrainPhase3.length = 0;\n\t\t\t\tdrainPhase4.length = 0;\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Always drain the lowest non-empty phase. Re-enqueues at any level\n\t\t\t// cause the next iteration to restart from phase 2 if needed.\n\t\t\tconst queue =\n\t\t\t\tdrainPhase2.length > 0 ? drainPhase2 : drainPhase3.length > 0 ? drainPhase3 : drainPhase4;\n\t\t\tconst ops = queue.splice(0);\n\t\t\tfor (const run of ops) {\n\t\t\t\ttry {\n\t\t\t\t\trun();\n\t\t\t\t} catch (e) {\n\t\t\t\t\terrors.push(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) flushInProgress = false;\n\t}\n\n\tif (errors.length === 1) throw errors[0];\n\tif (errors.length > 1) {\n\t\tthrow new AggregateError(errors, \"batch drain: multiple callbacks threw\");\n\t}\n}\n\n/**\n * Deliver pre-sorted messages through `sink` with tier-based deferral applied.\n *\n * `messages` MUST be in ascending tier order (produced by `_frameBatch` in\n * `node.ts`); the walker exploits that invariant to find phase cuts in one\n * pass without re-sorting.\n *\n * Behavior:\n * - Tier 0–2 — delivered synchronously.\n * - Tier 3 — deferred to {@link drainPhase2} when batching, else synchronous.\n * - Tier 4 — deferred to {@link drainPhase3} when batching, else synchronous.\n * - Tier 5 — deferred to {@link drainPhase4} when batching, else synchronous.\n *\n * Tier-classification uses the caller-supplied `tierOf` so that batch stays\n * decoupled from `GraphReFlyConfig`. NodeImpl passes `config.tierOf` (a\n * pre-bound closure built once in the config constructor) at the emit site;\n * alternate configs can pass their own lookup.\n */\nexport function downWithBatch(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\ttierOf: (t: symbol) => number,\n): void {\n\tif (messages.length === 0) return;\n\n\t// Fast path: single message (hot in propagation).\n\tif (messages.length === 1) {\n\t\tconst tier = tierOf(messages[0][0]);\n\t\tif (tier < 3 || !isBatching()) {\n\t\t\tsink(messages);\n\t\t\treturn;\n\t\t}\n\t\tconst queue = tier >= 5 ? drainPhase4 : tier === 4 ? drainPhase3 : drainPhase2;\n\t\tqueue.push(() => sink(messages));\n\t\treturn;\n\t}\n\n\t// Multi-message: walk once over pre-sorted input, find phase cuts.\n\t// Monotone tier order means `phase2Start <= phase3Start <= phase4Start`.\n\tconst n = messages.length;\n\tlet phase2Start = n;\n\tlet phase3Start = n;\n\tlet phase4Start = n;\n\n\tlet i = 0;\n\twhile (i < n && tierOf(messages[i][0]) < 3) i++;\n\tphase2Start = i;\n\twhile (i < n && tierOf(messages[i][0]) === 3) i++;\n\tphase3Start = i;\n\twhile (i < n && tierOf(messages[i][0]) === 4) i++;\n\tphase4Start = i;\n\t// Anything from phase4Start..n has tier >= 5.\n\n\tconst batching = isBatching();\n\n\tif (phase2Start > 0) {\n\t\t// Immediate tier 0–2 region.\n\t\tconst immediate = messages.slice(0, phase2Start);\n\t\tsink(immediate);\n\t}\n\n\tif (phase3Start > phase2Start) {\n\t\tconst phase2 = messages.slice(phase2Start, phase3Start);\n\t\tif (batching) drainPhase2.push(() => sink(phase2));\n\t\telse sink(phase2);\n\t}\n\n\tif (phase4Start > phase3Start) {\n\t\tconst phase3 = messages.slice(phase3Start, phase4Start);\n\t\tif (batching) drainPhase3.push(() => sink(phase3));\n\t\telse sink(phase3);\n\t}\n\n\tif (n > phase4Start) {\n\t\tconst phase4 = messages.slice(phase4Start, n);\n\t\tif (batching) drainPhase4.push(() => sink(phase4));\n\t\telse sink(phase4);\n\t}\n}\n","/**\n * Centralised timestamp utilities.\n *\n * Convention: all graphrefly-ts timestamps use nanoseconds (`_ns` suffix).\n *\n * - {@link monotonicNs} — monotonic clock (ordering, durations, timeline events).\n * - {@link wallClockNs} — wall-clock (mutation attribution, cron emission).\n *\n * **Precision limits (JS platform):**\n *\n * - `monotonicNs`: effective ~microsecond precision. `performance.now()` returns\n * milliseconds with ~5µs resolution; the last 3 digits of the nanosecond value\n * are always zero. Python's `time.monotonic_ns()` gives true nanoseconds.\n *\n * - `wallClockNs`: ~256ns precision loss at current epoch. `Date.now() * 1e6`\n * produces values around 1.8×10¹⁸ which exceed IEEE 754's 2⁵³ safe integer\n * limit. Python's `time.time_ns()` (arbitrary-precision `int`) has no loss.\n * In practice this is irrelevant — JS is single-threaded, so sub-microsecond\n * timestamp collisions cannot occur.\n */\n\n/** Monotonic nanosecond timestamp via `performance.now()`. */\nexport function monotonicNs(): number {\n\treturn Math.trunc(performance.now() * 1_000_000);\n}\n\n/** Wall-clock nanosecond timestamp via `Date.now()`. */\nexport function wallClockNs(): number {\n\treturn Date.now() * 1_000_000;\n}\n","import type { Actor } from \"./actor.js\";\n\n/**\n * Actions checked by {@link NodeGuard}. `write` covers both {@link Node.down} and\n * {@link Node.up} today; finer-grained strings may be added later (e.g. `\"write.data\"`).\n */\nexport type GuardAction = \"write\" | \"signal\" | \"observe\" | (string & {});\n\nexport type NodeGuard = (actor: Actor, action: GuardAction) => boolean;\n\nexport type GuardDeniedDetails = {\n\tactor: Actor;\n\taction: GuardAction;\n\t/** Registry or options name when known */\n\tnodeName?: string;\n};\n\n/**\n * Thrown when a {@link NodeGuard} denies an action for a given actor.\n *\n * Carries the rejected `actor`, `action`, and optional `nodeName` for diagnostic\n * messages and middleware error handling.\n *\n * @example\n * ```ts\n * import { GuardDenied, policy } from \"@graphrefly/graphrefly-ts\";\n *\n * const guard = policy((allow) => { allow(\"observe\"); });\n * try {\n * if (!guard({ type: \"llm\", id: \"agent-1\" }, \"write\")) {\n * throw new GuardDenied(\n * { actor: { type: \"llm\", id: \"agent-1\" }, action: \"write\", nodeName: \"userInput\" },\n * );\n * }\n * } catch (e) {\n * if (e instanceof GuardDenied) console.error(e.action, e.actor.type); // \"write\" \"llm\"\n * }\n * ```\n */\nexport class GuardDenied extends Error {\n\treadonly actor: Actor;\n\treadonly action: GuardAction;\n\treadonly nodeName?: string;\n\n\t/**\n\t * @param details - Actor, action, and optional node name for the denial.\n\t * @param message - Optional override for the default error message.\n\t */\n\tconstructor(details: GuardDeniedDetails, message?: string) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\t`GuardDenied: action \"${String(details.action)}\" denied for actor type \"${String(details.actor.type)}\"`,\n\t\t);\n\t\tthis.name = \"GuardDenied\";\n\t\tthis.actor = details.actor;\n\t\tthis.action = details.action;\n\t\tthis.nodeName = details.nodeName;\n\t}\n\n\t/** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */\n\tget node(): string | undefined {\n\t\treturn this.nodeName;\n\t}\n}\n\ntype Where = (actor: Actor) => boolean;\n\ntype Rule = {\n\tkind: \"allow\" | \"deny\";\n\tactions: Set<GuardAction>;\n\twhere: Where;\n};\n\nfunction normalizeActions(action: GuardAction | readonly GuardAction[]): GuardAction[] {\n\tif (Array.isArray(action)) {\n\t\treturn [...action];\n\t}\n\treturn [action as GuardAction];\n}\n\nfunction matchesActions(set: Set<GuardAction>, action: GuardAction): boolean {\n\treturn set.has(action) || set.has(\"*\" as GuardAction);\n}\n\nexport type PolicyAllow = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyDeny = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyRuleData = {\n\teffect: \"allow\" | \"deny\";\n\taction: GuardAction | readonly GuardAction[];\n\tactorType?: string | readonly string[];\n\tactorId?: string | readonly string[];\n\tclaims?: Record<string, unknown>;\n};\n\n/**\n * Declarative guard builder. Precedence: any matching **deny** blocks even if an allow also matches.\n * If no rule matches, the guard returns `false` (deny-by-default). Aligned with graphrefly-py `policy()`.\n *\n * @param build - Callback that registers `allow(...)` / `deny(...)` rules in order.\n * @returns A `NodeGuard` for use as `node({ guard })`.\n *\n * @example\n * ```ts\n * const guard = policy((allow, deny) => {\n * allow(\"observe\");\n * deny(\"write\", { where: (a) => a.type === \"llm\" });\n * });\n * ```\n */\nexport function policy(build: (allow: PolicyAllow, deny: PolicyDeny) => void): NodeGuard {\n\tconst rules: Rule[] = [];\n\tconst allow: PolicyAllow = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"allow\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tconst deny: PolicyDeny = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"deny\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tbuild(allow, deny);\n\treturn (actor, action) => {\n\t\tlet denied = false;\n\t\tlet allowed = false;\n\t\tfor (const r of rules) {\n\t\t\tif (!matchesActions(r.actions, action)) continue;\n\t\t\tif (!r.where(actor)) continue;\n\t\t\tif (r.kind === \"deny\") {\n\t\t\t\tdenied = true;\n\t\t\t} else {\n\t\t\t\tallowed = true;\n\t\t\t}\n\t\t}\n\t\tif (denied) return false;\n\t\treturn allowed;\n\t};\n}\n\n/**\n * Rebuild a declarative guard from persisted policy data (snapshot-safe).\n *\n * Rules are deny-overrides, same semantics as {@link policy}.\n */\nexport function policyFromRules(rules: readonly PolicyRuleData[]): NodeGuard {\n\treturn policy((allow, deny) => {\n\t\tfor (const rule of rules) {\n\t\t\tconst actorTypes =\n\t\t\t\trule.actorType == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);\n\t\t\tconst actorIds =\n\t\t\t\trule.actorId == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);\n\t\t\tconst claimEntries = Object.entries(rule.claims ?? {});\n\t\t\tconst where: Where = (actor) => {\n\t\t\t\tif (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;\n\t\t\t\tif (actorIds !== null && !actorIds.has(String(actor.id ?? \"\"))) return false;\n\t\t\t\tfor (const [key, value] of claimEntries) {\n\t\t\t\t\tif ((actor as Record<string, unknown>)[key] !== value) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tif (rule.effect === \"deny\") {\n\t\t\t\tdeny(rule.action, { where });\n\t\t\t} else {\n\t\t\t\tallow(rule.action, { where });\n\t\t\t}\n\t\t}\n\t});\n}\n\nconst STANDARD_WRITE_TYPES = [\"human\", \"llm\", \"wallet\", \"system\"] as const;\n\n/**\n * Derives a best-effort `meta.access` hint string by probing `guard` with the\n * standard actor types `human`, `llm`, `wallet`, `system` for the `\"write\"` action\n * (roadmap 1.5). Aligned with graphrefly-py `access_hint_for_guard`.\n *\n * @param guard - Guard function to probe (typically from {@link policy}).\n * @returns `\"restricted\"` when no standard type is allowed; `\"both\"` when both\n * `human` and `llm` are allowed (plus optionally `system`); the single allowed\n * type name when only one passes; or a `\"+\"` joined list otherwise.\n *\n * @example\n * ```ts\n * import { policy, accessHintForGuard } from \"@graphrefly/graphrefly-ts\";\n *\n * const guardBoth = policy((allow) => { allow(\"write\"); });\n * accessHintForGuard(guardBoth); // \"both\"\n *\n * const guardHuman = policy((allow) => {\n * allow(\"write\", { where: (a) => a.type === \"human\" });\n * });\n * accessHintForGuard(guardHuman); // \"human\"\n * ```\n */\nexport function accessHintForGuard(guard: NodeGuard): string {\n\tconst allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: \"\" }, \"write\"));\n\tif (allowed.length === 0) return \"restricted\";\n\tif (\n\t\tallowed.includes(\"human\") &&\n\t\tallowed.includes(\"llm\") &&\n\t\tallowed.every((t) => t === \"human\" || t === \"llm\" || t === \"system\")\n\t) {\n\t\treturn \"both\";\n\t}\n\tif (allowed.length === 1) return allowed[0];\n\treturn allowed.join(\"+\");\n}\n","/**\n * GraphReFly message protocol — §1 `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n * Emissions are always `[[Type, Data?], ...]` (no single-tuple shorthand).\n *\n * This file is protocol-pure:\n * - Message type symbols (10 built-ins).\n * - `Message` / `Messages` tuple types.\n * - `MessageTypeRegistration` interface (shape of a registry entry).\n *\n * It does NOT own the registry, tier lookups, or any cross-cutting singleton\n * state — that lives in `GraphReFlyConfig` (see `config.ts`) so custom\n * protocols can build isolated instances. Import this module when you need\n * the symbol constants or the tuple types; import `config.ts` when you need\n * tier / wire-crossing / registry lookups.\n */\n\n/** Subscribe-time handshake. Delivered to each new sink at the top of `subscribe()`. Tier 0. */\nexport const START = Symbol.for(\"graphrefly/START\");\n/** Value delivery (`DATA`, value). Tier 3 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 1 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 3 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 1 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 2 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 2 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 5 — deferred to batch phase 4. */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 4 — deferred to batch phase 3. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 4 — deferred to batch phase 3. */\nexport const ERROR = Symbol.for(\"graphrefly/ERROR\");\n\n/** One protocol tuple: `[Type, optional payload]`. */\nexport type Message = readonly [symbol, unknown?];\n\n/** A batch of tuples — the wire shape for `node.down()` / `node.up()`. */\nexport type Messages = readonly Message[];\n\n// ---------------------------------------------------------------------------\n// Interned singletons for payload-free tuples\n// ---------------------------------------------------------------------------\n//\n// Every emission path used to allocate fresh `[[DIRTY]]`, `[[RESOLVED]]`,\n// etc. — two arrays per emit in the hot path. Since none of these tuples\n// carry a payload, one frozen instance is indistinguishable from a\n// fresh one. We intern them at module load and reuse forever. Only\n// `[DATA, v]`, `[ERROR, e]`, `[PAUSE, lockId]`, `[RESUME, lockId]` still\n// allocate per-call because they carry payloads.\n//\n// Downstream code MUST treat these as immutable. `Object.freeze` makes\n// accidental mutation throw in strict mode. Do not `push`, splice, or\n// otherwise mutate a Messages array that came from one of these.\n\n/** Singleton `[DIRTY]` tuple — payload-free, interned. */\nexport const DIRTY_MSG: Message = Object.freeze([DIRTY]) as Message;\n/** Singleton `[RESOLVED]` tuple — payload-free, interned. */\nexport const RESOLVED_MSG: Message = Object.freeze([RESOLVED]) as Message;\n/** Singleton `[INVALIDATE]` tuple — payload-free, interned. */\nexport const INVALIDATE_MSG: Message = Object.freeze([INVALIDATE]) as Message;\n/** Singleton `[START]` tuple — payload-free, interned. */\nexport const START_MSG: Message = Object.freeze([START]) as Message;\n/** Singleton `[COMPLETE]` tuple — payload-free, interned. */\nexport const COMPLETE_MSG: Message = Object.freeze([COMPLETE]) as Message;\n/** Singleton `[TEARDOWN]` tuple — payload-free, interned. */\nexport const TEARDOWN_MSG: Message = Object.freeze([TEARDOWN]) as Message;\n\n/** Pre-wrapped `[[DIRTY]]` for `_emit([DIRTY_ONLY_BATCH])`-style callers. */\nexport const DIRTY_ONLY_BATCH: Messages = Object.freeze([DIRTY_MSG]) as Messages;\n/** Pre-wrapped `[[RESOLVED]]`. */\nexport const RESOLVED_ONLY_BATCH: Messages = Object.freeze([RESOLVED_MSG]) as Messages;\n/** Pre-wrapped `[[INVALIDATE]]`. */\nexport const INVALIDATE_ONLY_BATCH: Messages = Object.freeze([INVALIDATE_MSG]) as Messages;\n/** Pre-wrapped `[[COMPLETE]]`. */\nexport const COMPLETE_ONLY_BATCH: Messages = Object.freeze([COMPLETE_MSG]) as Messages;\n/** Pre-wrapped `[[TEARDOWN]]`. */\nexport const TEARDOWN_ONLY_BATCH: Messages = Object.freeze([TEARDOWN_MSG]) as Messages;\n\n// ---------------------------------------------------------------------------\n// Registry entry shape\n// ---------------------------------------------------------------------------\n\n/**\n * Per-type record stored in a {@link GraphReFlyConfig}'s registry.\n *\n * - `tier` — signal tier (0–5 built-in; custom tiers allowed but should fit\n * the phase model used by `batch.ts`).\n * - `wireCrossing` — when `true`, forwarded across SSE/WebSocket/worker\n * adapters. Defaults to `tier >= 3` if omitted in registration input.\n * - `metaPassthrough` — when `false`, this message type is filtered out of\n * `Graph.signal` deliveries to meta companion nodes (spec §2.3). Meta\n * companions still receive everything via their primary's own cascade.\n * Defaults to `true` (meta receives the message).\n */\nexport interface MessageTypeRegistration {\n\ttier: number;\n\twireCrossing: boolean;\n\tmetaPassthrough: boolean;\n}\n\n/**\n * Input accepted by {@link GraphReFlyConfig.registerMessageType}. Only `tier`\n * is required; `wireCrossing` defaults to `tier >= 3`; `metaPassthrough`\n * defaults to `true`.\n */\nexport interface MessageTypeRegistrationInput {\n\ttier: number;\n\twireCrossing?: boolean;\n\tmetaPassthrough?: boolean;\n}\n","/**\n * Who is performing an operation (attribution + ABAC input).\n *\n * @see GRAPHREFLY-SPEC — roadmap Phase 1.5 (Actor & Guard).\n */\nexport type Actor = {\n\ttype: \"human\" | \"llm\" | \"wallet\" | \"system\" | string;\n\tid: string;\n} & Record<string, unknown>;\n\n/** Default actor when none is passed ({@link normalizeActor}). */\nexport const DEFAULT_ACTOR: Actor = { type: \"system\", id: \"\" };\n\n/**\n * Fills missing `type` / `id` on an actor and returns {@link DEFAULT_ACTOR} when input is undefined.\n *\n * @param actor - Optional partial actor from a transport hint.\n * @returns A normalized `Actor` safe to pass to guards and graph APIs.\n *\n * @example\n * ```ts\n * import { normalizeActor } from \"@graphrefly/graphrefly-ts\";\n *\n * normalizeActor({ type: \"human\", id: \"u1\" });\n * ```\n */\nexport function normalizeActor(actor?: Actor): Actor {\n\tif (actor == null) return DEFAULT_ACTOR;\n\tconst { type, id, ...rest } = actor;\n\treturn {\n\t\ttype: type ?? \"system\",\n\t\tid: id ?? \"\",\n\t\t...rest,\n\t} as Actor;\n}\n","/**\n * Singleton protocol config. Holds the message-type registry, the\n * `onMessage` / `onSubscribe` hooks, versioning defaults, and the freeze flag.\n *\n * Layering: this file is protocol-pure. It imports only from `messages.ts`\n * and declares opaque type shapes for handlers — the concrete default\n * implementations and the `defaultConfig` instance live in `node.ts` so that\n * handler bodies can touch `NodeImpl` internals without creating a cycle.\n *\n * Two access paths:\n * 1. **Default instance** (`defaultConfig` in `node.ts`) — use\n * `configure((cfg) => ...)` at app startup; every node implicitly binds to it.\n * 2. **Isolated instance** (`new GraphReFlyConfig(...)`) — pass via\n * `opts.config` for test isolation or custom protocol stacks.\n *\n * A config **freezes on first getter read** of any hook (`onMessage`,\n * `onSubscribe`). `NodeImpl`'s constructor intentionally touches one of these\n * on first use so configuration cannot drift once nodes exist.\n */\n\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\ttype MessageTypeRegistration,\n\ttype MessageTypeRegistrationInput,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, VersioningLevel } from \"./versioning.js\";\n\n// ---------------------------------------------------------------------------\n// Handler type shapes\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal node surface visible to default handlers. Concrete `NodeImpl`\n * implements this plus a large set of package-private fields; handlers that\n * need the richer surface cast to the concrete type in `node.ts`.\n */\nexport interface NodeCtx {\n\treadonly name?: string;\n\treadonly status: string;\n\treadonly cache: unknown;\n}\n\n/** Imperative actions available inside a node's compute function (§5). */\nexport interface NodeActions {\n\t/**\n\t * Sugar for `down([[DATA, value]])`. One call = one wave with a\n\t * single DATA payload. The emit pipeline auto-prefixes `[DIRTY]`,\n\t * runs equals substitution against the live cache, and dispatches\n\t * to sinks with phase deferral. Diamond-safe by construction.\n\t */\n\temit(value: unknown): void;\n\t/**\n\t * Send one or more messages downstream. Accepts either a single\n\t * {@link Message} tuple or a {@link Messages} array of tuples. One\n\t * call = one wave: the emit pipeline tier-sorts the input,\n\t * auto-prefixes `[DIRTY]` when a tier-3 payload is present and the\n\t * node isn't already dirty, runs equals substitution, then\n\t * dispatches. Multiple calls produce multiple waves.\n\t */\n\tdown(messageOrMessages: Message | Messages): void;\n\t/**\n\t * Send one or more messages upstream. Accepts the same shapes as\n\t * {@link down}. Tier 3 (DATA/RESOLVED) and tier 4 (COMPLETE/ERROR)\n\t * are downstream-only and will throw — up is for DIRTY, INVALIDATE,\n\t * PAUSE, RESUME, and TEARDOWN only. No cache advance, no equals,\n\t * no framing — a plain forward to every dep.\n\t */\n\tup(messageOrMessages: Message | Messages): void;\n}\n\n/**\n * Message-flow context passed to {@link OnMessageHandler}.\n *\n * - `\"down-in\"` — message arriving from a dep (identified by `depIndex`).\n * - `\"up-in\"` — message arriving from a sink.\n */\nexport type MessageContext = { direction: \"down-in\"; depIndex: number } | { direction: \"up-in\" };\n\n/**\n * Per-sink context passed to {@link OnSubscribeHandler}.\n */\nexport interface SubscribeContext {\n\t/** Post-subscribe sink count. `1` means first subscriber after 0. */\n\tsinkCount: number;\n\t/** True when this subscribe cleared a resubscribable terminal state. */\n\tafterTerminalReset: boolean;\n}\n\n/**\n * Singleton message interceptor. Called for every message in either direction\n * before the default per-tier dispatch runs. Return `\"consume\"` to suppress\n * default handling.\n */\nexport type OnMessageHandler = (\n\tnode: NodeCtx,\n\tmsg: Message,\n\tctx: MessageContext,\n\tactions: NodeActions,\n) => \"consume\" | undefined;\n\n/**\n * Singleton subscribe ceremony. Fires for every sink subscribe on every node.\n * Default implementation emits the START handshake (+ cached DATA when\n * present) to the new sink. Return a cleanup function to run on unsubscribe.\n */\nexport type OnSubscribeHandler = (\n\tnode: NodeCtx,\n\tsink: (messages: Messages) => void,\n\tctx: SubscribeContext,\n\tactions: NodeActions,\n) => (() => void) | undefined;\n\n/**\n * Event payload for {@link GlobalInspectorHook}. One event fires per outgoing\n * message batch from any node bound to the config.\n *\n * - `kind: \"emit\"` — fires after equals substitution (`finalMessages`) and\n * before sink dispatch. `messages` is the exact batch sinks see.\n */\nexport type GlobalInspectorEvent = {\n\tkind: \"emit\";\n\tnode: NodeCtx;\n\tmessages: Messages;\n};\n\n/**\n * Process-global observability hook for full-graph tracing\n * (Redux-DevTools-style action history). Fires from every node's `_emit`\n * waist whenever {@link GraphReFlyConfig.inspectorEnabled} is `true`.\n *\n * Distinct from per-node `_setInspectorHook` (which is the dep-message /\n * fn-run causal trace used by `Graph.observe(path, { causal, derived })`).\n * Use the global hook to record every emission across every node — useful for\n * time-travel debuggers, tracers, and replay tooling. Use the per-node hook\n * to attribute a single subscribed path's wave to its driving deps.\n *\n * Errors thrown from the hook are swallowed — instrumentation must not break\n * the data plane.\n */\nexport type GlobalInspectorHook = (event: GlobalInspectorEvent) => void;\n\n// ---------------------------------------------------------------------------\n// GraphReFlyConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Singleton protocol config.\n *\n * A config freezes on first getter read of any hook. After freeze, any\n * attempt to mutate (register a message type, set a hook) throws.\n */\nexport class GraphReFlyConfig {\n\tprivate _messageTypes = new Map<symbol, MessageTypeRegistration>();\n\tprivate _codecs = new Map<string, { readonly name: string; readonly version: number }>();\n\tprivate _onMessage: OnMessageHandler;\n\tprivate _onSubscribe: OnSubscribeHandler;\n\tprivate _defaultVersioning: VersioningLevel | undefined;\n\tprivate _defaultHashFn: HashFn | undefined;\n\tprivate _inspectorEnabled: boolean = !(\n\t\ttypeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n\t);\n\tprivate _globalInspector?: GlobalInspectorHook;\n\tprivate _frozen = false;\n\n\t/**\n\t * Pre-bound tier lookup — shared by every node bound to this config. Since\n\t * the registry is frozen on first hook access, this closure can be built\n\t * once in the constructor and handed directly to `downWithBatch` /\n\t * `_frameBatch` paths without per-node or per-emission `.bind(config)`\n\t * allocation.\n\t */\n\treadonly tierOf: (t: symbol) => number;\n\n\tconstructor(init: {\n\t\tonMessage: OnMessageHandler;\n\t\tonSubscribe: OnSubscribeHandler;\n\t\tdefaultVersioning?: VersioningLevel;\n\t\tdefaultHashFn?: HashFn;\n\t}) {\n\t\tthis._onMessage = init.onMessage;\n\t\tthis._onSubscribe = init.onSubscribe;\n\t\tthis._defaultVersioning = init.defaultVersioning;\n\t\tthis._defaultHashFn = init.defaultHashFn;\n\t\t// Captured once. Calls back into `this._messageTypes` — still returns\n\t\t// the current registration, but post-freeze the registry is immutable\n\t\t// so the closure is effectively constant.\n\t\tthis.tierOf = (t: symbol): number => {\n\t\t\tconst reg = this._messageTypes.get(t);\n\t\t\treturn reg != null ? reg.tier : 1;\n\t\t};\n\t}\n\n\t// --- Hook getters (freeze on read) ---\n\n\tget onMessage(): OnMessageHandler {\n\t\tthis._frozen = true;\n\t\treturn this._onMessage;\n\t}\n\n\tget onSubscribe(): OnSubscribeHandler {\n\t\tthis._frozen = true;\n\t\treturn this._onSubscribe;\n\t}\n\n\t// --- Hook setters (throw when frozen) ---\n\n\tset onMessage(v: OnMessageHandler) {\n\t\tthis._assertUnfrozen();\n\t\tthis._onMessage = v;\n\t}\n\n\tset onSubscribe(v: OnSubscribeHandler) {\n\t\tthis._assertUnfrozen();\n\t\tthis._onSubscribe = v;\n\t}\n\n\t/**\n\t * Default versioning level applied to every node bound to this config,\n\t * unless the node's own `opts.versioning` provides an explicit override.\n\t * Setting this is only allowed before the config freezes (i.e., before\n\t * the first node is created) so every node in the graph sees a\n\t * consistent starting level. Individual nodes can still opt into a\n\t * higher level via `opts.versioning`, or post-hoc via\n\t * `NodeImpl._applyVersioning(level)` when the node is quiescent.\n\t *\n\t * v0 is the minimum opt-in — unversioned nodes (`undefined`) skip\n\t * the version counter entirely. v1 adds content-addressed cid.\n\t * Future levels (v2, v3) are reserved for linked-history and\n\t * cryptographic attestation extensions.\n\t */\n\tget defaultVersioning(): VersioningLevel | undefined {\n\t\treturn this._defaultVersioning;\n\t}\n\tset defaultVersioning(v: VersioningLevel | undefined) {\n\t\tthis._assertUnfrozen();\n\t\tthis._defaultVersioning = v;\n\t}\n\n\t/**\n\t * Default content-hash function applied to every versioned node bound\n\t * to this config, unless the node's own `opts.versioningHash` provides\n\t * an explicit override. Use this when a graph needs a non-default hash\n\t * — e.g., swap the vendored sync SHA-256 for a faster non-crypto hash\n\t * (xxHash, FNV-1a) in hot-path workloads, or a stronger hash when\n\t * versioning v1 cids are used as audit anchors.\n\t *\n\t * Only settable before the config freezes. Individual nodes can still\n\t * override via `opts.versioningHash`.\n\t */\n\tget defaultHashFn(): HashFn | undefined {\n\t\treturn this._defaultHashFn;\n\t}\n\tset defaultHashFn(v: HashFn | undefined) {\n\t\tthis._assertUnfrozen();\n\t\tthis._defaultHashFn = v;\n\t}\n\n\t/**\n\t * When `false`, structured observation options (`causal`, `timeline`)\n\t * and `Graph.trace()` writes are no-ops. Raw `Graph.observe()` always\n\t * works. Default: `true` outside production (`NODE_ENV !== \"production\"`).\n\t *\n\t * Settable at any time — inspector gating is an operational concern, not\n\t * a protocol invariant, so it does NOT require freeze before node creation.\n\t */\n\tget inspectorEnabled(): boolean {\n\t\treturn this._inspectorEnabled;\n\t}\n\tset inspectorEnabled(v: boolean) {\n\t\tthis._inspectorEnabled = v;\n\t}\n\n\t/**\n\t * Process-global observability hook (Redux-DevTools-style full-graph\n\t * tracer). Fires once per outgoing batch from every node bound to this\n\t * config, gated by {@link inspectorEnabled}. See {@link GlobalInspectorHook}.\n\t *\n\t * Settable at any time — like {@link inspectorEnabled} this is operational,\n\t * not protocol-shaping, so it does NOT trigger config freeze.\n\t */\n\tget globalInspector(): GlobalInspectorHook | undefined {\n\t\treturn this._globalInspector;\n\t}\n\tset globalInspector(v: GlobalInspectorHook | undefined) {\n\t\tthis._globalInspector = v;\n\t}\n\n\t// --- Registry (writes require unfrozen; reads are free lookups) ---\n\n\t/**\n\t * Register a custom message type. Must be called before any node that\n\t * uses this config has been created — otherwise throws. Default\n\t * `wireCrossing` is `tier >= 3`.\n\t */\n\tregisterMessageType(t: symbol, input: MessageTypeRegistrationInput): this {\n\t\tthis._assertUnfrozen();\n\t\tthis._messageTypes.set(t, {\n\t\t\ttier: input.tier,\n\t\t\twireCrossing: input.wireCrossing ?? input.tier >= 3,\n\t\t\tmetaPassthrough: input.metaPassthrough ?? true,\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** Tier for `t`. Unknown types default to tier 1 (immediate, after START). */\n\tmessageTier(t: symbol): number {\n\t\tconst reg = this._messageTypes.get(t);\n\t\treturn reg != null ? reg.tier : 1;\n\t}\n\n\t/**\n\t * Whether `t` is registered as wire-crossing. Unknown types default to\n\t * `true` (spec §1.3.6 forward-compat — unknowns cross the wire).\n\t */\n\tisWireCrossing(t: symbol): boolean {\n\t\tconst reg = this._messageTypes.get(t);\n\t\treturn reg != null ? reg.wireCrossing : true;\n\t}\n\n\t/** Convenience inverse of {@link isWireCrossing}. */\n\tisLocalOnly(t: symbol): boolean {\n\t\treturn !this.isWireCrossing(t);\n\t}\n\n\t/**\n\t * Whether `t` is forwarded to meta companions by `Graph.signal`. Defaults\n\t * to `true` for unknowns (forward-compat — new types pass through meta by\n\t * default; opt-in filter via `registerMessageType({metaPassthrough: false})`).\n\t */\n\tisMetaPassthrough(t: symbol): boolean {\n\t\tconst reg = this._messageTypes.get(t);\n\t\treturn reg != null ? reg.metaPassthrough : true;\n\t}\n\n\t/** Whether `t` is a registered (built-in or custom) type. */\n\tisKnownMessageType(t: symbol): boolean {\n\t\treturn this._messageTypes.has(t);\n\t}\n\n\t// --- Codec registry (writes require unfrozen; reads are free lookups) ---\n\n\t/**\n\t * Register a graph codec by `codec.name`. Used by the envelope-based\n\t * `graph.snapshot({format: \"bytes\", codec: name})` path and\n\t * `Graph.decode(bytes)` auto-dispatch. Must be called before any node\n\t * bound to this config is created — otherwise throws.\n\t *\n\t * Re-registering the same name overwrites, so user codecs can shadow\n\t * built-in ones before freeze (e.g., to swap a zstd-wrapped dag-cbor in\n\t * for `\"dag-cbor\"`).\n\t */\n\tregisterCodec<T extends { readonly name: string; readonly version: number }>(codec: T): this {\n\t\tthis._assertUnfrozen();\n\t\tthis._codecs.set(codec.name, codec);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Resolve a registered codec by name. Returns `undefined` for unknown\n\t * names. Typed callers cast to their concrete codec interface (e.g.,\n\t * `config.lookupCodec<GraphCodec>(\"json\")`) — this method stays\n\t * layer-pure (no import of graph-layer types into `core/`).\n\t */\n\tlookupCodec<T = { readonly name: string; readonly version: number }>(\n\t\tname: string,\n\t): T | undefined {\n\t\treturn this._codecs.get(name) as T | undefined;\n\t}\n\n\t/** @internal Used by tests and dev tooling — check freeze state without triggering it. */\n\t_isFrozen(): boolean {\n\t\treturn this._frozen;\n\t}\n\n\tprivate _assertUnfrozen(): void {\n\t\tif (this._frozen) {\n\t\t\tthrow new Error(\n\t\t\t\t\"GraphReFlyConfig is frozen: a node has already captured this config. \" +\n\t\t\t\t\t\"Register custom types and set hooks before creating any node.\",\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Built-in registration\n// ---------------------------------------------------------------------------\n\n/**\n * Register the 10 built-in message types on a fresh config. Called by\n * `node.ts` when it constructs `defaultConfig` and by test code / advanced\n * users after `new GraphReFlyConfig(...)`.\n */\nexport function registerBuiltins(cfg: GraphReFlyConfig): void {\n\tcfg.registerMessageType(START, { tier: 0, wireCrossing: false });\n\tcfg.registerMessageType(DIRTY, { tier: 1, wireCrossing: false });\n\t// INVALIDATE, COMPLETE, ERROR, TEARDOWN do NOT pass through to meta\n\t// companions via Graph.signal (spec §2.3). Meta still sees them via the\n\t// primary's own down-cascade.\n\tcfg.registerMessageType(INVALIDATE, {\n\t\ttier: 1,\n\t\twireCrossing: false,\n\t\tmetaPassthrough: false,\n\t});\n\tcfg.registerMessageType(PAUSE, { tier: 2, wireCrossing: false });\n\tcfg.registerMessageType(RESUME, { tier: 2, wireCrossing: false });\n\tcfg.registerMessageType(DATA, { tier: 3, wireCrossing: true });\n\tcfg.registerMessageType(RESOLVED, { tier: 3, wireCrossing: true });\n\tcfg.registerMessageType(COMPLETE, {\n\t\ttier: 4,\n\t\twireCrossing: true,\n\t\tmetaPassthrough: false,\n\t});\n\tcfg.registerMessageType(ERROR, {\n\t\ttier: 4,\n\t\twireCrossing: true,\n\t\tmetaPassthrough: false,\n\t});\n\tcfg.registerMessageType(TEARDOWN, {\n\t\ttier: 5,\n\t\twireCrossing: true,\n\t\tmetaPassthrough: false,\n\t});\n}\n","/**\n * Node versioning — GRAPHREFLY-SPEC §7.\n *\n * Progressive, optional versioning for node identity and change tracking.\n *\n * - **V0**: `id` + `version` — identity & change detection (~16 bytes overhead)\n * - **V1**: + `cid` + `prev` — content addressing & linked history (~60 bytes overhead)\n *\n * **Lifecycle notes:**\n * - Version advances only on DATA (not RESOLVED, INVALIDATE, or TEARDOWN).\n * - `resetOnTeardown` clears the cached value but does NOT reset versioning state.\n * After teardown, `v.cid` still reflects the last DATA value, not the cleared cache.\n * The invariant `hash(node.cache) === v.cid` only holds in `settled`/`resolved` status.\n * - Resubscribable nodes preserve versioning across subscription lifetimes (monotonic counter).\n */\n\n// Runtime-agnostic — no `node:crypto` import. `randomUUID` comes from Web\n// Crypto (`globalThis.crypto.randomUUID()`), available in Node 14.17+,\n// browsers, Deno, Bun, and Cloudflare Workers. The default content hash is a\n// vendored sync SHA-256 (see `sha256Hex` below) so versioning stays callable\n// from any runtime — `crypto.subtle.digest` is async and can't back a\n// synchronous `defaultHash`.\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** V0: identity + monotonic version counter. */\nexport type V0 = {\n\treadonly id: string;\n\tversion: number;\n};\n\n/** V1: V0 + content-addressed identifier + previous cid link. */\nexport type V1 = V0 & {\n\tcid: string;\n\tprev: string | null;\n};\n\n/** Union of all versioning info shapes. */\nexport type NodeVersionInfo = V0 | V1;\n\n/** Supported versioning levels (extensible to 2, 3 later). */\nexport type VersioningLevel = 0 | 1;\n\n/** Function that hashes a value to a hex string (for V1 cid). */\nexport type HashFn = (value: unknown) => string;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface VersioningOptions {\n\t/** Override auto-generated id. */\n\tid?: string;\n\t/** Custom hash function for V1 cid (default: SHA-256 truncated to 16 hex chars). */\n\thash?: HashFn;\n}\n\n// ---------------------------------------------------------------------------\n// Default hash\n// ---------------------------------------------------------------------------\n\n/**\n * Canonicalize a value for deterministic cross-language hashing.\n *\n * - Integer-valued floats normalize to integer strings (`1.0` → `1`).\n * - `NaN`, `Infinity`, `-Infinity` are rejected (no JSON equivalent).\n * - `undefined` normalizes to `null`.\n * - Object keys are sorted lexicographically.\n *\n * This ensures TS `JSON.stringify` and Python `json.dumps(sort_keys=True)`\n * produce identical output for the same logical value.\n */\nexport function canonicalizeForHash(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow new TypeError(`Cannot hash non-finite number: ${value}`);\n\t\t}\n\t\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. ` +\n\t\t\t\t\t\"Cross-language cid parity is not guaranteed for unsafe integers.\",\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\" || typeof value === \"boolean\" || value === null) {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalizeForHash);\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst sorted: Record<string, unknown> = {};\n\t\tfor (const k of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tsorted[k] = canonicalizeForHash((value as Record<string, unknown>)[k]);\n\t\t}\n\t\treturn sorted;\n\t}\n\t// Fallback: coerce to null (bigint, symbol, function)\n\treturn null;\n}\n\n// SHA-256 round constants (FIPS 180-4).\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n\t0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n\t0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n\t0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n\t0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n\t0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n\t0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n\t0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nconst UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();\n\n/**\n * Sync SHA-256 of a UTF-8 string, returned as a lowercase hex digest. Matches\n * Node `crypto.createHash(\"sha256\").update(msg).digest(\"hex\")` byte-for-byte.\n *\n * Runtime-agnostic (no `node:crypto`, no `crypto.subtle`). Small enough to\n * inline rather than pulling a dependency; called only from `defaultHash`,\n * which runs once per DATA on versioned nodes, so per-call allocation is\n * acceptable. Callers that need a faster path override via\n * `NodeOptions.versioningHash`.\n */\nfunction sha256Hex(msg: string): string {\n\tconst bytes = UTF8_ENCODER.encode(msg);\n\tconst msgLen = bytes.length;\n\tconst bitLen = msgLen * 8;\n\t// Pad to multiple of 64: 0x80 byte + zeros + 8-byte big-endian bit length.\n\tconst totalLen = (msgLen + 9 + 63) & ~63;\n\tconst padded = new Uint8Array(totalLen);\n\tpadded.set(bytes);\n\tpadded[msgLen] = 0x80;\n\tconst dv = new DataView(padded.buffer);\n\t// Bit length as big-endian 64-bit int. JS numbers are 53-bit safe, so we\n\t// split into two 32-bit halves; messages up to 2^53 bits are supported.\n\tdv.setUint32(totalLen - 4, bitLen >>> 0, false);\n\tdv.setUint32(totalLen - 8, Math.floor(bitLen / 0x100000000) >>> 0, false);\n\n\t// Initial hash values (first 32 bits of fractional parts of sqrt of first 8 primes).\n\tlet h0 = 0x6a09e667;\n\tlet h1 = 0xbb67ae85;\n\tlet h2 = 0x3c6ef372;\n\tlet h3 = 0xa54ff53a;\n\tlet h4 = 0x510e527f;\n\tlet h5 = 0x9b05688c;\n\tlet h6 = 0x1f83d9ab;\n\tlet h7 = 0x5be0cd19;\n\n\tconst W = new Uint32Array(64);\n\tconst rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n\n\tfor (let off = 0; off < totalLen; off += 64) {\n\t\tfor (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4, false);\n\t\tfor (let i = 16; i < 64; i++) {\n\t\t\tconst w15 = W[i - 15];\n\t\t\tconst w2 = W[i - 2];\n\t\t\tconst s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ (w15 >>> 3);\n\t\t\tconst s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ (w2 >>> 10);\n\t\t\tW[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0;\n\t\t}\n\n\t\tlet a = h0;\n\t\tlet b = h1;\n\t\tlet c = h2;\n\t\tlet d = h3;\n\t\tlet e = h4;\n\t\tlet f = h5;\n\t\tlet g = h6;\n\t\tlet h = h7;\n\n\t\tfor (let i = 0; i < 64; i++) {\n\t\t\tconst S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n\t\t\tconst ch = (e & f) ^ (~e & g);\n\t\t\tconst t1 = (h + S1 + ch + SHA256_K[i] + W[i]) >>> 0;\n\t\t\tconst S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n\t\t\tconst mj = (a & b) ^ (a & c) ^ (b & c);\n\t\t\tconst t2 = (S0 + mj) >>> 0;\n\t\t\th = g;\n\t\t\tg = f;\n\t\t\tf = e;\n\t\t\te = (d + t1) >>> 0;\n\t\t\td = c;\n\t\t\tc = b;\n\t\t\tb = a;\n\t\t\ta = (t1 + t2) >>> 0;\n\t\t}\n\n\t\th0 = (h0 + a) >>> 0;\n\t\th1 = (h1 + b) >>> 0;\n\t\th2 = (h2 + c) >>> 0;\n\t\th3 = (h3 + d) >>> 0;\n\t\th4 = (h4 + e) >>> 0;\n\t\th5 = (h5 + f) >>> 0;\n\t\th6 = (h6 + g) >>> 0;\n\t\th7 = (h7 + h) >>> 0;\n\t}\n\n\tconst toHex = (x: number): string => x.toString(16).padStart(8, \"0\");\n\treturn (\n\t\ttoHex(h0) + toHex(h1) + toHex(h2) + toHex(h3) + toHex(h4) + toHex(h5) + toHex(h6) + toHex(h7)\n\t);\n}\n\n/**\n * Default content hash: SHA-256 of deterministic JSON, truncated to 16 hex\n * chars (~64-bit). Uses {@link canonicalizeForHash} for cross-language parity\n * with Python `default_hash`.\n */\nexport function defaultHash(value: unknown): string {\n\tconst canonical = canonicalizeForHash(value ?? null);\n\tconst json = JSON.stringify(canonical);\n\treturn sha256Hex(json).slice(0, 16);\n}\n\n/**\n * Cross-runtime UUID generator. Uses Web Crypto (`globalThis.crypto.randomUUID`)\n * when available. Falls back to a tiny `Math.random`-seeded RFC 4122 v4\n * generator for environments that omit `crypto.randomUUID` — identity only,\n * not cryptographic.\n */\nfunction randomUuid(): string {\n\tconst c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n\tif (c?.randomUUID) return c.randomUUID();\n\t// Fallback (extremely rare — only hits on very old runtimes that expose no\n\t// Web Crypto at all). Not cryptographically strong.\n\tconst r = () =>\n\t\tMath.floor(Math.random() * 0x100000000)\n\t\t\t.toString(16)\n\t\t\t.padStart(8, \"0\");\n\tconst hex = r() + r() + r() + r();\n\treturn (\n\t\t`${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-` +\n\t\t`${((parseInt(hex.slice(16, 17), 16) & 0x3) | 0x8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create initial versioning state for a node.\n *\n * @param level - 0 for V0, 1 for V1.\n * @param initialValue - The node's initial cached value (used for V1 cid).\n * @param opts - Optional overrides (id, hash).\n */\nexport function createVersioning(\n\tlevel: VersioningLevel,\n\tinitialValue: unknown,\n\topts?: VersioningOptions,\n): NodeVersionInfo {\n\tconst id = opts?.id ?? randomUuid();\n\tif (level === 0) {\n\t\treturn { id, version: 0 } satisfies V0;\n\t}\n\tconst hash = opts?.hash ?? defaultHash;\n\tconst cid = hash(initialValue);\n\treturn { id, version: 0, cid, prev: null } satisfies V1;\n}\n\n// ---------------------------------------------------------------------------\n// Advance\n// ---------------------------------------------------------------------------\n\n/**\n * Advance versioning state after a DATA emission (value changed).\n *\n * Mutates `info` in place for performance (called on every DATA).\n * Only call when the cached value has actually changed (not on RESOLVED).\n *\n * @param info - The node's current versioning state.\n * @param newValue - The new cached value.\n * @param hashFn - Hash function (only used for V1).\n */\nexport function advanceVersion(info: NodeVersionInfo, newValue: unknown, hashFn: HashFn): void {\n\tinfo.version += 1;\n\tif (\"cid\" in info) {\n\t\t(info as V1).prev = (info as V1).cid;\n\t\t(info as V1).cid = hashFn(newValue);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this V1 versioning info? */\nexport function isV1(info: NodeVersionInfo): info is V1 {\n\treturn \"cid\" in info;\n}\n","/**\n * `NodeImpl` — the single GraphReFly node primitive.\n *\n * Per-dep state lives in a `DepRecord[]` — one entry per declared dep —\n * consolidating subscription cleanup, latest-data tracking, dirty/settled\n * flags, and terminal state into a single structure per dep.\n *\n * This file also owns the default singleton handlers (`defaultOnMessage`,\n * `defaultOnSubscribe`), the `defaultConfig` instance, and the public\n * `configure(...)` entry point. They live here because their bodies touch\n * `NodeImpl` internals; `config.ts` stays NodeImpl-agnostic.\n *\n * See GRAPHREFLY-SPEC §2 and COMPOSITION-GUIDE §1/§9 for the behavior\n * contract. See SESSION-foundation-redesign.md §§1–10 for design history.\n */\n\nimport { registerBuiltinCodecs } from \"../graph/codec.js\";\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type {\n\tMessageContext,\n\tNodeActions,\n\tNodeCtx,\n\tOnMessageHandler,\n\tOnSubscribeHandler,\n\tSubscribeContext,\n} from \"./config.js\";\nimport { GraphReFlyConfig, registerBuiltins } from \"./config.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tCOMPLETE_ONLY_BATCH,\n\tDATA,\n\tDIRTY,\n\tDIRTY_MSG,\n\tDIRTY_ONLY_BATCH,\n\tERROR,\n\tINVALIDATE,\n\tINVALIDATE_ONLY_BATCH,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tRESOLVED,\n\tRESOLVED_MSG,\n\tRESOLVED_ONLY_BATCH,\n\tRESUME,\n\tSTART,\n\tSTART_MSG,\n\tTEARDOWN,\n\tTEARDOWN_ONLY_BATCH,\n} from \"./messages.js\";\nimport {\n\tadvanceVersion,\n\tcreateVersioning,\n\tdefaultHash,\n\ttype HashFn,\n\ttype NodeVersionInfo,\n\ttype VersioningLevel,\n} from \"./versioning.js\";\n\n// ---------------------------------------------------------------------------\n// Internal sentinel + type helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Placeholder unsubscribe used to mark a dep subscription as \"pending\" during\n * the synchronous window between `dep.unsub = noopUnsub` and the return of\n * `dep.node.subscribe(...)`. Ensures the liveness check `dep.unsub === null`\n * in the subscription callback correctly passes for synchronous push-on-\n * subscribe deliveries, while still blocking stale drainPhase2 closures that\n * fire after deactivation has set `dep.unsub = null`.\n */\nconst noopUnsub: () => void = () => {};\n\n/**\n * Maximum `_pendingRerun` depth before we give up and emit ERROR. Bounds\n * autoTrackNode / `_addDep` discovery loops — a well-formed discovery\n * converges in O(n) total rounds for n deps, so 100 is ample.\n */\nconst MAX_RERUN_DEPTH = 100;\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Lifecycle status of a node (GRAPHREFLY-SPEC §2.2). */\nexport type NodeStatus =\n\t| \"sentinel\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\n/** Callback that receives downstream message batches. */\nexport type NodeSink = (messages: Messages) => void;\n\n/**\n * Observability hook events fired by a per-node inspector. Used by\n * `Graph.observe(path, { causal, derived })` to build causal traces.\n *\n * - `\"dep_message\"` — fires in `_onDepMessage` before default dispatch,\n * one event per message received from a dep. Includes `depIndex` and\n * the raw `Message` tuple.\n * - `\"run\"` — fires in `_execFn` just before the user fn runs. Includes\n * the per-dep `prevData` snapshot that will be passed to fn.\n */\nexport type NodeInspectorHookEvent =\n\t| { kind: \"dep_message\"; depIndex: number; message: Message }\n\t| {\n\t\t\tkind: \"run\";\n\t\t\tbatchData: readonly (readonly unknown[] | undefined)[];\n\t\t\tprevData: readonly unknown[];\n\t };\n\n/** Callback attached to a node for per-message/per-run inspection. */\nexport type NodeInspectorHook = (event: NodeInspectorHookEvent) => void;\n\n/** Describe `type` for `Graph.describe` (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"effect\";\n\n/** Actor/delivery context for {@link Node.down} and {@link Node.up}. */\nexport type NodeTransportOptions = {\n\tactor?: Actor;\n\t/** When `true`, skips guard checks. */\n\tinternal?: boolean;\n\t/** `signal` for `Graph.signal` deliveries; default `write`. */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/**\n * Cleanup return shape from a node {@link NodeFn}.\n * - `() => void` — fires before the next fn run AND on deactivation (default).\n * - `{ deactivation: () => void }` — fires only on deactivation (persistent\n * resources that should survive across fn re-runs).\n */\nexport type NodeFnCleanup = (() => void) | { deactivation: () => void };\n\n/**\n * Fn-time context exposing per-wave metadata and a per-node persistent\n * scratch pad.\n *\n * - `prevData[i]` — last DATA value from dep `i` as of the END of the\n * previous wave (i.e. the value that was stable before this wave started).\n * Use as the fallback when `data[i]` is `undefined` (not involved) or\n * `[]` (RESOLVED, no new values this wave).\n * `undefined` means dep `i` has never produced DATA (sentinel state).\n * `null` is a valid DATA value. `undefined` is not a valid DATA value —\n * the protocol reserves it as the \"never sent\" sentinel.\n * - `ctx.prevData[i] === undefined` → dep has never produced DATA\n * - `ctx.prevData[i] !== undefined` → last DATA value (may be `null`)\n * - `terminalDeps[i]` — runtime shape:\n * - `undefined` → dep `i` is still live.\n * - `true` → dep `i` sent COMPLETE.\n * - anything else → dep `i` sent ERROR, value is the error payload.\n * Type is `readonly unknown[]` because `true | unknown` collapses to\n * `unknown` anyway; the three states are documented contract, not type.\n * - `store` — mutable bag that persists across fn runs within one activation\n * cycle. Wiped on deactivation and on resubscribable terminal reset.\n */\nexport interface FnCtx {\n\treadonly prevData: readonly unknown[];\n\treadonly terminalDeps: readonly unknown[];\n\treadonly store: Record<string, unknown>;\n}\n\n/**\n * Compute function passed to `node(deps, fn, opts?)`.\n *\n * `data[i]` holds the batch of DATA values received from dep `i` during the\n * current wave. Shape contract:\n * - `undefined` — dep `i` was not involved in this wave (no DIRTY received).\n * - `[]` — dep `i` was involved (dirtied), but settled as RESOLVED (value\n * unchanged). Use `ctx.prevData[i]` to read its last known value from the\n * previous wave.\n * - `[v1, v2, ...]` — dep `i` sent one or more DATA values. `at(-1)` gives\n * the latest; iterate for multi-emission processing.\n *\n * Emission is explicit via `actions.emit(v)` (sugar: equals + framing) or\n * `actions.down(msgs)` (raw). Return a cleanup function (or\n * `{ deactivation }`) to register teardown — any non-cleanup return value\n * is ignored. The `| void` leg lets arrow-block bodies satisfy `NodeFn`\n * without an explicit `return undefined`.\n *\n * Sugar constructors (`derived`, `effect`, `dynamicNode`) unwrap `data[i]`\n * to a single scalar (`at(-1)` with `ctx.prevData[i]` fallback) so their\n * user-facing fn signatures stay unchanged. Use raw `node()` when you need\n * the full batch array.\n */\nexport type NodeFn = (\n\tdata: readonly (readonly unknown[] | undefined)[],\n\tactions: NodeActions,\n\tctx: FnCtx,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: see JSDoc above.\n) => NodeFnCleanup | void;\n\n/** Options accepted by every node constructor. */\nexport interface NodeOptions<T = unknown> {\n\tname?: string;\n\tdescribeKind?: NodeDescribeKind;\n\tequals?: (a: T, b: T) => boolean;\n\t/**\n\t * Pre-populate the cache at construction. `null` is a valid initial value.\n\t * `undefined` is treated as absent (not a valid DATA payload).\n\t */\n\tinitial?: T | null;\n\tmeta?: Record<string, unknown>;\n\tresubscribable?: boolean;\n\tresetOnTeardown?: boolean;\n\t/** Auto-emit `[[COMPLETE]]` when all deps complete. Default `true`. */\n\tcompleteWhenDepsComplete?: boolean;\n\t/**\n\t * Auto-propagate `[[ERROR]]` when any dep errors. Default `true`.\n\t * Set `false` only for rescue/catchError operators that handle errors\n\t * explicitly via `ctx.terminalDeps`.\n\t */\n\terrorWhenDepsError?: boolean;\n\t/**\n\t * Tier-2 PAUSE/RESUME handling.\n\t * - `true` (default): wave completion suppressed while paused; fn fires\n\t * once on RESUME if gate is satisfied.\n\t * - `false`: node ignores PAUSE (sources like timers that must keep running).\n\t * - `\"resumeAll\"`: on RESUME, replay every buffered DATA (future).\n\t */\n\tpausable?: boolean | \"resumeAll\";\n\tguard?: NodeGuard;\n\tversioning?: VersioningLevel;\n\tversioningId?: string;\n\tversioningHash?: HashFn;\n\t/**\n\t * Override the config instance this node binds to. Defaults to\n\t * {@link defaultConfig}. Useful for test isolation and custom protocol\n\t * stacks. The first node that reads any hook on the config freezes it.\n\t */\n\tconfig?: GraphReFlyConfig;\n}\n\n/** A reactive node in the GraphReFly protocol. */\nexport interface Node<T = unknown> {\n\treadonly name?: string;\n\treadonly status: NodeStatus;\n\t/**\n\t * Current cached value. Returns `undefined` when the node is in\n\t * `\"sentinel\"` state (no DATA ever emitted). v5 reserves `undefined`\n\t * globally as the sentinel value — the valid DATA type is `T | null`.\n\t * Therefore `node.cache === undefined` is a valid \"never emitted\" guard.\n\t * `node.status` distinguishes the richer states (`\"sentinel\"`,\n\t * `\"settled\"`, `\"errored\"`, etc.) when you need more than has-value.\n\t */\n\treadonly cache: T | null | undefined;\n\treadonly meta: Record<string, Node>;\n\treadonly lastMutation: Readonly<{ actor: Actor; timestamp_ns: number }> | undefined;\n\treadonly v: Readonly<NodeVersionInfo> | undefined;\n\t/**\n\t * Send one or more messages downstream. Accepts either a single\n\t * {@link Message} tuple (e.g. `node.down([DATA, 42])`) or a\n\t * {@link Messages} array of tuples (e.g.\n\t * `node.down([[DIRTY], [DATA, 42]])`). One call = one wave: the\n\t * emit pipeline tier-sorts the input, auto-prefixes `[DIRTY]` when\n\t * any tier-3 payload is present and the node is not already dirty,\n\t * runs equals substitution against the live cache (§3.5.1), then\n\t * dispatches to sinks with phase deferral.\n\t */\n\tdown(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void;\n\t/**\n\t * Sugar for `down([[DATA, value]])`. One wave with a single DATA\n\t * payload — the pipeline adds the synthetic DIRTY prefix and runs\n\t * equals substitution against the live cache.\n\t */\n\temit(value: T | undefined | null, options?: NodeTransportOptions): void;\n\t/**\n\t * Send one or more messages upstream. Accepts the same shapes as\n\t * {@link down}. Upstream messages are tier <3 + tier 5 only\n\t * (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN); tier-3/4 payloads\n\t * throw — DATA/RESOLVED/COMPLETE/ERROR are downstream-only in this\n\t * protocol. No equals substitution, no cache advance, no DIRTY\n\t * auto-prefix — the up direction just forwards to every dep.\n\t */\n\tup?(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void;\n\tsubscribe(sink: NodeSink, actor?: Actor): () => void;\n\tallowsObserve(actor: Actor): boolean;\n\thasGuard(): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// DepRecord — per-dep state (§8.2)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-dep runtime state. One entry per upstream node.\n *\n * `terminal` is the single terminal-state slot, shaped to match\n * {@link FnCtx.terminalDeps}:\n * - `undefined` — dep is still live.\n * - `true` — dep sent COMPLETE.\n * - anything else — dep sent ERROR with that payload.\n *\n * Edge case: an ERROR carrying an `undefined` payload is indistinguishable\n * from \"live\". Pass meaningful error values (Error objects, domain tags).\n */\nexport interface DepRecord {\n\treadonly node: Node;\n\tunsub: (() => void) | null;\n\t/**\n\t * Last DATA value from this dep as of the end of the previous completed\n\t * wave. `undefined` until dep has produced at least one DATA (sentinel).\n\t * Committed by `_execFn` after snapshotting `ctx.prevData` and before\n\t * `_clearWaveFlags`. `undefined` is reserved as the \"never sent\" sentinel —\n\t * `undefined` is not a valid DATA payload.\n\t */\n\tprevData: unknown;\n\t/** True while awaiting DATA/RESOLVED for the current wave. */\n\tdirty: boolean;\n\t/**\n\t * True if this dep was dirtied in the current wave (set in `_depDirtied`,\n\t * cleared in `_clearWaveFlags`). Distinguishes \"RESOLVED\" (`involvedThisWave\n\t * && dataBatch.length === 0`) from \"not involved\" (`!involvedThisWave`) in\n\t * the `data[i]` batch snapshot passed to fn.\n\t */\n\tinvolvedThisWave: boolean;\n\t/**\n\t * DATA values accumulated from this dep during the current wave.\n\t * Populated by `_depSettledAsData`, cleared by `_clearWaveFlags`.\n\t * Snapshotted (copied) by `_execFn` before `_clearWaveFlags` runs so\n\t * that fn always sees the full wave batch.\n\t */\n\tdataBatch: unknown[];\n\t/** Terminal-state slot — see JSDoc on {@link DepRecord}. */\n\tterminal: unknown;\n}\n\nfunction createDepRecord(n: Node): DepRecord {\n\treturn {\n\t\tnode: n,\n\t\tunsub: null,\n\t\tprevData: undefined,\n\t\tdirty: false,\n\t\tinvolvedThisWave: false,\n\t\tdataBatch: [],\n\t\tterminal: undefined,\n\t};\n}\n\nfunction resetDepRecord(d: DepRecord): void {\n\td.prevData = undefined;\n\td.dirty = false;\n\td.involvedThisWave = false;\n\td.dataBatch.length = 0;\n\td.terminal = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Normalization helper\n// ---------------------------------------------------------------------------\n\n/**\n * Accept either a single `Message` tuple or a `Messages` array and return\n * a `Messages` array. The discriminator is the type of the first element:\n * a `Message` has a symbol at index 0, while a `Messages` array has a\n * nested array at index 0. This lets `node.down(...)` and `actions.down(...)`\n * take either shape without a wrapper allocation on the common single-msg\n * path.\n */\nfunction normalizeMessages(input: Message | Messages): Messages {\n\tif (input.length === 0) return input as Messages;\n\treturn typeof (input as Message)[0] === \"symbol\" ? [input as Message] : (input as Messages);\n}\n\n// ---------------------------------------------------------------------------\n// Default handlers\n// ---------------------------------------------------------------------------\n\n/**\n * Default {@link OnMessageHandler}. For `\"down-in\"` messages (from a dep),\n * routes to `NodeImpl._onDepMessage`. For `\"up-in\"` messages (from a sink),\n * the up-path is wired directly via `Node.up()` and never passes through\n * onMessage — this hook is reserved for future P5 symmetry.\n */\nconst defaultOnMessage: OnMessageHandler = (\n\tnode: NodeCtx,\n\tmsg: Message,\n\tctx: MessageContext,\n\t_actions: NodeActions,\n): \"consume\" | undefined => {\n\tif (ctx.direction === \"down-in\") {\n\t\t(node as NodeImpl)._onDepMessage(ctx.depIndex, msg);\n\t}\n\t// up-in is currently unused; default is to do nothing.\n\treturn undefined;\n};\n\n/**\n * Default {@link OnSubscribeHandler}. Delivers the subscribe handshake —\n * `[[START]]` for a sentinel cache, or `[[START], [DATA, cached]]` when a\n * value exists. Terminal nodes skip entirely so absence of START tells the\n * sink the stream is over (spec §2.2). Delivered through `downWithBatch` so\n * `subscribe()` inside `batch()` still defers the paired DATA correctly.\n */\nconst defaultOnSubscribe: OnSubscribeHandler = (\n\tnode: NodeCtx,\n\tsink: NodeSink,\n\t_ctx: SubscribeContext,\n\t_actions: NodeActions,\n): (() => void) | undefined => {\n\tconst impl = node as NodeImpl;\n\tif (impl._status === \"completed\" || impl._status === \"errored\") return;\n\tconst cached = impl._cached;\n\tconst initial: Message[] =\n\t\tcached === undefined ? [START_MSG] : [START_MSG, [DATA, cached] as Message];\n\t// When the node is mid-wave (`\"dirty\"`), append a DIRTY so the late\n\t// joiner participates in the in-flight wave. Without this, the next\n\t// DATA/RESOLVED the sink receives lacks the preceding DIRTY required\n\t// by spec §1.3.1 — the emit-side DIRTY auto-prefix is suppressed when\n\t// `_status` is already `\"dirty\"`.\n\tif (impl._status === \"dirty\") initial.push(DIRTY_MSG);\n\tdownWithBatch(sink, initial, impl._config.tierOf);\n};\n\n// ---------------------------------------------------------------------------\n// defaultConfig + configure\n// ---------------------------------------------------------------------------\n\n/**\n * Default {@link GraphReFlyConfig} instance. Every `NodeImpl` constructed\n * without an explicit `opts.config` binds to this instance and freezes it\n * on first hook access.\n */\nexport const defaultConfig = new GraphReFlyConfig({\n\tonMessage: defaultOnMessage,\n\tonSubscribe: defaultOnSubscribe,\n});\nregisterBuiltins(defaultConfig);\nregisterBuiltinCodecs(defaultConfig);\n\n/**\n * Apply configuration to {@link defaultConfig}. Must be called before the\n * first node is created — otherwise throws. Custom message types, hook\n * overrides, etc. go through here at app startup.\n *\n * ```ts\n * configure((cfg) => {\n * cfg.registerMessageType(MY_TYPE, { tier: 3 });\n * cfg.onMessage = (node, msg, ctx, actions) => { ... };\n * });\n * ```\n */\nexport function configure(fn: (cfg: GraphReFlyConfig) => void): void {\n\tif (defaultConfig._isFrozen()) {\n\t\tthrow new Error(\n\t\t\t\"configure() called after a node was created — the default \" +\n\t\t\t\t\"GraphReFlyConfig is frozen. Call configure(...) at application \" +\n\t\t\t\t\"startup, before any node factories run.\",\n\t\t);\n\t}\n\tfn(defaultConfig);\n}\n\n// Re-export the class for advanced callers that want an isolated instance.\nexport { GraphReFlyConfig };\n\n// ---------------------------------------------------------------------------\n// NodeImpl\n// ---------------------------------------------------------------------------\n\n/**\n * Single-class node implementation. Covers state, producer, derived, effect,\n * and passthrough shapes. See `sugar.ts` for ergonomic factories and\n * `dynamicNode()` (sugar-level wrapper around plain `NodeImpl`).\n */\nexport class NodeImpl<T = unknown> implements Node<T> {\n\t// --- Identity ---\n\treadonly _optsName: string | undefined;\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\t/**\n\t * Cached `Object.keys(meta).length > 0` check. `meta` is frozen at\n\t * construction so this boolean never flips. Used by `_emit` to skip\n\t * the meta TEARDOWN fan-out block allocation on the common \"no meta\"\n\t * hot path.\n\t */\n\treadonly _hasMeta: boolean;\n\n\t// --- Config ---\n\treadonly _config: GraphReFlyConfig;\n\n\t// --- Topology ---\n\t/** Mutable for autoTrackNode / Graph.connect() post-construction dep addition. */\n\t_deps: DepRecord[];\n\t_sinks: NodeSink | Set<NodeSink> | null = null;\n\t_sinkCount = 0;\n\n\t// --- State ---\n\t_cached: T | undefined;\n\t_status: NodeStatus;\n\t_cleanup: NodeFnCleanup | undefined;\n\t_store: Record<string, unknown> = {};\n\t_waveHasNewData = false;\n\t_hasNewTerminal = false;\n\t_hasCalledFnOnce = false;\n\t_paused = false;\n\t_pendingWave = false;\n\t_isExecutingFn = false;\n\t_pendingRerun = false;\n\t_rerunDepth = 0;\n\n\t// --- Settlement counter (A3) ---\n\t/**\n\t * Count of deps currently in `dirty === true`. `_maybeRunFnOnSettlement`\n\t * treats `0` as \"wave settled\" — O(1) check for full dep settlement.\n\t */\n\t_dirtyDepCount = 0;\n\n\t// --- PAUSE/RESUME lock tracking (C0) ---\n\t/**\n\t * Set of active pause locks held against this node. Every `[PAUSE, lockId]`\n\t * adds its `lockId` to the set; every `[RESUME, lockId]` removes it.\n\t * `_paused` is a derived quantity: `_pauseLocks.size > 0`. Multi-pauser\n\t * correctness — one controller releasing its lock does NOT resume the\n\t * node while another controller still holds its lock.\n\t */\n\t_pauseLocks: Set<unknown> | null = null;\n\t/**\n\t * Buffered DATA messages held while paused. Only populated when\n\t * `_pausable === \"resumeAll\"` (bufferAll mode). On final lock release\n\t * the buffer is replayed through the node's outgoing pipeline in the\n\t * order received. Non-bufferAll pause mode drops DATA on the floor\n\t * (upstream is expected to honor PAUSE by suppressing production).\n\t */\n\t_pauseBuffer: Message[] | null = null;\n\n\t// --- Options (frozen at construction) ---\n\treadonly _fn: NodeFn | undefined;\n\treadonly _equals: (a: T, b: T) => boolean;\n\treadonly _resubscribable: boolean;\n\treadonly _resetOnTeardown: boolean;\n\treadonly _autoComplete: boolean;\n\treadonly _autoError: boolean;\n\treadonly _pausable: boolean | \"resumeAll\";\n\treadonly _guard: NodeGuard | undefined;\n\t_hashFn: HashFn;\n\t_versioning: NodeVersionInfo | undefined;\n\t/**\n\t * Explicit versioning level, tracked separately from `_versioning` so\n\t * monotonicity checks and future v2/v3 extensions don't rely on the\n\t * fragile `\"cid\" in _versioning` shape discriminator. `undefined` means\n\t * the node has no versioning attached; `0` / `1` / future levels name\n\t * the tier. Mutated in lockstep with `_versioning` by the constructor\n\t * and by `_applyVersioning`.\n\t */\n\t_versioningLevel: VersioningLevel | undefined;\n\n\t// --- ABAC ---\n\t_lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\n\t/**\n\t * @internal Per-node inspector hooks for `Graph.observe(path,\n\t * { causal, derived })`. Fires in `_onDepMessage` and `_execFn`.\n\t * Attached via `_setInspectorHook` (returns a disposer). Multiple\n\t * observers can attach simultaneously — all registered hooks fire for\n\t * every event.\n\t */\n\t_inspectorHooks: Set<NodeInspectorHook> | undefined;\n\n\t// --- Actions (built once in the constructor) ---\n\treadonly _actions: NodeActions;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn | undefined, opts: NodeOptions<T>) {\n\t\t// Bind to config FIRST so meta nodes inherit it. Touching a hook\n\t\t// getter below freezes the config on first node creation.\n\t\tthis._config = opts.config ?? defaultConfig;\n\t\tvoid this._config.onMessage;\n\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = (opts.equals ?? (Object.is as (a: T, b: T) => boolean)) as (\n\t\t\ta: T,\n\t\t\tb: T,\n\t\t) => boolean;\n\t\tthis._resubscribable = opts.resubscribable ?? false;\n\t\tthis._resetOnTeardown = opts.resetOnTeardown ?? false;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._autoError = opts.errorWhenDepsError ?? true;\n\t\tthis._pausable = opts.pausable ?? true;\n\t\tthis._guard = opts.guard;\n\t\tthis._fn = fn;\n\n\t\t// `undefined` is the sentinel (\"no cached value\") so `initial: undefined`\n\t\t// is treated as absent. `null` is a valid DATA value and sets the cache.\n\t\tthis._cached = opts.initial !== undefined ? (opts.initial as T) : undefined;\n\t\t// State-with-initial starts \"settled\"; everything else starts \"sentinel\".\n\t\tthis._status =\n\t\t\tdeps.length === 0 && fn == null && this._cached !== undefined ? \"settled\" : \"sentinel\";\n\n\t\t// Versioning\n\t\t// Hash resolution: per-node `opts.versioningHash` wins; then the\n\t\t// bound config's `defaultHashFn`; then the vendored sync SHA-256.\n\t\t// Hot-path workloads that want a faster hash (xxHash, FNV-1a) can\n\t\t// set it once at app init via `configure(cfg => { cfg.defaultHashFn = ... })`.\n\t\tthis._hashFn = opts.versioningHash ?? this._config.defaultHashFn ?? defaultHash;\n\t\t// Versioning level resolution: per-node `opts.versioning` wins; if\n\t\t// absent, fall back to the bound config's `defaultVersioning`. `null`\n\t\t// stays unversioned. Explicit levels (0, 1, …) attach the versioning\n\t\t// info at construction so the next DATA emit advances it.\n\t\tconst versioningLevel: VersioningLevel | undefined =\n\t\t\topts.versioning ?? this._config.defaultVersioning;\n\t\tthis._versioningLevel = versioningLevel;\n\t\tthis._versioning =\n\t\t\tversioningLevel != null\n\t\t\t\t? createVersioning(versioningLevel, this._cached === undefined ? undefined : this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\t// Per-dep records: one DepRecord per declared dep.\n\t\tthis._deps = deps.map(createDepRecord);\n\n\t\t// Meta companions (simple state children; inherit config + guard).\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tconst metaOpts: NodeOptions<unknown> = {\n\t\t\t\tinitial: v,\n\t\t\t\tname: `${opts.name ?? \"node\"}:meta:${k}`,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\tconfig: this._config,\n\t\t\t};\n\t\t\tif (opts.guard != null) metaOpts.guard = opts.guard;\n\t\t\tmeta[k] = new NodeImpl<unknown>([], undefined, metaOpts);\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\t\tthis._hasMeta = Object.keys(meta).length > 0;\n\n\t\t// Actions: built once, closure over `this`. Every call goes through\n\t\t// `_emit` which owns the full dispatch invariant — tier sort,\n\t\t// synthetic DIRTY prefix, equals substitution, and phase dispatch.\n\t\t// One call = one wave. Multiple calls produce multiple waves.\n\t\t// No accumulation, no user-facing bundle builder.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\temit(value: unknown): void {\n\t\t\t\tself._emit([[DATA, value] as Message]);\n\t\t\t},\n\t\t\tdown(messageOrMessages: Message | Messages): void {\n\t\t\t\tself._emit(normalizeMessages(messageOrMessages));\n\t\t\t},\n\t\t\tup(messageOrMessages: Message | Messages): void {\n\t\t\t\tself._emitUp(normalizeMessages(messageOrMessages));\n\t\t\t},\n\t\t};\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\t// --- Derived state ---\n\n\tprivate get _isTerminal(): boolean {\n\t\treturn this._status === \"completed\" || this._status === \"errored\";\n\t}\n\n\t// --- Public getters ---\n\n\tget name(): string | undefined {\n\t\treturn this._optsName;\n\t}\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget cache(): T | undefined | null {\n\t\treturn this._cached === undefined ? undefined : (this._cached as T);\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\tget v(): Readonly<NodeVersionInfo> | undefined {\n\t\treturn this._versioning;\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\t/**\n\t * @internal Retroactively attach (or upgrade) versioning state on this\n\t * node. Intended for `Graph.setVersioning(level)` bulk application and\n\t * for rare cases where a specific node needs to be bumped to a higher\n\t * level (e.g., `v0 → v1`) after construction.\n\t *\n\t * **Safety:** the mutation is rejected mid-wave. Specifically,\n\t * throws if the node is currently executing its fn (`_isExecutingFn`).\n\t * Callers at quiescent points — before the first sink subscribes, or\n\t * after all sinks unsubscribe, or between external `down()` / `emit()`\n\t * invocations — are safe. The re-entrance window that motivated §10.6.4\n\t * removal was the \"transition `_versioning` from `undefined` to a fresh\n\t * object mid-`_updateState`\" case; that path is now guarded.\n\t *\n\t * **Monotonicity:** levels can only go up. Downgrade (e.g., `v1 → v0`)\n\t * is a no-op — once a node carries higher-level metadata, dropping it\n\t * mid-graph would tear the linked-history invariant for v1 and above.\n\t *\n\t * **Linked-history boundary (D1, 2026-04-13):** upgrading v0 → v1\n\t * produces a **fresh history root**. The new v1 state has `cid =\n\t * hash(currentCachedValue)` and `prev = null`, not a synthetic `prev`\n\t * anchored to any previous v0 value. The v0 monotonic `version` counter\n\t * is preserved across the upgrade, but the linked-cid chain (spec §7)\n\t * starts fresh at the upgrade point. Downstream audit tools that walk\n\t * `v.cid.prev` backwards through time will see a `null` boundary at\n\t * the upgrade — **this is intentional**: v0 had no cid to link to, and\n\t * fabricating one would lie about the hash. Callers that require an\n\t * unbroken cid chain from birth must attach versioning at construction\n\t * via `opts.versioning` or `config.defaultVersioning`, not retroactively.\n\t *\n\t * @param level - New minimum versioning level.\n\t * @param opts - Optional id / hash overrides; applied only if the\n\t * node currently has no versioning state.\n\t */\n\t_applyVersioning(level: VersioningLevel, opts?: { id?: string; hash?: HashFn }): void {\n\t\tif (this._isExecutingFn) {\n\t\t\tthrow new Error(\n\t\t\t\t`Node \"${this.name}\": _applyVersioning cannot run mid-fn — ` +\n\t\t\t\t\t\"call it outside of `_execFn` (typically at graph setup time \" +\n\t\t\t\t\t\"before the first subscribe).\",\n\t\t\t);\n\t\t}\n\t\tconst currentLevel = this._versioningLevel;\n\t\tif (currentLevel != null && level <= currentLevel) {\n\t\t\t// Downgrade or no-op. Monotonic: higher levels only.\n\t\t\treturn;\n\t\t}\n\t\tconst hash = opts?.hash ?? this._hashFn;\n\t\tif (hash !== this._hashFn) this._hashFn = hash;\n\t\tconst initialValue = this._cached === undefined ? undefined : this._cached;\n\t\t// Preserve the existing id + version counter across upgrades so\n\t\t// downstream consumers watching `v.id` don't see an identity jump.\n\t\tconst current = this._versioning;\n\t\tconst preservedId = current?.id ?? opts?.id;\n\t\tconst preservedVersion = current?.version ?? 0;\n\t\tconst fresh = createVersioning(level, initialValue, {\n\t\t\tid: preservedId,\n\t\t\thash,\n\t\t});\n\t\tfresh.version = preservedVersion;\n\t\tthis._versioning = fresh;\n\t\tthis._versioningLevel = level;\n\t}\n\n\t/**\n\t * @internal Attach an inspector hook. Returns a disposer that removes\n\t * the hook. Used by `Graph.observe(path, { causal, derived })` to build\n\t * causal traces. Multiple hooks may be attached concurrently — all fire\n\t * for every event in registration order. Passing `undefined` is a no-op\n\t * and returns a no-op disposer.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tif (hook == null) return () => {};\n\t\tif (this._inspectorHooks == null) this._inspectorHooks = new Set();\n\t\tthis._inspectorHooks.add(hook);\n\t\treturn () => {\n\t\t\tthis._inspectorHooks?.delete(hook);\n\t\t\tif (this._inspectorHooks?.size === 0) this._inspectorHooks = undefined;\n\t\t};\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\t// --- Guard helper ---\n\n\tprivate _checkGuard(options?: NodeTransportOptions): void {\n\t\tif (options?.internal || this._guard == null) return;\n\t\tconst actor = normalizeActor(options?.actor);\n\t\tconst action: GuardAction = options?.delivery === \"signal\" ? \"signal\" : \"write\";\n\t\tif (!this._guard(actor, action)) {\n\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t}\n\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t}\n\n\t// --- Public transport ---\n\n\tdown(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void {\n\t\tconst messages = normalizeMessages(messageOrMessages);\n\t\tif (messages.length === 0) return;\n\t\tthis._checkGuard(options);\n\t\tthis._emit(messages);\n\t}\n\n\temit(value: T | undefined | null, options?: NodeTransportOptions): void {\n\t\tthis._checkGuard(options);\n\t\tthis._emit([[DATA, value] as Message]);\n\t}\n\n\tup(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void {\n\t\tif (this._deps.length === 0) return;\n\t\tconst messages = normalizeMessages(messageOrMessages);\n\t\tif (messages.length === 0) return;\n\t\tthis._checkGuard(options);\n\t\tconst forwardOpts: NodeTransportOptions = options ?? { internal: true };\n\t\t// Validate tier constraint before fanning out (B1.4 option a).\n\t\tthis._validateUpTiers(messages);\n\t\tfor (const d of this._deps) {\n\t\t\td.node.up?.(messages, forwardOpts);\n\t\t}\n\t}\n\n\t/**\n\t * @internal Internal up-path used by `actions.up(...)` from inside fn.\n\t * Same tier validation as public `up`, but bypasses the guard check\n\t * since the fn context is already inside an authorized operation.\n\t */\n\tprivate _emitUp(messages: Messages): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (messages.length === 0) return;\n\t\tthis._validateUpTiers(messages);\n\t\tfor (const d of this._deps) {\n\t\t\td.node.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\t/**\n\t * @internal Enforce spec §1.2 — up-direction messages are restricted to\n\t * tier 0–2 and tier 5 (START, DIRTY, INVALIDATE, PAUSE, RESUME,\n\t * TEARDOWN). Tier 3 (DATA/RESOLVED) and tier 4 (COMPLETE/ERROR) are\n\t * downstream-only. Emitting tier-3/4 via `up` would bypass equals\n\t * substitution and cache advance entirely and is a protocol bug.\n\t */\n\tprivate _validateUpTiers(messages: Messages): void {\n\t\tconst tierOf = this._config.tierOf;\n\t\tfor (const m of messages) {\n\t\t\tconst tier = tierOf(m[0]);\n\t\t\tif (tier === 3 || tier === 4) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Node \"${this.name}\": tier-${tier} messages cannot flow up — ` +\n\t\t\t\t\t\t\"DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \" +\n\t\t\t\t\t\t\"`down(...)` for value delivery; `up(...)` is for control \" +\n\t\t\t\t\t\t\"signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tsubscribe(sink: NodeSink, actor?: Actor): () => void {\n\t\tif (actor != null && this._guard != null) {\n\t\t\tconst a = normalizeActor(actor);\n\t\t\tif (!this._guard(a, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor: a, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\t// Resubscribable terminal reset.\n\t\tconst wasTerminal = this._isTerminal;\n\t\tconst afterTerminalReset = wasTerminal && this._resubscribable;\n\t\tif (afterTerminalReset) {\n\t\t\tthis._cached = undefined;\n\t\t\tthis._status = \"sentinel\";\n\t\t\tthis._store = {};\n\t\t\tthis._hasCalledFnOnce = false;\n\t\t\tthis._waveHasNewData = false;\n\t\t\tthis._hasNewTerminal = false;\n\t\t\tthis._paused = false;\n\t\t\tthis._pendingWave = false;\n\t\t\tthis._pendingRerun = false;\n\t\t\tthis._isExecutingFn = false;\n\t\t\tthis._rerunDepth = 0;\n\t\t\tthis._dirtyDepCount = 0;\n\t\t\t// C0: clear pause state so a new subscriber after terminal-reset\n\t\t\t// starts from a clean pause lockset — otherwise a lockId from\n\t\t\t// the previous lifecycle would leave the node stuck paused and\n\t\t\t// swallow every emit.\n\t\t\tthis._pauseLocks = null;\n\t\t\tthis._pauseBuffer = null;\n\t\t\tfor (const d of this._deps) resetDepRecord(d);\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\n\t\t// Subscribe ceremony via singleton.\n\t\t// Rollback on throw: undo the sinkCount bump — sink is not yet registered,\n\t\t// no _activate() has run, nothing else to clean up.\n\t\tlet subCleanup: (() => void) | undefined;\n\t\ttry {\n\t\t\tsubCleanup = this._config.onSubscribe(\n\t\t\t\tthis as unknown as NodeCtx,\n\t\t\t\tsink,\n\t\t\t\t{ sinkCount: this._sinkCount, afterTerminalReset },\n\t\t\t\tthis._actions,\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tthis._sinkCount -= 1;\n\t\t\tthrow err;\n\t\t}\n\n\t\t// Register sink AFTER START delivery (spec §2.2).\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\t// First-subscriber activation.\n\t\t// Rollback on throw: undo sink registration, sinkCount bump, and subCleanup.\n\t\t// _activate() rolls back its own partial dep subscriptions before re-throwing.\n\t\tconst isTerminalNow = this._isTerminal;\n\t\tif (this._sinkCount === 1 && !isTerminalNow) {\n\t\t\ttry {\n\t\t\t\tthis._activate();\n\t\t\t} catch (err) {\n\t\t\t\tthis._sinkCount -= 1;\n\t\t\t\tthis._removeSink(sink);\n\t\t\t\t// Restore status: onSubscribe emitted START which set _status to\n\t\t\t\t// \"pending\". With zero sinks the node is back to its pre-subscribe\n\t\t\t\t// state; reset so node.status reflects no active subscription.\n\t\t\t\tif (this._sinkCount === 0) this._status = \"sentinel\";\n\t\t\t\tif (typeof subCleanup === \"function\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsubCleanup();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* best-effort: subCleanup errors are secondary */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\t// Reflect \"activated but no value yet\" as pending.\n\t\tif (this._status === \"sentinel\" && this._cached === undefined) {\n\t\t\tthis._status = \"pending\";\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn (): void => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tthis._removeSink(sink);\n\t\t\tif (typeof subCleanup === \"function\") subCleanup();\n\t\t\tif (this._sinks == null) this._deactivate();\n\t\t};\n\t}\n\n\tprivate _removeSink(sink: NodeSink): void {\n\t\tif (this._sinks === sink) {\n\t\t\tthis._sinks = null;\n\t\t} else if (this._sinks != null && typeof this._sinks !== \"function\") {\n\t\t\tthis._sinks.delete(sink);\n\t\t\tif (this._sinks.size === 1) {\n\t\t\t\tconst [only] = this._sinks;\n\t\t\t\tthis._sinks = only;\n\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\tthis._sinks = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Lifecycle ---\n\n\t/**\n\t * @internal First-sink activation. For a producer (no deps + fn),\n\t * invokes fn once. For a compute node (has deps), subscribes to every\n\t * dep with the pre-set-dirty trick so the first-run gate waits for\n\t * every dep to settle at least once.\n\t */\n\t_activate(): void {\n\t\tif (this._deps.length === 0) {\n\t\t\tif (this._fn) this._execFn();\n\t\t\treturn;\n\t\t}\n\t\t// Pre-set every dep as sentinel BEFORE subscribing. If the first dep\n\t\t// delivers DATA synchronously during its subscribe callback, the\n\t\t// sentinel gate holds fn until all deps have contributed at least one\n\t\t// value. _dirtyDepCount starts at 0 — actual DIRTY messages from deps\n\t\t// drive it; pre-dirtying all deps would cause any dep that only delivers\n\t\t// [[START]] (no DATA) to appear permanently \"mid-wave\", which blocks\n\t\t// terminal propagation from other deps incorrectly.\n\t\tthis._dirtyDepCount = 0;\n\t\t// Capture the initial length BEFORE subscribing. `_addDep` can fire\n\t\t// synchronously during a dep's subscribe callback (e.g., via\n\t\t// `autoTrackNode` discovery in `_execFn`) and push new DepRecords.\n\t\t// Iterating `this._deps.length` live would mean this loop also\n\t\t// subscribes the new dep that `_addDep` already subscribed — a\n\t\t// double-subscribe bug. Snapshot the length instead; `_addDep`\n\t\t// owns the subscribe + counter bump for any dep it adds.\n\t\tconst initialLen = this._deps.length;\n\t\t// subscribedCount tracks how many deps were successfully subscribed.\n\t\t// On failure, only those deps need to be rolled back.\n\t\tlet subscribedCount = 0;\n\t\ttry {\n\t\t\tfor (let i = 0; i < initialLen; i++) {\n\t\t\t\tconst depIdx = i;\n\t\t\t\tconst dep = this._deps[i];\n\t\t\t\t// Pre-set to noopUnsub so the liveness check inside the callback\n\t\t\t\t// passes during synchronous push-on-subscribe (dep.unsub is non-null),\n\t\t\t\t// while still blocking stale drainPhase2 closures that fire after\n\t\t\t\t// _deactivate sets dep.unsub = null.\n\t\t\t\tdep.unsub = noopUnsub;\n\t\t\t\tdep.unsub = dep.node.subscribe((msgs) => {\n\t\t\t\t\t// Liveness check: dep.unsub === null means this subscription was\n\t\t\t\t\t// cancelled by _deactivate. Drop deliveries from stale drainPhase2\n\t\t\t\t\t// closures that outlived the subscription.\n\t\t\t\t\tif (dep.unsub === null) return;\n\t\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\t\tthis._config.onMessage(\n\t\t\t\t\t\t\tthis as unknown as NodeCtx,\n\t\t\t\t\t\t\tm,\n\t\t\t\t\t\t\t{ direction: \"down-in\", depIndex: depIdx },\n\t\t\t\t\t\t\tthis._actions,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tsubscribedCount++;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// Dep at index `subscribedCount` failed — its dep.unsub is still noopUnsub.\n\t\t\t// Mark it null so the liveness check treats any queued closures as stale.\n\t\t\tthis._deps[subscribedCount].unsub = null;\n\t\t\t// Unsubscribe all deps that DID subscribe successfully (0..subscribedCount-1).\n\t\t\tfor (let j = 0; j < subscribedCount; j++) {\n\t\t\t\tconst d = this._deps[j];\n\t\t\t\tif (d.unsub != null) {\n\t\t\t\t\tconst u = d.unsub;\n\t\t\t\t\td.unsub = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tu();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* best-effort: dep unsub errors are secondary */\n\t\t\t\t\t}\n\t\t\t\t\tresetDepRecord(d);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._dirtyDepCount = 0;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/**\n\t * @internal Append a dep post-construction. Used by `autoTrackNode`\n\t * (runtime dep discovery) and `Graph.connect()` (post-construction\n\t * wiring). Subscribes immediately — if DATA arrives synchronously\n\t * during subscribe and fn is currently executing, the re-run is\n\t * deferred via `_pendingRerun` flag (see `_execFn` guard).\n\t *\n\t * **Dedup:** idempotent on duplicate `depNode` — if `depNode` is\n\t * already in `_deps`, returns the existing index without mutating\n\t * state. Callers can safely invoke `_addDep` without their own\n\t * \"already added\" check. `autoTrackNode` still keeps a `depIndexMap`\n\t * as a fast-path lookup for known deps (returning cached `data[idx]`\n\t * without calling `_addDep` at all); this internal dedup is the\n\t * backstop for any caller that doesn't track its own dep set.\n\t *\n\t * @returns The index of the new dep in `_deps`, or the existing index\n\t * if the dep was already present.\n\t */\n\t_addDep(depNode: Node): number {\n\t\t// Dedup: idempotent on repeated adds of the same dep. Matches\n\t\t// reference equality — the DepRecord is keyed by `node` identity,\n\t\t// so a caller with a fresh `depNode` that observes as equal but\n\t\t// is a distinct object is treated as a new dep.\n\t\tfor (let i = 0; i < this._deps.length; i++) {\n\t\t\tif (this._deps[i].node === depNode) return i;\n\t\t}\n\t\tconst depIdx = this._deps.length;\n\t\tconst record = createDepRecord(depNode);\n\t\tthis._deps.push(record);\n\n\t\t// If the node is inactive (no subscribers yet), defer subscribe to\n\t\t// _activate(). Subscribing here would create a duplicate subscription\n\t\t// because _activate() unconditionally subscribes to all _deps entries.\n\t\t// _activate() resets _dirtyDepCount to 0 before subscribing, so pre-\n\t\t// dirtying is wasted work and causes counter underflow on the first DATA.\n\t\tif (this._sinks == null) return depIdx;\n\n\t\trecord.dirty = true;\n\t\t// New dep starts dirty — bump the A3 counter to match the pre-set flag.\n\t\t// Skipping the helper here because the record isn't in the array yet when\n\t\t// the helper would early-return on `dep.dirty === true`.\n\t\tthis._dirtyDepCount++;\n\t\t// Topology change → downstream sees a new wave. Skip when already\n\t\t// dirty (we're inside an in-flight wave and have already emitted).\n\t\t// `_depDirtied` can't do this for us because `record.dirty` was\n\t\t// pre-set above, which short-circuits its DIRTY-emit path.\n\t\tif (this._status !== \"dirty\") this._emit(DIRTY_ONLY_BATCH);\n\t\trecord.unsub = noopUnsub;\n\t\ttry {\n\t\t\trecord.unsub = depNode.subscribe((msgs) => {\n\t\t\t\tif (record.unsub === null) return;\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tthis._config.onMessage(\n\t\t\t\t\t\tthis as unknown as NodeCtx,\n\t\t\t\t\t\tm,\n\t\t\t\t\t\t{ direction: \"down-in\", depIndex: depIdx },\n\t\t\t\t\t\tthis._actions,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (err) {\n\t\t\t// Rollback: remove the dep record we just pushed and undo the dirty\n\t\t\t// counter. record.unsub stays null (already cleared below) so any\n\t\t\t// drainPhase2 closures queued by subscribe before it threw are\n\t\t\t// treated as stale and dropped by the liveness check.\n\t\t\trecord.unsub = null;\n\t\t\tthis._deps.pop();\n\t\t\tthis._dirtyDepCount--;\n\t\t\t// Propagate: _execFn's catch block will emit ERROR, which settles\n\t\t\t// downstream nodes that received the DIRTY we emitted above.\n\t\t\tthrow err;\n\t\t}\n\t\treturn depIdx;\n\t}\n\n\t/**\n\t * @internal Unsubscribes from deps, fires fn cleanup (both shapes),\n\t * clears wave/store state, and (for compute nodes) drops `_cached` per\n\t * the ROM/RAM rule. Idempotent: second call is a no-op.\n\t *\n\t * @param skipStatusUpdate — When `true`, the caller takes responsibility\n\t * for setting `_status` after deactivation (e.g. TEARDOWN always sets\n\t * `\"sentinel\"` unconditionally). When `false` (default), deactivation\n\t * applies the ROM rule: compute nodes → `\"sentinel\"`, state nodes\n\t * preserve their current status.\n\t */\n\t_deactivate(skipStatusUpdate = false): void {\n\t\t// Fn cleanup — both () => void and { deactivation } forms fire here.\n\t\t// Note on cleanup-throw ERRORs: when deactivation runs as part of\n\t\t// last-sink-unsubscribe, `_sinks` is already `null` by the time this\n\t\t// method is reached, so any ERROR emitted here lands on\n\t\t// `_deliverToSinks`'s null-guard and is dropped by design. Cleanup\n\t\t// errors during teardown are best-effort — callers that need to\n\t\t// observe them should install a host-level error channel via\n\t\t// `configure()`.\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tif (typeof cleanup === \"function\") {\n\t\t\ttry {\n\t\t\t\tcleanup();\n\t\t\t} catch (err) {\n\t\t\t\tthis._emit([[ERROR, this._wrapFnError(\"cleanup threw\", err)]]);\n\t\t\t}\n\t\t} else if (\n\t\t\tcleanup != null &&\n\t\t\ttypeof (cleanup as { deactivation?: unknown }).deactivation === \"function\"\n\t\t) {\n\t\t\ttry {\n\t\t\t\t(cleanup as { deactivation: () => void }).deactivation();\n\t\t\t} catch (err) {\n\t\t\t\tthis._emit([[ERROR, this._wrapFnError(\"cleanup.deactivation threw\", err)]]);\n\t\t\t}\n\t\t}\n\n\t\t// Disconnect from deps.\n\t\tfor (const d of this._deps) {\n\t\t\tif (d.unsub != null) {\n\t\t\t\tconst u = d.unsub;\n\t\t\t\td.unsub = null;\n\t\t\t\ttry {\n\t\t\t\t\tu();\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort teardown of upstream subscription */\n\t\t\t\t}\n\t\t\t}\n\t\t\tresetDepRecord(d);\n\t\t}\n\n\t\t// Clear wave + store state.\n\t\tthis._waveHasNewData = false;\n\t\tthis._hasNewTerminal = false;\n\t\tthis._hasCalledFnOnce = false;\n\t\tthis._paused = false;\n\t\tthis._pendingWave = false;\n\t\tthis._pendingRerun = false;\n\t\tthis._rerunDepth = 0;\n\t\tthis._store = {};\n\t\t// A3 counter reset with DepRecord bulk-reset.\n\t\tthis._dirtyDepCount = 0;\n\t\t// C0 pause state: TEARDOWN is a hard reset. Buffered tier-3/4\n\t\t// messages from a paused `resumeAll` node are DISCARDED rather than\n\t\t// drained, matching \"teardown wipes in-flight state\" semantics.\n\t\t// Clearing both structures also prevents a memory leak on\n\t\t// non-resubscribable teardown, and guarantees a resubscribable\n\t\t// re-activation starts from `_paused === false` with no stale\n\t\t// lockset carried over from the previous lifecycle.\n\t\tthis._pauseLocks = null;\n\t\tthis._pauseBuffer = null;\n\n\t\t// ROM/RAM: compute nodes clear cache; pure state nodes preserve it.\n\t\tif (this._fn != null) {\n\t\t\tthis._cached = undefined;\n\t\t}\n\n\t\tif (!skipStatusUpdate) {\n\t\t\t// Compute nodes → \"sentinel\" (cache cleared, no value).\n\t\t\t// - Non-terminal: always reset.\n\t\t\t// - Terminal + resubscribable: reset (resubscribable means\n\t\t\t// \"can be re-activated after terminal\" — the terminal state\n\t\t\t// doesn't persist across subscription cycles).\n\t\t\t// - Terminal + non-resubscribable: preserve (stream is over).\n\t\t\t// State nodes preserve status (ROM rule, value is intrinsic).\n\t\t\tif (this._fn != null || this._deps.length > 0) {\n\t\t\t\tif (!this._isTerminal || this._resubscribable) {\n\t\t\t\t\tthis._status = \"sentinel\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Dep message dispatch (§3.5 singleton default) ---\n\n\t/**\n\t * @internal Default per-tier dispatch for incoming dep messages. Called\n\t * by `defaultOnMessage`. Updates the DepRecord, triggers wave\n\t * completion, and forwards passthrough traffic.\n\t */\n\t_onDepMessage(depIndex: number, msg: Message): void {\n\t\tconst dep = this._deps[depIndex];\n\t\tconst t = msg[0];\n\n\t\t// Fire inspector hooks before default dispatch. Common case: no hooks\n\t\t// (undefined slot). Multiple observers can attach simultaneously.\n\t\tif (this._inspectorHooks != null) {\n\t\t\tconst ev: NodeInspectorHookEvent = { kind: \"dep_message\", depIndex, message: msg };\n\t\t\tfor (const hook of this._inspectorHooks) hook(ev);\n\t\t}\n\n\t\t// Tier 0 (START) — informational, no state change.\n\t\tif (t === START) return;\n\n\t\t// Tier 1\n\t\tif (t === DIRTY) {\n\t\t\tthis._depDirtied(dep);\n\t\t\treturn;\n\t\t}\n\t\tif (t === INVALIDATE) {\n\t\t\tthis._depInvalidated(dep);\n\t\t\tthis._emit(INVALIDATE_ONLY_BATCH);\n\t\t\treturn;\n\t\t}\n\n\t\t// Tier 2 — PAUSE / RESUME flow downstream (spec §1.2). Lock bookkeeping\n\t\t// happens inside `_emit` so both `_onDepMessage` (PAUSE received from\n\t\t// a dep) and external `node.down([[PAUSE, lockId]])` (source\n\t\t// directly issuing PAUSE) hit the same path. Here we just forward —\n\t\t// `_emit` will consume the lock, update `_paused`, and broadcast.\n\t\tif (t === PAUSE || t === RESUME) {\n\t\t\tthis._emit([msg]);\n\t\t\treturn;\n\t\t}\n\n\t\t// Tier 5\n\t\tif (t === TEARDOWN) {\n\t\t\tthis._emit(TEARDOWN_ONLY_BATCH);\n\t\t\treturn;\n\t\t}\n\n\t\t// Tier 3 / 4 — centralized transitions keep the settlement counters\n\t\t// (`_dirtyDepCount`, `_sentinelDepCount`) in sync with the flags on\n\t\t// every DepRecord. A3 optimization: the two counters let\n\t\t// `_maybeRunFnOnSettlement` check wave completion in O(1) instead\n\t\t// of two `every(...)` scans.\n\t\tif (t === DATA) {\n\t\t\tthis._depSettledAsData(dep, msg[1]);\n\t\t} else if (t === RESOLVED) {\n\t\t\tthis._depSettledAsResolved(dep);\n\t\t} else if (t === COMPLETE) {\n\t\t\tthis._depSettledAsTerminal(dep, true);\n\t\t} else if (t === ERROR) {\n\t\t\tthis._depSettledAsTerminal(dep, msg[1]);\n\t\t} else {\n\t\t\t// Unknown type: forward as-is (spec §1.3.6 forward-compat).\n\t\t\tthis._emit([msg]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this._fn) {\n\t\t\t// Passthrough: forward DATA/RESOLVED 1:1 through the unified\n\t\t\t// emit pipeline. `_emit` owns tier sort + synthetic DIRTY\n\t\t\t// prefix + equals substitution uniformly — no manual framing.\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._emit([msg]);\n\t\t\t}\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\tthis._maybeAutoTerminalAfterWave();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tthis._maybeRunFnOnSettlement();\n\t}\n\n\t// --- Centralized dep-state transitions (A3 settlement counters) ---\n\t//\n\t// Every mutation to `DepRecord.dirty` / `DepRecord.prevData` /\n\t// `DepRecord.terminal` must go through one of these helpers so the\n\t// `_dirtyDepCount` and `_sentinelDepCount` counters stay in sync with\n\t// the per-record flags. `_maybeRunFnOnSettlement` reads the counters\n\t// and never re-scans the `_deps` array.\n\n\t/**\n\t * Called when a dep transitions `dirty: false → true` (either from an\n\t * incoming DIRTY, or pre-set during `_activate` / `_addDep` /\n\t * `_depInvalidated`). No-op if the dep is already dirty. Fires the\n\t * downstream DIRTY emit if we're the first to dirty this wave.\n\t */\n\tprivate _depDirtied(dep: DepRecord): void {\n\t\tif (dep.dirty) return;\n\t\tdep.dirty = true;\n\t\tdep.involvedThisWave = true;\n\t\tthis._dirtyDepCount++;\n\t\t// First dep to dirty this wave → propagate DIRTY to our own sinks.\n\t\tif (this._status !== \"dirty\") {\n\t\t\tthis._emit(DIRTY_ONLY_BATCH);\n\t\t}\n\t}\n\n\t/**\n\t * Called when a dep delivers new DATA: clears dirty, stores the payload,\n\t * marks wave-has-data, and — if this is the dep's first DATA — clears\n\t * its sentinel slot so the first-run gate can open.\n\t */\n\tprivate _depSettledAsData(dep: DepRecord, value: unknown): void {\n\t\tif (dep.dirty) {\n\t\t\tdep.dirty = false;\n\t\t\tthis._dirtyDepCount--;\n\t\t}\n\t\tdep.involvedThisWave = true;\n\t\tdep.dataBatch.push(value);\n\t\tthis._waveHasNewData = true;\n\t}\n\n\t/**\n\t * Called when a dep emits RESOLVED (wave settled, value unchanged).\n\t * Clears dirty; does NOT touch `prevData` / `terminal` / sentinel\n\t * count — sentinel only exits on first DATA or terminal, not RESOLVED.\n\t */\n\tprivate _depSettledAsResolved(dep: DepRecord): void {\n\t\tif (dep.dirty) {\n\t\t\tdep.dirty = false;\n\t\t\tthis._dirtyDepCount--;\n\t\t}\n\t}\n\n\t/**\n\t * Called when a dep delivers COMPLETE (`terminal = true`) or ERROR\n\t * (`terminal = errorPayload`). Clears dirty, stores the terminal, and\n\t * — if the dep had never contributed a DATA yet — leaves sentinel\n\t * since the gate treats \"terminated without data\" as gate-open too.\n\t */\n\tprivate _depSettledAsTerminal(dep: DepRecord, terminal: unknown): void {\n\t\tif (dep.dirty) {\n\t\t\tdep.dirty = false;\n\t\t\tthis._dirtyDepCount--;\n\t\t}\n\t\tdep.terminal = terminal;\n\t\tdep.involvedThisWave = true;\n\t\tthis._hasNewTerminal = true;\n\t}\n\n\t/**\n\t * Called when a dep emits INVALIDATE: clears prevData, terminal, and\n\t * dataBatch. The dep is now back in the \"never delivered a real value\"\n\t * state — `prevData === undefined` so the sentinel check in fn will fire.\n\t */\n\tprivate _depInvalidated(dep: DepRecord): void {\n\t\tdep.prevData = undefined;\n\t\tdep.terminal = undefined;\n\t\tdep.dataBatch.length = 0;\n\t\tif (!dep.dirty) {\n\t\t\tdep.dirty = true;\n\t\t\tdep.involvedThisWave = true;\n\t\t\tthis._dirtyDepCount++;\n\t\t} else {\n\t\t\tdep.involvedThisWave = false; // cancel prior wave involvement\n\t\t}\n\t}\n\n\tprivate _maybeRunFnOnSettlement(): void {\n\t\tif (this._isTerminal && !this._resubscribable) return;\n\t\t// O(1) gate: `_dirtyDepCount === 0` means every dep has delivered its\n\t\t// settlement for this wave (DATA, RESOLVED, or terminal).\n\t\tif (this._dirtyDepCount > 0) return;\n\t\tif (this._paused) {\n\t\t\tthis._pendingWave = true;\n\t\t\treturn;\n\t\t}\n\t\t// Pre-fn skip: when no dep sent DATA this wave (all RESOLVED), skip\n\t\t// fn and emit RESOLVED directly. Transitive-skip optimization — leaf\n\t\t// fn is not re-run when a mid-chain node produces the same value.\n\t\tif (!this._waveHasNewData && !this._hasNewTerminal && this._hasCalledFnOnce) {\n\t\t\tthis._clearWaveFlags();\n\t\t\tthis._emit(RESOLVED_ONLY_BATCH);\n\t\t\tthis._maybeAutoTerminalAfterWave();\n\t\t\treturn;\n\t\t}\n\t\tif (this._fn) this._execFn();\n\t\tthis._maybeAutoTerminalAfterWave();\n\t}\n\n\tprivate _maybeAutoTerminalAfterWave(): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (this._isTerminal) return;\n\t\t// ERROR always propagates (unless rescue operator opts out via\n\t\t// errorWhenDepsError: false). Checked independently of _autoComplete\n\t\t// so operators with completeWhenDepsComplete: false still get\n\t\t// automatic error forwarding.\n\t\tconst erroredDep = this._deps.find((d) => d.terminal !== undefined && d.terminal !== true);\n\t\tif (erroredDep != null) {\n\t\t\tif (this._autoError) {\n\t\t\t\tthis._emit([[ERROR, erroredDep.terminal]]);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t// COMPLETE only when autoComplete is true and ALL deps are terminal.\n\t\tif (this._autoComplete && this._deps.every((d) => d.terminal !== undefined)) {\n\t\t\tthis._emit(COMPLETE_ONLY_BATCH);\n\t\t}\n\t}\n\n\t// --- Fn execution ---\n\n\t/**\n\t * @internal Runs the node fn once. Default cleanup (function form) fires\n\t * before the new run; `{ deactivation }` cleanup survives.\n\t */\n\tprivate _execFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._isTerminal && !this._resubscribable) return;\n\t\t// Re-entrance guard: if fn is currently executing (e.g. _addDep\n\t\t// triggered a synchronous DATA delivery → _maybeRunFnOnSettlement\n\t\t// → _execFn), defer the re-run until the current fn returns.\n\t\tif (this._isExecutingFn) {\n\t\t\tthis._pendingRerun = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Pre-run cleanup — only the function-form cleanup fires here.\n\t\tconst prevCleanup = this._cleanup;\n\t\tif (typeof prevCleanup === \"function\") {\n\t\t\tthis._cleanup = undefined;\n\t\t\ttry {\n\t\t\t\tprevCleanup();\n\t\t\t} catch (err) {\n\t\t\t\tthis._emit([[ERROR, this._wrapFnError(\"cleanup threw\", err)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// { deactivation } cleanup is preserved across runs.\n\n\t\t// Snapshot dep state BEFORE clearing wave flags so the snapshot\n\t\t// reflects \"this wave\" rather than \"next wave\".\n\t\t// dataBatch is copied here because _clearWaveFlags truncates the live\n\t\t// array in-place (length = 0) — the fn must see the full wave batch.\n\t\tconst batchData: (readonly unknown[] | undefined)[] = this._deps.map((d) =>\n\t\t\t!d.involvedThisWave ? undefined : d.dataBatch.length > 0 ? [...d.dataBatch] : [],\n\t\t);\n\t\t// Snapshot prevData BEFORE committing this wave's values — fn sees the\n\t\t// stable values from the end of the previous wave, not the current wave.\n\t\t// undefined = \"never sent DATA\". null is a valid DATA value.\n\t\tconst prevData: unknown[] = this._deps.map((d) => d.prevData);\n\t\t// Commit: advance each dep's prevData to this wave's last DATA so the\n\t\t// NEXT wave's fn snapshot sees the current wave as \"previous\".\n\t\t// Use the already-copied batchData rather than dep.dataBatch to avoid\n\t\t// any ordering dependency with _clearWaveFlags.\n\t\tfor (let i = 0; i < this._deps.length; i++) {\n\t\t\tconst batch = batchData[i];\n\t\t\tif (batch != null && batch.length > 0) {\n\t\t\t\tthis._deps[i].prevData = batch[batch.length - 1] as unknown;\n\t\t\t}\n\t\t}\n\t\tconst terminalDeps = this._deps.map((d) => d.terminal);\n\t\tconst ctx: FnCtx = { prevData, terminalDeps, store: this._store };\n\n\t\tthis._hasCalledFnOnce = true;\n\t\tthis._clearWaveFlags();\n\n\t\t// Fire inspector hooks before fn runs — for Graph.observe causal traces.\n\t\tif (this._inspectorHooks != null) {\n\t\t\tconst ev: NodeInspectorHookEvent = { kind: \"run\", batchData, prevData };\n\t\t\tfor (const hook of this._inspectorHooks) hook(ev);\n\t\t}\n\n\t\tthis._isExecutingFn = true;\n\t\ttry {\n\t\t\tconst result = this._fn(batchData, this._actions, ctx);\n\t\t\tif (typeof result === \"function\") {\n\t\t\t\tthis._cleanup = result;\n\t\t\t} else if (\n\t\t\t\tresult != null &&\n\t\t\t\ttypeof result === \"object\" &&\n\t\t\t\ttypeof (result as { deactivation?: unknown }).deactivation === \"function\"\n\t\t\t) {\n\t\t\t\tthis._cleanup = result as { deactivation: () => void };\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis._emit([[ERROR, this._wrapFnError(\"fn threw\", err)]]);\n\t\t} finally {\n\t\t\tthis._isExecutingFn = false;\n\t\t\t// Run any pending rerun BEFORE clearing wave flags so the\n\t\t\t// rerun's settlement check sees \"this wave had new data\" and\n\t\t\t// skips the pre-fn-skip optimization. Without this ordering,\n\t\t\t// autoTrackNode discovery's second pass gets swallowed by\n\t\t\t// the pre-fn-skip path.\n\t\t\tif (this._pendingRerun) {\n\t\t\t\tthis._pendingRerun = false;\n\t\t\t\tthis._rerunDepth += 1;\n\t\t\t\tif (this._rerunDepth > MAX_RERUN_DEPTH) {\n\t\t\t\t\tthis._rerunDepth = 0;\n\t\t\t\t\tthis._emit([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tERROR,\n\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t`Node \"${this.name}\": _pendingRerun depth exceeded ${MAX_RERUN_DEPTH} — likely a reactive cycle`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else {\n\t\t\t\t\tthis._maybeRunFnOnSettlement();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Chain converged — reset the depth counter for the next wave.\n\t\t\t\tthis._rerunDepth = 0;\n\t\t\t}\n\t\t\t// Clear flags after rerun so any involvedThisWave/dataBatch set by\n\t\t\t// fn's _addDep subscribe handshakes doesn't leak into the next\n\t\t\t// wave's snapshot. The inner _execFn (if any) already did\n\t\t\t// its own pre-snapshot clear; this is for the case where\n\t\t\t// fn added deps but no rerun fired.\n\t\t\tthis._clearWaveFlags();\n\t\t}\n\t}\n\n\tprivate _clearWaveFlags(): void {\n\t\tthis._waveHasNewData = false;\n\t\tthis._hasNewTerminal = false;\n\t\tfor (const d of this._deps) {\n\t\t\td.involvedThisWave = false;\n\t\t\td.dataBatch.length = 0;\n\t\t}\n\t}\n\n\tprivate _wrapFnError(label: string, err: unknown): Error {\n\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\treturn new Error(`Node \"${this.name}\": ${label}: ${msg}`, { cause: err });\n\t}\n\n\t// --- Framing (tier sort + synthetic DIRTY prefix) ---\n\n\t/**\n\t * @internal Stable tier sort + synthetic DIRTY prefix for an outgoing\n\t * batch. Fast path: already-monotone single-tier batches (the common\n\t * case from interned singletons like `DIRTY_ONLY_BATCH`) return the\n\t * input unchanged. General path: decorate-sort-undecorate into a new\n\t * array, then prepend `[DIRTY]` after any tier-0 START entries when\n\t * a tier-3 payload is present and the node isn't already dirty.\n\t *\n\t * Single source of truth for the spec §1.3.1 framing invariant. Every\n\t * outgoing path hits `_frameBatch` exactly once via `_emit`.\n\t */\n\tprivate _frameBatch(messages: Messages): Messages {\n\t\tconst tierOf = this._config.tierOf;\n\t\t// Fast path: single message.\n\t\tif (messages.length === 1) {\n\t\t\tconst t = tierOf(messages[0][0]);\n\t\t\tif (t === 3 && this._status !== \"dirty\") {\n\t\t\t\treturn [DIRTY_MSG, messages[0]];\n\t\t\t}\n\t\t\treturn messages;\n\t\t}\n\t\t// Check monotonicity and tier-3 presence in a single pass.\n\t\tlet monotone = true;\n\t\tlet hasTier3 = false;\n\t\tlet hasDirty = false;\n\t\tlet prevTier = -1;\n\t\tfor (const m of messages) {\n\t\t\tconst tier = tierOf(m[0]);\n\t\t\tif (tier < prevTier) monotone = false;\n\t\t\tif (tier === 3) hasTier3 = true;\n\t\t\tif (m[0] === DIRTY) hasDirty = true;\n\t\t\tprevTier = tier;\n\t\t}\n\t\tlet sorted: Messages = messages;\n\t\tif (!monotone) {\n\t\t\t// Stable sort via index-keyed decoration.\n\t\t\tconst indexed = messages.map((m, i) => ({ m, i, tier: tierOf(m[0]) }));\n\t\t\tindexed.sort((a, b) => a.tier - b.tier || a.i - b.i);\n\t\t\tsorted = indexed.map((x) => x.m);\n\t\t}\n\t\tif (hasTier3 && !hasDirty && this._status !== \"dirty\") {\n\t\t\t// Insert DIRTY after any tier-0 START entries to preserve\n\t\t\t// monotonicity.\n\t\t\tlet insertAt = 0;\n\t\t\twhile (insertAt < sorted.length && tierOf(sorted[insertAt][0]) === 0) insertAt++;\n\t\t\tif (insertAt === 0) return [DIRTY_MSG, ...sorted];\n\t\t\treturn [...sorted.slice(0, insertAt), DIRTY_MSG, ...sorted.slice(insertAt)];\n\t\t}\n\t\treturn sorted;\n\t}\n\n\t// --- Emit pipeline ---\n\n\t/**\n\t * @internal The unified dispatch waist — one call = one wave.\n\t *\n\t * Pipeline stages, in order:\n\t *\n\t * 1. Early-return on empty batch.\n\t * 2. Terminal filter — post-COMPLETE/ERROR only TEARDOWN/INVALIDATE\n\t * still propagate so graph teardown and cache-clear still work.\n\t * 3. Tier sort (stable) — the batch can be in any order when it\n\t * arrives; the walker downstream (`downWithBatch`) assumes\n\t * ascending tier monotone, and so does `_updateState`'s tier-3\n\t * slice walk. This is the single source of truth for ordering.\n\t * 4. Synthetic DIRTY prefix — if a tier-3 payload is present, no\n\t * DIRTY is already in the batch, and the node isn't already in\n\t * `\"dirty\"` status, prepend `[DIRTY]` after any tier-0 START\n\t * entries. Guarantees spec §1.3.1 (DIRTY precedes DATA within\n\t * the same batch) uniformly across every entry point.\n\t * 5. PAUSE/RESUME lock bookkeeping (C0) — update `_pauseLocks`,\n\t * derive `_paused`, filter unknown-lockId RESUME, replay\n\t * bufferAll buffer on final lock release.\n\t * 6. Meta TEARDOWN fan-out — notify meta children before\n\t * `_updateState`'s TEARDOWN branch calls `_deactivate`. Hoisted\n\t * out of the walk to keep `_updateState` re-entrance-free.\n\t * 7. `_updateState` — walk the batch in tier order, advancing\n\t * `_cached` / `_status` / `_versioning` and running equals\n\t * substitution on tier-3 DATA (§3.5.1). Returns\n\t * `{finalMessages, equalsError?}`.\n\t * 8. `downWithBatch` dispatch (or bufferAll capture if paused with\n\t * `pausable: \"resumeAll\"`).\n\t * 9. Recursive ERROR emission if equals threw mid-walk.\n\t *\n\t * `node.down` / `node.emit` / `actions.down` / `actions.emit` all\n\t * converge here — the unified `_emit` waist (spec §1.3.1).\n\t */\n\t_emit(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\n\t\t// Terminal filter: after COMPLETE/ERROR (non-resubscribable), only\n\t\t// TEARDOWN / INVALIDATE still propagate so graph teardown and cache-\n\t\t// clear still work.\n\t\tlet deliverable = messages;\n\t\tconst terminal = this._isTerminal;\n\t\tif (terminal && !this._resubscribable) {\n\t\t\tconst pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (pass.length === 0) return;\n\t\t\tdeliverable = pass;\n\t\t}\n\n\t\t// Tier sort + synthetic DIRTY prefix (stages 3 + 4 of the emit\n\t\t// pipeline). `_frameBatch` is a no-op for pre-sorted single-msg\n\t\t// batches (the common case from the tuple-interning A2 call sites);\n\t\t// otherwise it produces a stable tier-sorted copy with `[DIRTY]`\n\t\t// auto-prepended after any tier-0 messages when a tier-3 payload\n\t\t// is present and the node isn't already dirty.\n\t\tdeliverable = this._frameBatch(deliverable);\n\n\t\t// C0 — PAUSE/RESUME lock tracking. Every tier-2 tuple MUST carry a\n\t\t// `lockId` payload. Each PAUSE / RESUME updates `_pauseLocks` and\n\t\t// derives `_paused` from set size — multi-pauser correctness\n\t\t// guarantees a node only resumes when every lock it holds is\n\t\t// released. All tier-2 messages are forwarded unconditionally so\n\t\t// downstream nodes on the propagation path keep their own lock\n\t\t// sets consistent (subscribers that joined the graph before any\n\t\t// PAUSE see the full lock history). `pausable: false` sources\n\t\t// forward PAUSE/RESUME but do not track locks — appropriate for\n\t\t// reactive timers that must keep ticking. Unknown-lockId RESUME\n\t\t// is swallowed to keep `dispose()` idempotent.\n\t\tlet filtered: Message[] | null = null;\n\t\tfor (let i = 0; i < deliverable.length; i++) {\n\t\t\tconst m = deliverable[i];\n\t\t\tconst t = m[0];\n\t\t\tif (t !== PAUSE && t !== RESUME) {\n\t\t\t\tif (filtered != null) filtered.push(m);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m.length < 2) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Node \"${this.name}\": [[${t === PAUSE ? \"PAUSE\" : \"RESUME\"}]] must ` +\n\t\t\t\t\t\t\"carry a lockId payload — bare PAUSE/RESUME is a protocol \" +\n\t\t\t\t\t\t\"violation (C0 rule). Use `[[PAUSE, lockId]]` / \" +\n\t\t\t\t\t\t\"`[[RESUME, lockId]]`.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet forward = true;\n\t\t\tif (this._pausable !== false) {\n\t\t\t\tconst lockId = m[1];\n\t\t\t\tif (t === PAUSE) {\n\t\t\t\t\tif (this._pauseLocks == null) this._pauseLocks = new Set();\n\t\t\t\t\tthis._pauseLocks.add(lockId);\n\t\t\t\t\tthis._paused = true;\n\t\t\t\t\tif (this._pausable === \"resumeAll\" && this._pauseBuffer == null) {\n\t\t\t\t\t\tthis._pauseBuffer = [];\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// RESUME\n\t\t\t\t\tif (this._pauseLocks == null || !this._pauseLocks.has(lockId)) {\n\t\t\t\t\t\t// Unknown lockId — swallow to keep dispose idempotent.\n\t\t\t\t\t\tforward = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis._pauseLocks.delete(lockId);\n\t\t\t\t\t\tif (this._pauseLocks.size === 0) {\n\t\t\t\t\t\t\tthis._paused = false;\n\t\t\t\t\t\t\t// Replay bufferAll buffer through the outgoing\n\t\t\t\t\t\t\t// pipeline BEFORE forwarding RESUME — subscribers\n\t\t\t\t\t\t\t// observe the deferred DATAs as part of the\n\t\t\t\t\t\t\t// pre-RESUME wake-up.\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t// D2 (2026-04-13) semantic note: the recursive\n\t\t\t\t\t\t\t// `_emit(drain)` goes through the full pipeline\n\t\t\t\t\t\t\t// including `_updateState`'s equals substitution.\n\t\t\t\t\t\t\t// A buffered `[DATA, v]` whose value matches the\n\t\t\t\t\t\t\t// *pre-pause* cache will collapse to RESOLVED on\n\t\t\t\t\t\t\t// replay — producer \"pulses\" that write the same\n\t\t\t\t\t\t\t// value while paused are absorbed. This matches\n\t\t\t\t\t\t\t// diamond-safety intent: `.cache` stays coherent\n\t\t\t\t\t\t\t// with \"the last DATA actually delivered to\n\t\t\t\t\t\t\t// sinks\". Producers that need pulse semantics\n\t\t\t\t\t\t\t// (every write observable regardless of value)\n\t\t\t\t\t\t\t// should set `equals: () => false` on the node.\n\t\t\t\t\t\t\tif (this._pauseBuffer != null && this._pauseBuffer.length > 0) {\n\t\t\t\t\t\t\t\tconst drain = this._pauseBuffer;\n\t\t\t\t\t\t\t\tthis._pauseBuffer = [];\n\t\t\t\t\t\t\t\tthis._emit(drain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Kick the held wave forward if one was pending.\n\t\t\t\t\t\t\tif (this._pendingWave) {\n\t\t\t\t\t\t\t\tthis._pendingWave = false;\n\t\t\t\t\t\t\t\tthis._maybeRunFnOnSettlement();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!forward) {\n\t\t\t\tif (filtered == null) filtered = deliverable.slice(0, i) as Message[];\n\t\t\t} else if (filtered != null) {\n\t\t\t\tfiltered.push(m);\n\t\t\t}\n\t\t}\n\t\tif (filtered != null) {\n\t\t\tif (filtered.length === 0) return;\n\t\t\tdeliverable = filtered;\n\t\t}\n\n\t\t// Meta TEARDOWN fan-out happens BEFORE `_updateState` so the walk\n\t\t// stays re-entrance-free: a meta node's own dispatch must not\n\t\t// re-enter the parent's outgoing pipeline while `this._cached` /\n\t\t// `this._status` are mid-commit. This preserves the spec ordering\n\t\t// \"meta propagates before deactivation\" — `_updateState`'s TEARDOWN\n\t\t// branch still runs `_deactivate` AFTER the meta children\n\t\t// have already been notified here.\n\t\tif (this._hasMeta && deliverable.some((m) => m[0] === TEARDOWN)) {\n\t\t\tfor (const k of Object.keys(this.meta)) {\n\t\t\t\ttry {\n\t\t\t\t\t(this.meta[k] as NodeImpl)._emit(TEARDOWN_ONLY_BATCH);\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// State update + equals substitution (§3.5.1 invariant). Returns the\n\t\t// possibly-rewritten batch and an optional equals-throw error. When\n\t\t// equals throws mid-walk we still deliver the successfully-walked\n\t\t// prefix to sinks before emitting ERROR, preserving cache/wire\n\t\t// coherence (user P2 option (i)).\n\t\tconst { finalMessages, equalsError } = this._updateState(deliverable);\n\n\t\t// Global inspector fan-out (Redux-DevTools-style tracer). Fires once\n\t\t// per outgoing batch, gated by `inspectorEnabled` so production paths\n\t\t// pay one boolean check. Hook errors are swallowed — instrumentation\n\t\t// must not break the data plane.\n\t\tif (finalMessages.length > 0 && this._config.inspectorEnabled) {\n\t\t\tconst inspector = this._config.globalInspector;\n\t\t\tif (inspector != null) {\n\t\t\t\ttry {\n\t\t\t\t\tinspector({ kind: \"emit\", node: this, messages: finalMessages });\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (finalMessages.length > 0) {\n\t\t\t// BufferAll: while paused with `pausable: \"resumeAll\"`, buffer\n\t\t\t// tier-3/4 payloads in order. Tier 0–2 and tier 5 continue to\n\t\t\t// dispatch synchronously — START/DIRTY/RESUME/PAUSE/TEARDOWN\n\t\t\t// must stay live so subscribers, downstream pausers, and graph\n\t\t\t// teardown all observe them. Cache/status advance has already\n\t\t\t// happened via `_updateState`, so the replay later just pushes\n\t\t\t// the deferred messages back through `downWithBatch`.\n\t\t\tif (this._paused && this._pausable === \"resumeAll\" && this._pauseBuffer != null) {\n\t\t\t\tconst tierOf = this._config.tierOf;\n\t\t\t\tconst immediate: Message[] = [];\n\t\t\t\tfor (const m of finalMessages) {\n\t\t\t\t\tconst tier = tierOf(m[0]);\n\t\t\t\t\tif (tier < 3 || tier === 5) {\n\t\t\t\t\t\timmediate.push(m);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis._pauseBuffer.push(m);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (immediate.length > 0) {\n\t\t\t\t\tdownWithBatch(this._deliverToSinks, immediate, tierOf);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdownWithBatch(this._deliverToSinks, finalMessages, this._config.tierOf);\n\t\t\t}\n\t\t}\n\n\t\tif (equalsError != null) {\n\t\t\tthis._emit([[ERROR, equalsError]]);\n\t\t}\n\t}\n\n\t/**\n\t * @internal Walk an outgoing (already-framed) batch, updating own\n\t * cache / status / versioning and running equals substitution on\n\t * every tier-3 DATA (§3.5.1). Framing — tier sort and synthetic\n\t * DIRTY prefix — has already happened upstream in `_frameBatch`.\n\t * This walk trusts the input is in monotone tier order and that the\n\t * spec §1.3.1 DIRTY/RESOLVED precedence invariant is already\n\t * satisfied by the frame.\n\t *\n\t * Equals substitution: every DATA payload is compared against the\n\t * live `_cached`; when equal, the tuple is rewritten to `[RESOLVED]`\n\t * in a per-call copy and cache is not re-advanced. `.cache` remains\n\t * coherent with \"the last DATA payload this node actually sent\n\t * downstream\".\n\t *\n\t * Returns `{ finalMessages, equalsError? }`:\n\t * - `finalMessages` — the array to deliver to sinks (may be\n\t * `messages` unchanged, a rewritten copy with DATA→RESOLVED\n\t * substitutions, or a truncated prefix when equals throws mid-walk).\n\t * - `equalsError` — present only when the configured `equals` function\n\t * threw on some DATA message. `_emit` delivers the prefix first,\n\t * then emits a fresh ERROR batch via a recursive `_emit` call so\n\t * subscribers observe `[...walked_prefix, ERROR]` in order.\n\t */\n\tprivate _updateState(messages: Messages): {\n\t\tfinalMessages: Messages;\n\t\tequalsError?: Error;\n\t} {\n\t\tconst tierOf = this._config.tierOf;\n\t\tlet rewritten: Message[] | undefined;\n\t\tlet equalsError: Error | undefined;\n\t\tlet abortedAt = -1;\n\t\t// Count tier-3 messages (DATA + RESOLVED) in the batch. Equals\n\t\t// substitution is only worthwhile for a single tier-3 message —\n\t\t// an unchanged value can be rewritten to RESOLVED, enabling the\n\t\t// downstream pre-fn skip. With multiple tier-3 messages the\n\t\t// downstream fn must run regardless, so equals on each is wasted.\n\t\tlet dataCount = 0;\n\t\tfor (const m of messages) {\n\t\t\tif (tierOf(m[0]) === 3) dataCount++;\n\t\t}\n\t\tconst checkEquals = dataCount <= 1;\n\t\t// Version advances once per batch wave, not per DATA in the batch.\n\t\t// _cached only retains the last DATA value, so intermediate version\n\t\t// entries would reference values that can never be retrieved from cache.\n\t\t// Pre-scan for the last DATA index so we know when to fire advanceVersion.\n\t\tlet lastDataIdx = -1;\n\t\tif (this._versioning != null && dataCount > 1) {\n\t\t\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\t\t\tif (messages[i][0] === DATA) {\n\t\t\t\t\tlastDataIdx = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (let i = 0; i < messages.length; i++) {\n\t\t\tconst m = messages[i];\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (m.length >= 2) {\n\t\t\t\t\tlet unchanged = false;\n\t\t\t\t\tif (checkEquals && this._cached !== undefined) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tunchanged = this._equals(this._cached as T, m[1] as T);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t// Abort walk on equals throw: deliver successfully-walked\n\t\t\t\t\t\t\t// prefix, then caller emits ERROR. Excludes the throwing\n\t\t\t\t\t\t\t// message from the prefix.\n\t\t\t\t\t\t\tequalsError = this._wrapFnError(\"equals threw\", err);\n\t\t\t\t\t\t\tabortedAt = i;\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 (unchanged) {\n\t\t\t\t\t\tif (rewritten == null) rewritten = messages.slice(0, i) as Message[];\n\t\t\t\t\t\trewritten.push(RESOLVED_MSG);\n\t\t\t\t\t\tthis._status = \"resolved\";\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\t\t// dataCount <= 1: lastDataIdx is -1; advance unconditionally\n\t\t\t\t\t\t// (single DATA, correct as before).\n\t\t\t\t\t\t// dataCount > 1: only advance on the last DATA in the batch.\n\t\t\t\t\t\tif (lastDataIdx < 0 || i === lastDataIdx) {\n\t\t\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._status = \"settled\";\n\t\t\t\tif (rewritten != null) rewritten.push(m);\n\t\t\t} else {\n\t\t\t\tif (rewritten != null) rewritten.push(m);\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\tthis._status = \"dirty\";\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tthis._status = \"resolved\";\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tthis._status = \"completed\";\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tthis._status = \"errored\";\n\t\t\t\t} else if (t === INVALIDATE) {\n\t\t\t\t\tthis._cached = undefined;\n\t\t\t\t\tthis._status = \"dirty\";\n\t\t\t\t\t// Function-form cleanup fires on invalidate (treats as \"re-run\").\n\t\t\t\t\tconst c = this._cleanup;\n\t\t\t\t\tif (typeof c === \"function\") {\n\t\t\t\t\t\tthis._cleanup = undefined;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tc();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t/* best-effort */\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (t === TEARDOWN) {\n\t\t\t\t\tif (this._resetOnTeardown) this._cached = undefined;\n\t\t\t\t\t// Meta TEARDOWN fan-out was already performed by `_emit`\n\t\t\t\t\t// before this walk. Deactivate now that meta children\n\t\t\t\t\t// have been notified.\n\t\t\t\t\tthis._deactivate(/* skipStatusUpdate */ true);\n\t\t\t\t\t// TEARDOWN is a hard reset — unconditionally \"sentinel\",\n\t\t\t\t\t// even if the node was previously completed/errored.\n\t\t\t\t\tthis._status = \"sentinel\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst base: Messages =\n\t\t\tabortedAt >= 0\n\t\t\t\t? ((rewritten ?? (messages.slice(0, abortedAt) as Messages)) as Messages)\n\t\t\t\t: (rewritten ?? messages);\n\t\treturn equalsError != null ? { finalMessages: base, equalsError } : { finalMessages: base };\n\t}\n\n\tprivate _deliverToSinks = (messages: Messages): void => {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others\n\t\t// mid-iteration. Iterating the live Set would skip not-yet-visited\n\t\t// sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) sink(messages);\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nconst isNodeArray = (value: unknown): value is readonly Node[] => Array.isArray(value);\nconst isNodeOptionsObject = (value: unknown): value is NodeOptions<unknown> =>\n\ttypeof value === \"object\" && value != null && !Array.isArray(value);\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (§2).\n *\n * Typical shapes:\n * - `node([])` / `node({ initial: v })` — a manual source (state node).\n * - `node(producerFn, opts)` — a producer that runs on first-subscribe.\n * - `node(deps, computeFn, opts)` — a derived / effect node.\n *\n * For value-returning computations, prefer the sugar factories in `sugar.ts`\n * (`state`, `derived`, `effect`, `producer`, `dynamicNode`), which wrap user\n * fns with `actions.emit(userFn(data))`. Calling `node()` directly gives you\n * the raw `NodeFn` contract: explicit emission via `actions`, cleanup return.\n */\nexport function node<T = unknown>(\n\tdepsOrFn?: readonly Node[] | NodeFn | NodeOptions<T>,\n\tfnOrOpts?: NodeFn | NodeOptions<T>,\n\toptsArg?: NodeOptions<T>,\n): Node<T> {\n\tconst deps: readonly Node[] = isNodeArray(depsOrFn) ? depsOrFn : [];\n\tconst fn: NodeFn | undefined =\n\t\ttypeof depsOrFn === \"function\"\n\t\t\t? depsOrFn\n\t\t\t: typeof fnOrOpts === \"function\"\n\t\t\t\t? fnOrOpts\n\t\t\t\t: undefined;\n\tlet opts: NodeOptions<T> = {};\n\tif (isNodeArray(depsOrFn)) {\n\t\topts = ((isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {}) as NodeOptions<T>;\n\t} else if (isNodeOptionsObject(depsOrFn)) {\n\t\topts = depsOrFn as NodeOptions<T>;\n\t} else {\n\t\topts = ((isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {}) as NodeOptions<T>;\n\t}\n\treturn new NodeImpl<T>(deps, fn, opts);\n}\n","import type { Actor } from \"./actor.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { type Node, type NodeDescribeKind, NodeImpl } from \"./node.js\";\n\n/**\n * JSON-shaped slice of a node for `Graph.describe()`\n * (GRAPHREFLY-SPEC §3.6, Appendix B).\n */\nexport type DescribeNodeOutput = {\n\ttype: NodeDescribeKind;\n\tstatus?: Node[\"status\"];\n\tdeps: string[];\n\tmeta?: Record<string, unknown>;\n\tname?: string;\n\tvalue?: unknown;\n\t/** True when the node is in `\"sentinel\"` state (no value ever). */\n\tsentinel?: boolean;\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\n\tguard?: string;\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/**\n\t * Latest reason annotation attached via `graph.trace(path, reason)`,\n\t * when present. Populated by `Graph.describe` only — `describeNode`\n\t * has no graph context.\n\t */\n\treason?: string;\n};\n\n/** Detail level for progressive disclosure (Phase 3.3b). */\nexport type DescribeDetail = \"minimal\" | \"standard\" | \"full\";\n\n/** Valid field names for `describe({ fields: [...] })`. */\nexport type DescribeField =\n\t| \"type\"\n\t| \"status\"\n\t| \"value\"\n\t| \"deps\"\n\t| \"meta\"\n\t| \"v\"\n\t| \"guard\"\n\t| \"lastMutation\"\n\t| `meta.${string}`;\n\n/** Resolve which fields to include based on detail level or explicit field list. */\nexport function resolveDescribeFields(\n\tdetail?: DescribeDetail,\n\tfields?: readonly DescribeField[],\n): Set<string> | null {\n\tif (fields != null && fields.length > 0) return new Set(fields);\n\tswitch (detail) {\n\t\tcase \"standard\":\n\t\t\treturn new Set([\"type\", \"status\", \"value\", \"deps\", \"meta\", \"v\"]);\n\t\tcase \"full\":\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn new Set([\"type\", \"deps\"]);\n\t}\n}\n\nfunction inferDescribeType(n: NodeImpl): NodeDescribeKind {\n\tif (n._describeKind != null) return n._describeKind;\n\tconst hasDeps = n._deps.length > 0;\n\tif (!hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\t// With deps: derived (passthrough falls under derived, no fn → derived shape).\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON.\n *\n * Values come from {@link Node.cache}, which returns the last settled cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status`\n * when freshness matters.\n */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.cache;\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta`\n * snapshot). Parity with `graphrefly-py` `describe_node`.\n */\nexport function describeNode(node: Node, includeFields?: Set<string> | null): DescribeNodeOutput {\n\tconst all = includeFields == null;\n\tconst metaKeys: string[] | null =\n\t\t!all && includeFields != null\n\t\t\t? [...includeFields].filter((f) => f.startsWith(\"meta.\")).map((f) => f.slice(5))\n\t\t\t: null;\n\tconst wantsMeta = all || includeFields!.has(\"meta\") || (metaKeys != null && metaKeys.length > 0);\n\n\tlet type: NodeDescribeKind = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.node.name ?? \"\");\n\t}\n\n\tconst out: DescribeNodeOutput = { type, deps };\n\n\tif (all || includeFields!.has(\"status\")) {\n\t\tout.status = node.status;\n\t}\n\n\tconst guard = node instanceof NodeImpl ? node._guard : undefined;\n\n\tif (wantsMeta) {\n\t\tconst rawMeta: Record<string, unknown> = { ...metaSnapshot(node) };\n\t\tif (guard != null && rawMeta.access === undefined) {\n\t\t\trawMeta.access = accessHintForGuard(guard);\n\t\t}\n\t\tif (metaKeys != null && metaKeys.length > 0 && !includeFields!.has(\"meta\")) {\n\t\t\tconst filtered: Record<string, unknown> = {};\n\t\t\tfor (const k of metaKeys) {\n\t\t\t\tif (k in rawMeta) filtered[k] = rawMeta[k];\n\t\t\t}\n\t\t\tout.meta = filtered;\n\t\t} else {\n\t\t\tout.meta = rawMeta;\n\t\t}\n\t}\n\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\tif (all || includeFields!.has(\"value\")) {\n\t\tif (node.status === \"sentinel\") out.sentinel = true;\n\t\ttry {\n\t\t\tout.value = node.cache;\n\t\t} catch {\n\t\t\t/* omit value */\n\t\t}\n\t}\n\n\tif ((all || includeFields!.has(\"v\")) && node.v != null) {\n\t\tconst vInfo: NonNullable<DescribeNodeOutput[\"v\"]> = {\n\t\t\tid: node.v.id,\n\t\t\tversion: node.v.version,\n\t\t};\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\tif (all || includeFields!.has(\"guard\")) {\n\t\tif (guard != null) out.guard = accessHintForGuard(guard);\n\t}\n\n\tif (all || includeFields!.has(\"lastMutation\")) {\n\t\tif (node.lastMutation != null) out.lastMutation = node.lastMutation;\n\t}\n\n\treturn out;\n}\n","/**\n * Sugar constructors over the raw `node()` primitive.\n *\n * Each factory wraps a user-friendly function into the canonical\n * `NodeFn = (data, actions, ctx) => cleanup | void` shape, then calls\n * `node(...)`. This is the only place `actions.emit(...)` is invoked\n * on behalf of the user — if you need finer control (multi-emission,\n * raw `actions.down` / `actions.up`, cleanup return), use the raw\n * `node()` factory from `./node.js` directly.\n *\n * See SESSION-foundation-redesign.md §8.5 + §10.6 for the rewrite.\n */\n\nimport type { NodeActions } from \"./config.js\";\nimport { RESOLVED } from \"./messages.js\";\nimport {\n\ttype FnCtx,\n\ttype Node,\n\ttype NodeFn,\n\ttype NodeFnCleanup,\n\tNodeImpl,\n\ttype NodeOptions,\n\tnode,\n} from \"./node.js\";\n\n// ---------------------------------------------------------------------------\n// Shared sentinel guard\n// ---------------------------------------------------------------------------\n\n/**\n * Returns `true` when fn should be suppressed (RESOLVED emitted instead).\n *\n * Fires when `allowPartial` is `false` and any dep has never delivered DATA:\n * `data[i]` absent this wave AND `ctx.prevData[i] === undefined`.\n *\n * `undefined` is the protocol-reserved \"never sent DATA\" sentinel. `null` is\n * a valid DATA value and will NOT trigger the guard.\n */\nfunction sentinelGuard(\n\tbatchData: readonly (readonly unknown[] | undefined)[],\n\tctx: FnCtx,\n\tallowPartial: boolean,\n): boolean {\n\tif (allowPartial) return false;\n\treturn batchData.some(\n\t\t(batch, i) => !(batch != null && batch.length > 0) && ctx.prevData[i] === undefined,\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// state — manual source with an optional initial value\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a manual source node. Drive it with `state.emit(v)` (framed,\n * diamond-safe) or `state.down([[DATA, v]])` (raw compat path).\n *\n * @param initial - Starting cached value. Pass `undefined` or `null`\n * explicitly to cache that value; omit to leave the node in `\"sentinel\"`.\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions<T>, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n// ---------------------------------------------------------------------------\n// producer — no-deps source with a compute body\n// ---------------------------------------------------------------------------\n\n/**\n * User-level producer compute: runs once on first-subscriber activation.\n * Receives `actions` for imperative emission and `ctx` for FnCtx (typically\n * only `store` is useful on a producer — no deps means `prevData` and\n * `terminalDeps` are empty).\n */\nexport type ProducerFn = (\n\tactions: NodeActions,\n\tctx: FnCtx,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: matches NodeFn — see its JSDoc.\n) => NodeFnCleanup | void;\n\n/**\n * Creates a producer node with no deps; `fn` runs once when the first\n * subscriber connects. Return a cleanup function (`() => void`) or\n * `{ deactivation: () => void }` to register teardown.\n *\n * @example\n * ```ts\n * const ticker = producer((actions) => {\n * const id = setInterval(() => actions.emit(Date.now()), 1000);\n * return () => clearInterval(id);\n * });\n * ```\n */\nexport function producer<T = unknown>(fn: ProducerFn, opts?: NodeOptions<T>): Node<T> {\n\tconst wrapped: NodeFn = (_data, actions, ctx) => fn(actions, ctx) ?? undefined;\n\treturn node<T>(wrapped, { describeKind: \"producer\", ...opts });\n}\n\n// ---------------------------------------------------------------------------\n// derived — dep-driven pure compute\n// ---------------------------------------------------------------------------\n\n/**\n * User-level derived compute: receives the latest DATA from each dep and\n * returns the new value. The sugar wraps it with `actions.emit(fn(...))`\n * so the return value flows through the framed emit pipeline.\n *\n * For derived nodes that need to inspect `ctx.prevData` / `ctx.terminalDeps`\n * / `ctx.store`, accept the optional second parameter.\n */\nexport type DerivedFn<T> = (data: readonly unknown[], ctx: FnCtx) => T | undefined | null;\n\n/**\n * Creates a derived node that computes **one output per wave** from the latest\n * value of each dependency — **snapshot / combine semantics**.\n *\n * `fn` receives one scalar per dep (the last DATA value seen this wave, or the\n * prior-wave value as fallback). It is called once per settled wave and emits\n * a single value via `actions.emit`. The equals check then suppresses the\n * emission as `RESOLVED` if the output has not changed.\n *\n * **Not for streaming one-to-one transforms.** If each DATA value in a batch\n * must produce a corresponding output (e.g. transforming every item emitted by\n * `fromIter` individually), use {@link map} or raw `node()` with full batch\n * iteration instead. `derived` only sees the *last* value per dep when a batch\n * carries multiple DATAs.\n *\n * @example\n * ```ts\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: DerivedFn<T>,\n\topts?: NodeOptions<T> & { partial?: boolean },\n): Node<T> {\n\tconst allowPartial = opts?.partial ?? false;\n\tconst wrapped: NodeFn = (batchData, actions, ctx) => {\n\t\t// Sentinel guard: if any dep has never sent DATA, emit RESOLVED.\n\t\t// Uses ctx.prevData[i] === undefined (the \"never sent\" sentinel).\n\t\t// null is valid DATA and won't trigger this. Skipped when partial:true.\n\t\tif (sentinelGuard(batchData, ctx, allowPartial)) {\n\t\t\tactions.down([[RESOLVED]]);\n\t\t\treturn undefined;\n\t\t}\n\t\t// Unwrap batch-per-dep to single latest scalar per dep.\n\t\t// Batch non-null+non-empty → take last value from this wave;\n\t\t// otherwise fall back to ctx.prevData[i] (last value from prior wave).\n\t\t// undefined means \"never sent DATA\" — sentinelGuard already blocks this\n\t\t// fn when partial:false and any dep is unset, so partial:true callers\n\t\t// receive undefined for uninitiated deps (same as JS convention).\n\t\tconst data = batchData.map((batch, i) =>\n\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t);\n\t\tactions.emit(fn(data, ctx));\n\t\treturn undefined;\n\t};\n\treturn node<T>(deps, wrapped, { describeKind: \"derived\", ...opts });\n}\n\n// ---------------------------------------------------------------------------\n// effect — dep-driven side effect, no auto-emit\n// ---------------------------------------------------------------------------\n\n/**\n * User-level effect compute: fires when deps settle. Return value is NOT\n * auto-emitted — use `actions.emit(v)` / `actions.down(msgs)` explicitly if\n * the effect also wants to produce downstream messages. Return a cleanup\n * function or `{ deactivation }` to register teardown.\n */\nexport type EffectFn = (\n\tdata: readonly unknown[],\n\tactions: NodeActions,\n\tctx: FnCtx,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: matches NodeFn — see its JSDoc.\n) => NodeFnCleanup | void;\n\n/**\n * Runs a side-effect when deps settle. Return value is not auto-emitted.\n *\n * @example\n * ```ts\n * effect([source], ([v]) => {\n * console.log(v);\n * });\n * ```\n */\nexport function effect(\n\tdeps: readonly Node[],\n\tfn: EffectFn,\n\topts?: NodeOptions<unknown> & { partial?: boolean },\n): Node<unknown> {\n\tconst allowPartial = opts?.partial ?? false;\n\tconst wrapped: NodeFn = (batchData, actions, ctx) => {\n\t\t// Sentinel guard: hold effect until all deps have initialised.\n\t\t// Matches pre-wave2 framework gate behaviour. Use partial:true to allow\n\t\t// the effect to fire before all deps have delivered their first value.\n\t\tif (sentinelGuard(batchData, ctx, allowPartial)) {\n\t\t\tactions.down([[RESOLVED]]);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst data = batchData.map((batch, i) =>\n\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t);\n\t\treturn fn(data, actions, ctx) ?? undefined;\n\t};\n\treturn node(deps, wrapped, { describeKind: \"effect\", ...opts });\n}\n\n// ---------------------------------------------------------------------------\n// dynamicNode — track-proxy wrapper over `derived`\n// ---------------------------------------------------------------------------\n\n/**\n * Proxy handed to a {@link DynamicFn}. `track(dep)` returns the dep's\n * latest DATA payload, as delivered through the protocol. Reading from\n * `track` does NOT bypass the message protocol — it reads the internal\n * `DepRecord.prevData` (the stable end-of-previous-wave value) that\n * `_onDepMessage` already populated. If a dep has not yet sent DATA,\n * `track` returns `undefined`.\n */\nexport type TrackFn = (dep: Node) => unknown;\n\n/** User-level dynamicNode compute. */\nexport type DynamicFn<T> = (track: TrackFn, ctx: FnCtx) => T | undefined | null;\n\n/**\n * Sugar over `derived(...)` that exposes dep values via a `track(dep)`\n * proxy instead of positional `data[i]`. All declared `allDeps` participate\n * in wave tracking, so the first fn run waits for every dep to settle.\n * Unused deps that update just re-run fn; `equals` absorbs unchanged\n * outputs as RESOLVED.\n *\n * P3-compliant: `track(dep)` reads from the framework-managed\n * `DepRecord.prevData` populated by the protocol, never from\n * `dep.cache`.\n *\n * @example\n * ```ts\n * const a = state(1);\n * const b = state(10);\n * const sum = dynamicNode([a, b], (track) => (track(a) as number) + (track(b) as number));\n * ```\n */\nexport function dynamicNode<T = unknown>(\n\tallDeps: readonly Node[],\n\tfn: DynamicFn<T>,\n\topts?: NodeOptions<T> & { partial?: boolean },\n): Node<T> {\n\tconst depIndex = new Map<Node, number>();\n\tallDeps.forEach((d, i) => {\n\t\tdepIndex.set(d, i);\n\t});\n\treturn derived<T>(\n\t\tallDeps,\n\t\t// data[i] is already sugar-unwrapped to a scalar by derived()'s wrapper.\n\t\t(data, ctx) => {\n\t\t\tconst track: TrackFn = (dep) => {\n\t\t\t\tconst i = depIndex.get(dep);\n\t\t\t\tif (i == null) {\n\t\t\t\t\tthrow new Error(`dynamicNode: untracked dep \"${dep.name ?? \"<unnamed>\"}\"`);\n\t\t\t\t}\n\t\t\t\treturn data[i];\n\t\t\t};\n\t\t\treturn fn(track, ctx);\n\t\t},\n\t\topts,\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// pipe — left-to-right operator composition\n// ---------------------------------------------------------------------------\n// autoTrackNode — runtime dep discovery (Jotai/signals compat)\n// ---------------------------------------------------------------------------\n\n/**\n * Like {@link dynamicNode} but deps are discovered at runtime via `track()`\n * calls — no upfront `allDeps` array needed. Designed for pull-based compat\n * layers (Jotai atoms, TC39 Signals) where deps are unknown until fn runs.\n *\n * **Two-phase discovery:**\n * 1. fn runs. Each `track(dep)` for an unknown dep: subscribes immediately\n * via `_addDep`, returns `dep.cache` as a stub (P3 boundary exception).\n * Result is discarded (discovery run).\n * 2. New deps settle (DATA from subscribe handshake). Wave machinery\n * re-triggers fn. `track(dep)` now returns protocol-delivered `data[i]`.\n * If MORE unknown deps appear, repeat step 1.\n * 3. Converges when no new deps found → real run → `actions.emit(result)`.\n *\n * P3 violation is limited to discovery runs. Once all deps are known,\n * subsequent waves use protocol-delivered values exclusively.\n *\n * Re-entrance safety: `_addDep` subscribes immediately. If the dep delivers\n * DATA synchronously during fn execution, `_execFn`'s re-entrance guard\n * defers the re-run to after the current fn returns.\n *\n * @param opts - Optional {@link AutoTrackOptions}. Pass `{ partial: true }` to\n * allow fn to run before all known deps have delivered their first value\n * (useful for optional/secondary deps).\n *\n * @example\n * ```ts\n * const a = state(1), b = state(2);\n * const sum = autoTrackNode((track) => track(a) + track(b));\n * // deps [a, b] discovered automatically on first run\n * ```\n */\n/**\n * Options for {@link autoTrackNode}.\n */\nexport interface AutoTrackOptions<T> extends NodeOptions<T> {\n\t/**\n\t * When `true`, fn may run before all known deps have delivered their first\n\t * DATA. Unknown deps return `undefined` via `track()`, which the fn must\n\t * handle explicitly. Useful when some deps are \"nice-to-have\" — e.g. a\n\t * primary computation should continue while a secondary dep is still\n\t * initialising.\n\t *\n\t * When `false` (default), fn is held until every known dep has delivered at\n\t * least one DATA value — a RESOLVED is emitted for the wave instead.\n\t * This matches `derived()` semantics and is the correct default for\n\t * pull-based compat layers (Signals, Jotai) where all deps must be\n\t * initialised before the computation is meaningful.\n\t *\n\t * @default false\n\t */\n\tpartial?: boolean;\n}\n\nexport function autoTrackNode<T = unknown>(\n\tfn: (track: TrackFn, ctx: FnCtx) => T | undefined | null,\n\topts?: AutoTrackOptions<T>,\n): Node<T> {\n\tlet implRef: NodeImpl<T>;\n\tconst depIndexMap = new Map<Node, number>();\n\tconst allowPartial = opts?.partial ?? false;\n\n\tconst wrappedFn: NodeFn = (batchData, actions, ctx) => {\n\t\tlet foundNew = false;\n\t\tconst track: TrackFn = (dep) => {\n\t\t\tconst idx = depIndexMap.get(dep);\n\t\t\tif (idx !== undefined) {\n\t\t\t\t// Known dep — return latest protocol-delivered value.\n\t\t\t\t// batch non-null+non-empty → latest from this wave;\n\t\t\t\t// otherwise fall back to ctx.prevData (last known value).\n\t\t\t\tif (idx < batchData.length) {\n\t\t\t\t\tconst batch = batchData[idx];\n\t\t\t\t\tif (batch != null && batch.length > 0) return batch.at(-1);\n\t\t\t\t\treturn ctx.prevData[idx];\n\t\t\t\t}\n\t\t\t\treturn dep.cache;\n\t\t\t}\n\t\t\t// Unknown dep — discovery phase.\n\t\t\tfoundNew = true;\n\t\t\tconst newIdx = implRef._addDep(dep);\n\t\t\tdepIndexMap.set(dep, newIdx);\n\t\t\treturn dep.cache; // P3 boundary exception (discovery stub)\n\t\t};\n\n\t\t// Sentinel guard (skipped when partial:true): if any known dep has never\n\t\t// delivered DATA (no DATA this wave AND ctx.prevData[idx] === undefined), emit RESOLVED\n\t\t// and defer. Mirrors derived()'s guard for the same sequential-handshake\n\t\t// scenario: when a node re-activates outside a batch and dep A delivers\n\t\t// synchronously before dep B is even subscribed, this holds fn until all\n\t\t// known deps have initialised rather than running with B=undefined.\n\t\t// Uses ctx.prevData[idx] === undefined — the protocol sentinel for\n\t\t// \"dep never sent DATA\". null is valid DATA and won't trigger this.\n\t\t// Only active when depIndexMap is non-empty (initial discovery runs are\n\t\t// unaffected) and when partial:false (default).\n\t\tif (!allowPartial && depIndexMap.size > 0) {\n\t\t\tfor (const [, idx] of depIndexMap) {\n\t\t\t\tif (idx < batchData.length) {\n\t\t\t\t\tconst batch = batchData[idx];\n\t\t\t\t\tif (!(batch != null && batch.length > 0) && ctx.prevData[idx] === undefined) {\n\t\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = fn(track, ctx);\n\t\t\tif (!foundNew) {\n\t\t\t\t// Real run — all deps known, protocol-delivered values.\n\t\t\t\tactions.emit(result);\n\t\t\t\t// Clear any stale discovery error from a prior run.\n\t\t\t\tif (ctx.store.__autoTrackLastDiscoveryError != null) {\n\t\t\t\t\tdelete ctx.store.__autoTrackLastDiscoveryError;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Discovery run — result discarded. New deps are subscribed via\n\t\t\t// _addDep. Their DATA delivery triggers _maybeRunFnOnSettlement\n\t\t\t// via the _pendingRerun mechanism, which will re-call fn.\n\t\t} catch (err) {\n\t\t\tif (!foundNew) throw err;\n\t\t\t// Discovery run threw — most likely a stale `.cache` read (P3\n\t\t\t// boundary exception), which the protocol-delivered retry will\n\t\t\t// not hit. Preserve the error on `ctx.store` for inspection; if\n\t\t\t// the retry succeeds, the flag is cleared above. If fn has a\n\t\t\t// real bug unrelated to cache, the non-discovery retry will\n\t\t\t// re-throw it out of `_execFn`.\n\t\t\tctx.store.__autoTrackLastDiscoveryError = err;\n\t\t}\n\t\treturn undefined;\n\t};\n\n\timplRef = new NodeImpl<T>([], wrappedFn, {\n\t\tdescribeKind: \"derived\",\n\t\t...opts,\n\t});\n\treturn implRef;\n}\n\n// ---------------------------------------------------------------------------\n// pipe — left-to-right operator composition\n// ---------------------------------------------------------------------------\n\n/** Unary operator used by {@link pipe}. */\nexport type PipeOperator = (n: Node) => Node;\n\n/**\n * Composes unary operators left-to-right; returns the final node.\n *\n * @example\n * ```ts\n * const out = pipe(\n * source,\n * (n) => map(n, (x) => x + 1),\n * (n) => filter(n, (x) => x > 0),\n * );\n * ```\n */\nexport function pipe(source: Node, ...ops: PipeOperator[]): Node {\n\tlet current = source;\n\tfor (const op of ops) current = op(current);\n\treturn current;\n}\n","/**\n * Creates a resettable deadline timer for internal timeout, retry, and rate-limiting use.\n *\n * @remarks **Centralised primitive:** wraps `setTimeout`/`clearTimeout` with a generation guard\n * so that stale callbacks never fire after `cancel()` or a new `start()`.\n *\n * @remarks **Spec §5.10 exception:** resilience operators (`timeout`, `retry`, `rateLimiter`)\n * need raw timers — `fromTimer` creates a new Node per reset, which is too heavy here.\n * Lives in `src/extra/` (not `src/core/`) because it is a documented escape hatch from\n * the protocol-pure core layer.\n *\n * @example\n * ```ts\n * import { ResettableTimer } from \"@graphrefly/graphrefly-ts\";\n *\n * const timer = new ResettableTimer();\n * timer.start(1000, () => console.log(\"fired\"));\n * timer.cancel(); // cancels before firing\n * timer.start(500, () => console.log(\"new deadline\"));\n * console.log(timer.pending); // true\n * ```\n *\n * @category extra\n */\nexport class ResettableTimer {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _gen = 0;\n\n\t/** Schedule callback after delayMs. Cancels any pending timer. */\n\tstart(delayMs: number, callback: () => void): void {\n\t\tthis.cancel();\n\t\tthis._gen += 1;\n\t\tconst gen = this._gen;\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tif (gen !== this._gen) return;\n\t\t\tcallback();\n\t\t}, delayMs);\n\t}\n\n\t/** Cancel the pending timer (if any). */\n\tcancel(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\t/** Whether a timer is currently pending. */\n\tget pending(): boolean {\n\t\treturn this._timer !== undefined;\n\t}\n}\n","/**\n * Fixed-capacity ring buffer — O(1) push and drop-oldest eviction.\n *\n * Used by `Graph._traceRing` (reasoning trace), `reactiveLog` (append-only\n * log backend), and `reactiveSink` (drop-oldest backpressure buffer). One\n * implementation, three use sites.\n *\n * @module\n * @internal\n */\n\n/**\n * Fixed-capacity ring buffer. Once `capacity` entries are stored, subsequent\n * `push` calls evict the oldest entry (drop-oldest / FIFO eviction).\n *\n * Operations:\n * - `push(item)` — O(1).\n * - `shift()` — O(1) remove oldest (returns `undefined` when empty).\n * - `at(i)` — O(1) index lookup, with Python-style negative indexing.\n * - `toArray()` — O(n) materialize in insertion order.\n * - `clear()` — O(1) reset to empty.\n *\n * Not thread-safe; JS semantics assumed (single-threaded within a sync call).\n */\nexport class RingBuffer<T> {\n\tprivate buf: (T | undefined)[];\n\tprivate head = 0;\n\tprivate _size = 0;\n\n\tconstructor(private capacity: number) {\n\t\tif (!Number.isInteger(capacity) || capacity <= 0) {\n\t\t\tthrow new Error(`RingBuffer capacity must be a positive integer (got ${capacity})`);\n\t\t}\n\t\tthis.buf = new Array(capacity);\n\t}\n\n\t/** Current number of stored entries. */\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\n\t/** Configured maximum before drop-oldest eviction fires. */\n\tget maxSize(): number {\n\t\treturn this.capacity;\n\t}\n\n\t/**\n\t * Append an item. If size equals capacity, drops the oldest entry and\n\t * advances the head pointer.\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\n\t/** Remove and return the oldest entry; `undefined` when empty. */\n\tshift(): T | undefined {\n\t\tif (this._size === 0) return undefined;\n\t\tconst item = this.buf[this.head];\n\t\tthis.buf[this.head] = undefined;\n\t\tthis.head = (this.head + 1) % this.capacity;\n\t\tthis._size--;\n\t\treturn item;\n\t}\n\n\t/**\n\t * O(1) index lookup. Negative indices count from the tail (Python-style).\n\t * Returns `undefined` for out-of-range.\n\t */\n\tat(i: number): T | undefined {\n\t\tif (this._size === 0) return undefined;\n\t\tconst n = i < 0 ? this._size + i : i;\n\t\tif (n < 0 || n >= this._size) return undefined;\n\t\treturn this.buf[(this.head + n) % this.capacity];\n\t}\n\n\t/**\n\t * Materialize the contents in insertion order (oldest → newest).\n\t * Returns a new array each call.\n\t */\n\ttoArray(): T[] {\n\t\tconst result: T[] = new Array(this._size);\n\t\tfor (let i = 0; i < this._size; i++) {\n\t\t\tresult[i] = this.buf[(this.head + i) % this.capacity]!;\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Reset to empty. Storage slots are released so held refs can GC. */\n\tclear(): void {\n\t\tfor (let i = 0; i < this._size; i++) {\n\t\t\tthis.buf[(this.head + i) % this.capacity] = undefined;\n\t\t}\n\t\tthis.head = 0;\n\t\tthis._size = 0;\n\t}\n}\n","/**\n * Graph profiling and inspection utilities.\n *\n * Provides per-node memory estimation, connectivity stats, and hotspot\n * detection. Non-invasive — reads from `describe()` and node internals\n * without modifying state.\n *\n * @module\n */\n\nimport { type Node, NodeImpl } from \"../core/node.js\";\nimport { sizeof } from \"../extra/utils/sizeof.js\";\nimport type { Graph, GraphDescribeOutput } from \"./graph.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Per-node profile entry. */\nexport interface NodeProfile {\n\t/** Qualified path within the graph. */\n\tpath: string;\n\t/** Node type (state, derived, producer, effect). */\n\ttype: string;\n\t/** Node status (disconnected, dirty, settled, errored, completed). */\n\tstatus: string;\n\t/** Approximate retained bytes for the node's cached value. */\n\tvalueSizeBytes: number;\n\t/** Number of downstream subscribers (sinks). */\n\tsubscriberCount: number;\n\t/** Number of upstream dependencies. */\n\tdepCount: number;\n\t/**\n\t * True if this is an effect node with no external subscribers — a classic\n\t * leak pattern. See {@link GraphProfileResult.orphans} for the broader\n\t * orphan-node detection across `derived` / `producer` / `effect`.\n\t */\n\tisOrphanEffect: boolean;\n\t/**\n\t * Orphan category (batch 8 Unit 13 D). `null` when the node is healthy.\n\t * - `\"orphan-effect\"` — effect with zero subscribers (pre-existing class).\n\t * - `\"idle-derived\"` — derived with zero subscribers (wasted compute path\n\t * if it ever activates; may indicate a factory forgot keepalive).\n\t * - `\"idle-producer\"` — producer with zero subscribers (no external\n\t * consumer; may be an over-eager factory or forgotten cleanup).\n\t */\n\torphanKind: \"orphan-effect\" | \"idle-derived\" | \"idle-producer\" | null;\n}\n\n/** Aggregate graph profile. */\nexport interface GraphProfileResult {\n\t/** Total node count. */\n\tnodeCount: number;\n\t/** Total edge count. */\n\tedgeCount: number;\n\t/** Subgraph count. */\n\tsubgraphCount: number;\n\t/** All node profiles. */\n\tnodes: NodeProfile[];\n\t/** Total approximate value memory across all nodes. */\n\ttotalValueSizeBytes: number;\n\t/**\n\t * Top-N hotspots by dimension. Each list is sorted descending. See\n\t * {@link GraphProfileOptions.topN} for the cap (default 10).\n\t */\n\thotspots: {\n\t\tbyValueSize: NodeProfile[];\n\t\tbySubscriberCount: NodeProfile[];\n\t\tbyDepCount: NodeProfile[];\n\t};\n\t/**\n\t * Every orphan across types — `effect`, `derived`, `producer` with zero\n\t * subscribers. See {@link NodeProfile.orphanKind} for category.\n\t */\n\torphans: NodeProfile[];\n\t/** Effect nodes with no external subscribers (legacy; subset of `orphans`). */\n\torphanEffects: NodeProfile[];\n}\n\n/** Options for {@link graphProfile}. */\nexport interface GraphProfileOptions {\n\t/** Limit hotspot list (default 10). */\n\ttopN?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Profile a graph's memory and connectivity characteristics.\n *\n * Uses `describe({ detail: \"standard\" })` for node metadata and direct\n * `NodeImpl` access for subscriber counts and cached values.\n *\n * @param graph - The graph to profile.\n * @param opts - Optional configuration.\n * @returns Aggregate profile with per-node details, hotspots (multi-dim), and orphans.\n */\nexport function graphProfile(graph: Graph, opts?: GraphProfileOptions): GraphProfileResult {\n\tconst topN = opts?.topN ?? 10;\n\n\tconst desc: GraphDescribeOutput = graph.describe({ detail: \"standard\" });\n\n\t// Build path→Node lookup via _collectObserveTargets (same as describe uses).\n\t// Runtime guard: if the internal method is missing (refactored), degrade\n\t// gracefully — profiles will show 0 for valueSizeBytes and subscriberCount.\n\tconst targets: [string, Node][] = [];\n\tconst collector = (\n\t\tgraph as unknown as { _collectObserveTargets?: (prefix: string, out: [string, Node][]) => void }\n\t)._collectObserveTargets;\n\tif (typeof collector === \"function\") {\n\t\tcollector.call(graph, \"\", targets);\n\t}\n\tconst pathToNode = new Map<string, Node>();\n\tfor (const [p, n] of targets) pathToNode.set(p, n);\n\n\tconst profiles: NodeProfile[] = [];\n\n\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\tconst nd = pathToNode.get(path);\n\t\tconst impl = nd instanceof NodeImpl ? nd : null;\n\n\t\tconst valueSizeBytes = impl ? sizeof(impl.cache) : 0;\n\t\tconst subscriberCount = impl ? impl._sinkCount : 0;\n\t\tconst depCount = nodeDesc.deps?.length ?? 0;\n\n\t\tconst isOrphanEffect = nodeDesc.type === \"effect\" && subscriberCount === 0;\n\t\tconst orphanKind: NodeProfile[\"orphanKind\"] =\n\t\t\tsubscriberCount === 0\n\t\t\t\t? nodeDesc.type === \"effect\"\n\t\t\t\t\t? \"orphan-effect\"\n\t\t\t\t\t: nodeDesc.type === \"derived\"\n\t\t\t\t\t\t? \"idle-derived\"\n\t\t\t\t\t\t: nodeDesc.type === \"producer\"\n\t\t\t\t\t\t\t? \"idle-producer\"\n\t\t\t\t\t\t\t: null\n\t\t\t\t: null;\n\n\t\tprofiles.push({\n\t\t\tpath,\n\t\t\ttype: nodeDesc.type,\n\t\t\tstatus: nodeDesc.status ?? \"unknown\",\n\t\t\tvalueSizeBytes,\n\t\t\tsubscriberCount,\n\t\t\tdepCount,\n\t\t\tisOrphanEffect,\n\t\t\torphanKind,\n\t\t});\n\t}\n\n\tconst totalValueSizeBytes = profiles.reduce((sum, p) => sum + p.valueSizeBytes, 0);\n\n\tconst topBy = <K extends keyof NodeProfile>(\n\t\tkey: K,\n\t\tcmp?: (a: NodeProfile, b: NodeProfile) => number,\n\t): NodeProfile[] =>\n\t\t[...profiles].sort(cmp ?? ((a, b) => (b[key] as number) - (a[key] as number))).slice(0, topN);\n\n\tconst orphans = profiles.filter((p) => p.orphanKind != null);\n\tconst orphanEffects = profiles.filter((p) => p.isOrphanEffect);\n\n\treturn {\n\t\tnodeCount: profiles.length,\n\t\tedgeCount: desc.edges.length,\n\t\tsubgraphCount: desc.subgraphs.length,\n\t\tnodes: profiles,\n\t\ttotalValueSizeBytes,\n\t\thotspots: {\n\t\t\tbyValueSize: topBy(\"valueSizeBytes\"),\n\t\t\tbySubscriberCount: topBy(\"subscriberCount\"),\n\t\t\tbyDepCount: topBy(\"depCount\"),\n\t\t},\n\t\torphans,\n\t\torphanEffects,\n\t};\n}\n","import type { Actor } from \"../core/actor.js\";\nimport { batch, isBatching } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport type { GraphReFlyConfig } from \"../core/config.js\";\nimport { GuardDenied } from \"../core/guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport {\n\ttype DescribeDetail,\n\ttype DescribeField,\n\ttype DescribeNodeOutput,\n\tdescribeNode,\n\tresolveDescribeFields,\n} from \"../core/meta.js\";\nimport {\n\tdefaultConfig,\n\ttype Node,\n\tNodeImpl,\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\";\nimport type { StorageHandle, StorageTier } from \"../extra/storage.js\";\nimport { ResettableTimer } from \"../extra/timer.js\";\nimport { RingBuffer } from \"../extra/utils/ring-buffer.js\";\nimport { decodeEnvelope, encodeEnvelope, type GraphCodec } from \"./codec.js\";\nimport { type GraphProfileOptions, type GraphProfileResult, graphProfile } from \"./profile.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/**\n * Options for {@link Graph}. Named fields documented below; the open index\n * signature is preserved so callers can stash extension data on the graph\n * without losing type discipline on the reserved names.\n *\n * - `config` — bind this graph to a specific {@link GraphReFlyConfig} for\n * tier/metaPassthrough/inspector lookups. Defaults to the singleton\n * `defaultConfig` exported from `core/node.ts`.\n * - `versioning` — convenience for `graph.setVersioning(level)` at\n * construction time. Monotonic bulk-apply; see {@link Graph.setVersioning}.\n * - `factories` — reserved for future per-graph factory registration;\n * currently factories flow through `Graph.fromSnapshot(data, {factories})`.\n */\nexport interface GraphOptions {\n\tconfig?: GraphReFlyConfig;\n\tversioning?: VersioningLevel;\n\tfactories?: Record<string, GraphNodeFactory>;\n\t/**\n\t * Capacity of the reasoning-trace ring buffer. Default: `1000`. Set lower\n\t * to reduce memory; higher for audit-heavy workloads. Set at construction\n\t * time — not mutable afterward (ring buffers can't resize cleanly).\n\t */\n\ttraceCapacity?: number;\n\t[key: string]: unknown;\n}\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/** Options for {@link Graph.describe} (Phase 3.3b progressive disclosure). */\nexport type GraphDescribeOptions = {\n\tactor?: Actor;\n\t/**\n\t * Node filter. Filters operate on whatever fields the chosen `detail` level\n\t * provides. For `metaHas` and `status` filters, use `detail: \"standard\"` or\n\t * higher — at `\"minimal\"` those fields are absent and the filter silently\n\t * excludes all nodes.\n\t */\n\tfilter?: DescribeFilter;\n\t/**\n\t * Detail level (Phase 3.3b). Default: `\"minimal\"`.\n\t * - `\"minimal\"` — type + deps only\n\t * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`)\n\t * - `\"full\"` — standard + guard, lastMutation\n\t */\n\tdetail?: DescribeDetail;\n\t/**\n\t * Explicit field selection (GraphQL-style). Overrides `detail` when provided.\n\t * Dotted paths like `\"meta.label\"` select specific meta keys.\n\t */\n\tfields?: DescribeField[];\n\t/**\n\t * Output format.\n\t * - `undefined` / omitted — return the full {@link GraphDescribeOutput} object.\n\t * - `\"spec\"` — GraphSpec input format (object; no status/value, deps as edges).\n\t * - `\"json\"` — stable JSON **text** with sorted keys.\n\t * - `\"pretty\"` — human-readable plaintext (optionally colorized; see\n\t * `colorize` / `indent` / `logger` / `includeEdges` / `includeSubgraphs`).\n\t * - `\"mermaid\"` — Mermaid flowchart text.\n\t * - `\"d2\"` — D2 diagram text.\n\t */\n\tformat?: \"spec\" | \"json\" | \"pretty\" | \"mermaid\" | \"d2\";\n\t/** Pretty/diagram render: direction for diagram formats (default `LR`). */\n\tdirection?: GraphDiagramDirection;\n\t/** Pretty/JSON render: indent (default 2 for JSON, ignored for pretty). */\n\tindent?: number;\n\t/** Pretty render: optional logger hook; fires with the rendered text before return. */\n\tlogger?: (text: string) => void;\n\t/** Pretty render: include an Edges section (default `true`). */\n\tincludeEdges?: boolean;\n\t/** Pretty render: include a Subgraphs section (default `true`). */\n\tincludeSubgraphs?: 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\t/**\n\t * Re-read the live graph with higher detail (Phase 3.3b).\n\t * Returns a new `GraphDescribeOutput`; the original remains a snapshot.\n\t * Present on live describe results; absent on deserialized snapshots.\n\t */\n\texpand?: (detailOrFields: DescribeDetail | DescribeField[]) => GraphDescribeOutput;\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.toObject},\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\n/**\n * Checkpoint record shape passed to `StorageTier.save`. Written by\n * {@link Graph.attachStorage} per-tier according to each tier's\n * `compactEvery` cadence.\n *\n * `mode: \"full\"` → full snapshot. Baseline anchor emitted on the first save\n * and every `compactEvery`-th save thereafter. Sufficient to recover state\n * on its own without WAL replay.\n * `mode: \"diff\"` → delta payload only, relative to this tier's most recent\n * `\"full\"` baseline. Between compacts. Wire-efficient; requires WAL replay\n * over the preceding `\"full\"` record to reconstruct state.\n *\n * Every record includes `seq` (per-tier monotonic counter), `timestamp_ns`\n * (wall-clock at flush time), and `format_version` (envelope version for\n * cross-version WAL replay).\n */\nexport type GraphCheckpointRecord = {\n\tseq: number;\n\ttimestamp_ns: number;\n\tformat_version: number;\n} & ({ mode: \"full\"; snapshot: GraphPersistSnapshot } | { mode: \"diff\"; diff: GraphWALDiff });\n\n/** Options for {@link Graph.attachStorage}. */\nexport type GraphAttachStorageOptions = {\n\t/**\n\t * Before the first save, attempt to restore from the first tier whose\n\t * `load(graph.name)` hits. Runs asynchronously in the background for\n\t * async tiers; errors surface via `onError`. Default `false`.\n\t */\n\tautoRestore?: boolean;\n\t/**\n\t * Limit the subscription surface (scoped observe). By default\n\t * `attachStorage` observes every node in the graph tree; on large graphs\n\t * that's thousands of subscriptions just for tier-gating. Pass a path\n\t * list (or a single glob) to observe only those nodes.\n\t */\n\tpaths?: readonly string[] | string;\n\t/** Pre-save path-level filter — skip records triggered by paths that fail this predicate. */\n\tfilter?: (name: string, described: DescribeNodeOutput) => boolean;\n\t/** Surfaced on tier save errors and autoRestore failures. */\n\tonError?: (error: unknown, tier: StorageTier) => 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 * Drain a disposer set iteratively — pop, remove, run. Disposers registered\n * mid-drain are picked up by the next iteration. Capped to guard against a\n * disposer that re-registers itself in an infinite loop. Exceptions are\n * surfaced via `console.error` rather than silently swallowed so leaks in\n * cleanup code remain visible.\n */\nfunction drainDisposers(set: Set<() => void>, graphName: string): void {\n\tconst cap = Math.max(16, set.size * 4);\n\tlet iterations = 0;\n\twhile (set.size > 0) {\n\t\tif (iterations++ >= cap) {\n\t\t\tconsole.error(\n\t\t\t\t`[Graph \"${graphName}\".destroy] disposer drain exceeded cap (${cap}); ${set.size} disposer(s) discarded`,\n\t\t\t);\n\t\t\tset.clear();\n\t\t\treturn;\n\t\t}\n\t\tconst it = set.values().next();\n\t\tif (it.done) return;\n\t\tconst dispose = it.value;\n\t\tset.delete(dispose);\n\t\ttry {\n\t\t\tdispose();\n\t\t} catch (err) {\n\t\t\tconsole.error(`[Graph \"${graphName}\".destroy] disposer threw:`, err);\n\t\t}\n\t}\n}\n\n/**\n * Cheap graph-level V0 version fingerprint: concatenate `v.id@v.version` for\n * every node that carries V0 info. Used by {@link Graph.attachStorage} to\n * short-circuit per-tier flushes when nothing versioned has changed since\n * the tier's last save. Non-versioned graphs produce an empty string so the\n * shortcut is a no-op for them (every scheduled flush writes).\n */\nfunction computeVersionFingerprint(nodes: Record<string, DescribeNodeOutput>): string {\n\tconst parts: string[] = [];\n\tfor (const path of Object.keys(nodes).sort()) {\n\t\tconst v = nodes[path]!.v;\n\t\tif (v != null) parts.push(`${path}\\t${v.id}\\t${v.version}`);\n\t}\n\treturn parts.join(\"\\n\");\n}\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/**\n * Structural deep equality — handles cycles, BigInt, Map, Set, Date, RegExp,\n * TypedArray, and nested objects/arrays. Used by `Graph.diff` to compare\n * node values without the cycle/BigInt/Map/Set footguns of `JSON.stringify`.\n *\n * Semantics: `Object.is` on primitives (so `NaN === NaN`, `-0 !== 0`), same\n * constructor required for object types, key-order-insensitive for plain\n * objects, order-sensitive for arrays + TypedArrays, unordered for Set,\n * key-equality for Map.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tconst seen = new WeakMap<object, WeakSet<object>>();\n\tconst walk = (x: unknown, y: unknown): boolean => {\n\t\tif (Object.is(x, y)) return true;\n\t\tif (x == null || y == null || typeof x !== \"object\" || typeof y !== \"object\") return false;\n\t\t// Cycle handling: assume equal on re-encounter (cycles match iff they\n\t\t// correspond structurally — standard \"optimistic\" deep-equal rule).\n\t\tlet seenRhs = seen.get(x as object);\n\t\tif (seenRhs == null) {\n\t\t\tseenRhs = new WeakSet();\n\t\t\tseen.set(x as object, seenRhs);\n\t\t}\n\t\tif (seenRhs.has(y as object)) return true;\n\t\tseenRhs.add(y as object);\n\n\t\tconst ctorA = (x as object).constructor;\n\t\tconst ctorB = (y as object).constructor;\n\t\tif (ctorA !== ctorB) return false;\n\n\t\tif (x instanceof Date) return (x as Date).getTime() === (y as Date).getTime();\n\t\tif (x instanceof RegExp)\n\t\t\treturn (\n\t\t\t\t(x as RegExp).source === (y as RegExp).source && (x as RegExp).flags === (y as RegExp).flags\n\t\t\t);\n\t\tif (Array.isArray(x)) {\n\t\t\tconst arrB = y as unknown[];\n\t\t\tif ((x as unknown[]).length !== arrB.length) return false;\n\t\t\tfor (let i = 0; i < (x as unknown[]).length; i++) {\n\t\t\t\tif (!walk((x as unknown[])[i], arrB[i])) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (x instanceof Map) {\n\t\t\tconst mB = y as Map<unknown, unknown>;\n\t\t\tif ((x as Map<unknown, unknown>).size !== mB.size) return false;\n\t\t\tfor (const [k, v] of x as Map<unknown, unknown>) {\n\t\t\t\tif (!mB.has(k) || !walk(v, mB.get(k))) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (x instanceof Set) {\n\t\t\tconst sB = y as Set<unknown>;\n\t\t\tif ((x as Set<unknown>).size !== sB.size) return false;\n\t\t\t// O(n²) fallback — Sets have no ordering, and walking each pair\n\t\t\t// is the only way to support structural equality on non-primitive\n\t\t\t// members. Acceptable: diff scale is describe-output-sized.\n\t\t\tfor (const v of x as Set<unknown>) {\n\t\t\t\tlet found = false;\n\t\t\t\tfor (const w of sB) {\n\t\t\t\t\tif (walk(v, w)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (ArrayBuffer.isView(x)) {\n\t\t\tconst taA = x as unknown as { length: number; [i: number]: number };\n\t\t\tconst taB = y as unknown as { length: number; [i: number]: number };\n\t\t\tif (taA.length !== taB.length) return false;\n\t\t\tfor (let i = 0; i < taA.length; i++) if (taA[i] !== taB[i]) return false;\n\t\t\treturn true;\n\t\t}\n\t\t// Plain object: same key-set, same values (key order irrelevant).\n\t\tconst keysA = Object.keys(x as Record<string, unknown>);\n\t\tconst keysB = Object.keys(y as Record<string, unknown>);\n\t\tif (keysA.length !== keysB.length) return false;\n\t\tconst setB = new Set(keysB);\n\t\tfor (const k of keysA) {\n\t\t\tif (!setB.has(k)) return false;\n\t\t\tif (!walk((x as Record<string, unknown>)[k], (y as Record<string, unknown>)[k])) return false;\n\t\t}\n\t\treturn true;\n\t};\n\treturn walk(a, b);\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 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\n// ---------------------------------------------------------------------------\n// describe({format}) renderers — consolidated from the ex-dumpGraph /\n// ex-toMermaid / ex-toD2 methods (Unit 12 + Unit 20).\n// ---------------------------------------------------------------------------\n\nfunction renderDescribeAsJson(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst includeEdges = options.includeEdges ?? true;\n\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\tconst { expand: _expand, ...rest } = d;\n\tconst payload: GraphDescribeOutput = {\n\t\t...rest,\n\t\tedges: includeEdges ? d.edges : [],\n\t\tsubgraphs: includeSubgraphs ? d.subgraphs : [],\n\t};\n\tconst text = JSON.stringify(sortJsonValue(payload), null, options.indent ?? 2);\n\toptions.logger?.(text);\n\treturn text;\n}\n\nfunction renderDescribeAsPretty(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst includeEdges = options.includeEdges ?? true;\n\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\tconst lines: string[] = [];\n\tlines.push(`Graph ${d.name}`);\n\tlines.push(\"Nodes:\");\n\tfor (const path of Object.keys(d.nodes).sort()) {\n\t\tconst n = d.nodes[path]!;\n\t\tlines.push(`- ${path} (${n.type}/${n.status}): ${describeData(n.value)}`);\n\t}\n\tif (includeEdges) {\n\t\tlines.push(\"Edges:\");\n\t\tfor (const edge of d.edges) {\n\t\t\tlines.push(`- ${edge.from} -> ${edge.to}`);\n\t\t}\n\t}\n\tif (includeSubgraphs) {\n\t\tlines.push(\"Subgraphs:\");\n\t\tfor (const sg of d.subgraphs) {\n\t\t\tlines.push(`- ${sg}`);\n\t\t}\n\t}\n\tconst text = lines.join(\"\\n\");\n\toptions.logger?.(text);\n\treturn text;\n}\n\nfunction renderDescribeAsMermaid(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst direction = normalizeDiagramDirection(options.direction);\n\tconst paths = Object.keys(d.nodes).sort();\n\tconst ids = new Map<string, string>();\n\tfor (let i = 0; i < paths.length; i += 1) ids.set(paths[i]!, `n${i}`);\n\tconst lines: string[] = [`flowchart ${direction}`];\n\tfor (const path of paths) {\n\t\tconst id = ids.get(path)!;\n\t\tlines.push(` ${id}[\"${escapeMermaidLabel(path)}\"]`);\n\t}\n\tfor (const [from, to] of collectDiagramArrows(d)) {\n\t\tconst fromId = ids.get(from);\n\t\tconst toId = ids.get(to);\n\t\tif (!fromId || !toId) continue;\n\t\tlines.push(` ${fromId} --> ${toId}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction renderDescribeAsD2(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst direction = normalizeDiagramDirection(options.direction);\n\tconst paths = Object.keys(d.nodes).sort();\n\tconst ids = new Map<string, string>();\n\tfor (let i = 0; i < paths.length; i += 1) ids.set(paths[i]!, `n${i}`);\n\tconst lines: string[] = [`direction: ${d2DirectionFromGraphDirection(direction)}`];\n\tfor (const path of paths) {\n\t\tconst id = ids.get(path)!;\n\t\tlines.push(`${id}: \"${escapeD2Label(path)}\"`);\n\t}\n\tfor (const [from, to] of collectDiagramArrows(d)) {\n\t\tconst fromId = ids.get(from);\n\t\tconst toId = ids.get(to);\n\t\tif (!fromId || !toId) continue;\n\t\tlines.push(`${fromId} -> ${toId}`);\n\t}\n\treturn lines.join(\"\\n\");\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\nconst OBSERVE_ANSI_THEME: Required<ObserveTheme> = {\n\tdata: \"\\u001b[32m\",\n\tdirty: \"\\u001b[33m\",\n\tresolved: \"\\u001b[36m\",\n\tinvalidate: \"\\u001b[93m\",\n\tpause: \"\\u001b[90m\",\n\tresume: \"\\u001b[96m\",\n\tcomplete: \"\\u001b[34m\",\n\terror: \"\\u001b[31m\",\n\tteardown: \"\\u001b[91m\",\n\tderived: \"\\u001b[35m\",\n\tpath: \"\\u001b[90m\",\n\treset: \"\\u001b[0m\",\n};\n\nconst OBSERVE_NO_COLOR_THEME: Required<ObserveTheme> = {\n\tdata: \"\",\n\tdirty: \"\",\n\tresolved: \"\",\n\tinvalidate: \"\",\n\tpause: \"\",\n\tresume: \"\",\n\tcomplete: \"\",\n\terror: \"\",\n\tteardown: \"\",\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 resolveObserveTheme(theme: ObserveOptions[\"theme\"]): Required<ObserveTheme> {\n\tif (theme === \"none\") return OBSERVE_NO_COLOR_THEME;\n\tif (theme === \"ansi\" || theme == null) return OBSERVE_ANSI_THEME;\n\treturn {\n\t\tdata: theme.data ?? \"\",\n\t\tdirty: theme.dirty ?? \"\",\n\t\tresolved: theme.resolved ?? \"\",\n\t\tinvalidate: theme.invalidate ?? \"\",\n\t\tpause: theme.pause ?? \"\",\n\t\tresume: theme.resume ?? \"\",\n\t\tcomplete: theme.complete ?? \"\",\n\t\terror: theme.error ?? \"\",\n\t\tteardown: theme.teardown ?? \"\",\n\t\tderived: theme.derived ?? \"\",\n\t\tpath: theme.path ?? \"\",\n\t\treset: theme.reset ?? \"\",\n\t};\n}\n\n/** Resolve observe `detail` level into effective boolean flags. */\nfunction resolveObserveDetail(opts?: ObserveOptions): ObserveOptions {\n\tif (opts == null) return {};\n\tconst detail = opts.detail;\n\tif (detail === \"full\") {\n\t\treturn {\n\t\t\t...opts,\n\t\t\tstructured: opts.structured ?? true,\n\t\t\ttimeline: opts.timeline ?? true,\n\t\t\tcausal: opts.causal ?? true,\n\t\t\tderived: opts.derived ?? true,\n\t\t};\n\t}\n\tif (detail === \"minimal\") {\n\t\treturn { ...opts, structured: opts.structured ?? true };\n\t}\n\treturn opts;\n}\n\n/**\n * Option shapes that trigger structured-mode dispatch in {@link Graph.observe}.\n * Presence of any of these fields (truthy) → returns {@link ObserveResult};\n * otherwise `observe()` returns the raw-stream variants.\n */\nexport type StructuredTriggers = {\n\tstructured?: true;\n\ttimeline?: true;\n\tcausal?: true;\n\tderived?: true;\n\tformat?: \"pretty\" | \"json\";\n\tdetail?: \"minimal\" | \"full\";\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/**\n * Detail level for `observe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — DATA events only, no timestamps, no causal info.\n * - `\"standard\"` — all message types (DATA, DIRTY, RESOLVED, INVALIDATE,\n * PAUSE, RESUME, COMPLETE, ERROR, TEARDOWN).\n * - `\"full\"` — standard + timeline + causal + derived.\n */\nexport type ObserveDetail = \"minimal\" | \"standard\" | \"full\";\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\t/**\n\t * Detail level (Phase 3.3b). Individual flags (`causal`, `timeline`, `derived`)\n\t * override. `\"full\"` implies all three plus structured.\n\t * `\"minimal\"` filters to DATA-only events.\n\t */\n\tdetail?: ObserveDetail;\n\n\t// ——— Format / logging (merged from spy) ———\n\n\t/**\n\t * When set, auto-enables structured mode and attaches a logger.\n\t * `\"pretty\"` renders colored one-line output; `\"json\"` emits one JSON object per event.\n\t */\n\tformat?: \"pretty\" | \"json\";\n\t/** Sink for rendered lines (`console.log` by default). Only used when `format` is set. */\n\tlogger?: (line: string, event: ObserveEvent) => void;\n\t/** Keep only these event types in formatted output. Only used when `format` is set. */\n\tincludeTypes?: ObserveEvent[\"type\"][];\n\t/** Exclude these event types from formatted output. Only used when `format` is set. */\n\texcludeTypes?: ObserveEvent[\"type\"][];\n\t/** Built-in color preset (`ansi` default) or explicit color tokens. Only used when `format` is set. */\n\ttheme?: ObserveThemeName | ObserveTheme;\n\t/**\n\t * Cap the `events` buffer. When set, the result uses a {@link RingBuffer}\n\t * under the hood: oldest events are dropped on overflow. Unbounded when\n\t * omitted (default).\n\t */\n\tmaxEvents?: number;\n};\n\n/** Accumulated observation result (structured mode). */\nexport type ObserveResult<T = unknown> = AsyncIterable<ObserveEvent> & {\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/** Number of INVALIDATE messages received (tier 1 cache-clear). */\n\treadonly invalidateCount: number;\n\t/** Number of PAUSE messages received (tier 2 backpressure). */\n\treadonly pauseCount: number;\n\t/** Number of RESUME messages received (tier 2 backpressure). */\n\treadonly resumeCount: number;\n\t/** Number of TEARDOWN messages received (tier 5 permanent cleanup). */\n\treadonly teardownCount: number;\n\t/**\n\t * All events in order — ring-buffered when `options.maxEvents` is set,\n\t * unbounded otherwise. Always materialized as an `ObserveEvent[]`\n\t * snapshot on read.\n\t */\n\treadonly events: ObserveEvent[];\n\t/** True if any observed node sent COMPLETE without prior ERROR on that node. */\n\treadonly anyCompletedCleanly: boolean;\n\t/** True if any observed node sent ERROR. */\n\treadonly anyErrored: boolean;\n\t/** True if at least one COMPLETE received and no ERROR from any observed node. */\n\treadonly completedWithoutErrors: boolean;\n\t/**\n\t * Attach a live listener that fires for each event as it arrives.\n\t * Returns an unsubscribe fn. Independent of the `events` buffer.\n\t */\n\tonEvent(listener: (event: ObserveEvent) => void): () => void;\n\t/** Stop observing. */\n\tdispose(): void;\n\t/**\n\t * Resubscribe with higher detail (Phase 3.3b).\n\t * Disposes current observation, returns new `ObserveResult` with merged options.\n\t */\n\texpand(\n\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t): ObserveResult<T>;\n};\n\n/** Fields common to every {@link ObserveEvent} variant. */\nexport interface ObserveEventBase {\n\tpath?: string;\n\t/** Optional `timeline` context — wall-clock when `options.timeline === true`. */\n\ttimestamp_ns?: number;\n\tin_batch?: boolean;\n\t/** Monotonically increasing counter per subscribe-callback invocation. All events in one delivery share the same id. */\n\tbatch_id?: number;\n}\n\n/** Optional `causal` context present on `data`/`resolved`/`derived` events. */\nexport interface ObserveCausalContext {\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\t/**\n\t * One scalar per dep: the last value that arrived in the current wave,\n\t * or the pre-wave cached value for deps that didn't fire. Convenient\n\t * for single-value-wave tooling (the common case).\n\t */\n\tdep_values?: unknown[];\n\t/**\n\t * Full per-dep batches for the wave that fired the fn — `dep_batches[i]`\n\t * is the array of values dep `i` delivered this wave (`undefined` for\n\t * deps that didn't fire). Use this to distinguish a single-value wave\n\t * from a multi-value wave; `dep_values` compresses each batch to its\n\t * last element and hides that difference.\n\t */\n\tdep_batches?: ReadonlyArray<ReadonlyArray<unknown> | undefined>;\n}\n\n/** A single event in the structured observation log (discriminated on `type`). */\nexport type ObserveEvent =\n\t| (ObserveEventBase & ObserveCausalContext & { type: \"data\"; data: unknown })\n\t| (ObserveEventBase & { type: \"dirty\" })\n\t| (ObserveEventBase & ObserveCausalContext & { type: \"resolved\" })\n\t| (ObserveEventBase & { type: \"invalidate\" })\n\t| (ObserveEventBase & { type: \"pause\"; lockId: unknown })\n\t| (ObserveEventBase & { type: \"resume\"; lockId: unknown })\n\t| (ObserveEventBase & { type: \"complete\" })\n\t| (ObserveEventBase & { type: \"error\"; data: unknown })\n\t| (ObserveEventBase & { type: \"teardown\" })\n\t| (ObserveEventBase & ObserveCausalContext & { type: \"derived\"; dep_values: unknown[] });\n\n/** Built-in color preset names for observe `format` rendering. */\nexport type ObserveThemeName = \"none\" | \"ansi\";\n\n/** ANSI/style overrides for observe `format` event rendering. */\nexport type ObserveTheme = Partial<Record<ObserveEvent[\"type\"] | \"path\" | \"reset\", string>>;\n\n/**\n * Reject characters that would collide with internal serialization or path\n * grammar. Control chars (0x00–0x1F, 0x7F) break `describe()` key stability,\n * diagram rendering, and any tab-delimited log/trace format. Keep the test\n * tight so the error message points at the first offending code point.\n */\nfunction assertNoControlChars(name: string, graphName: string, label: string): void {\n\tfor (let i = 0; i < name.length; i++) {\n\t\tconst c = name.charCodeAt(i);\n\t\tif (c < 0x20 || c === 0x7f) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${graphName}\": ${label} \"${name}\" must not contain control character (U+${c.toString(16).padStart(4, \"0\").toUpperCase()} at index ${i})`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Validate a registerable local name (`add`, `mount`, `remove` inputs):\n * non-empty, no `::` separator, not the reserved `__meta__` segment, and no\n * control characters.\n */\nfunction assertRegisterableName(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\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\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\tassertNoControlChars(name, graphName, label);\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/**\n * Strip messages that are not marked `metaPassthrough` on the given config\n * (spec §2.3 Companion lifecycle). Built-ins: `INVALIDATE`, `COMPLETE`,\n * `ERROR`, `TEARDOWN` are registered `metaPassthrough: false` in\n * `registerBuiltins`. Custom types default to `true` (meta receives them).\n *\n * To target a meta node directly without the filter, call `meta.down(...)`.\n *\n * Returns empty array when nothing remains.\n */\nfunction filterMetaMessages(messages: Messages, config: GraphReFlyConfig): Messages {\n\t// Fast path: if every message is metaPassthrough, reuse the input array.\n\tlet anyFiltered = false;\n\tfor (const m of messages) {\n\t\tif (!config.isMetaPassthrough(m[0])) {\n\t\t\tanyFiltered = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!anyFiltered) return messages;\n\tconst kept = messages.filter((m) => config.isMetaPassthrough(m[0]));\n\treturn kept as unknown as Messages;\n}\n\n/**\n * TEARDOWN every node in a mounted graph tree (depth-first into mounts).\n * Errors from individual node teardowns are swallowed — a single bad handler\n * must not abort cleanup of the rest of the subtree.\n */\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\ttry {\n\t\t\tn.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\t} catch {\n\t\t\t/* resilience: keep tearing down siblings */\n\t\t}\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\treadonly name: string;\n\treadonly opts: Readonly<GraphOptions>;\n\t/** Protocol config bound to this graph (defaults to `defaultConfig`). */\n\treadonly config: GraphReFlyConfig;\n\t/** @internal — exposed for {@link teardownMountedGraph} and cross-graph helpers. */\n\treadonly _nodes = new Map<string, Node>();\n\t/**\n\t * @internal Reverse lookup for duplicate-instance detection in\n\t * {@link Graph.add} — O(1) replacement for an O(n) scan of `_nodes`.\n\t * Weak so nodes can be GC'd after `remove()` even if a caller keeps the\n\t * map alive via some unusual pattern.\n\t */\n\tprivate readonly _nodeToName = new WeakMap<Node, string>();\n\t/** @internal — exposed for {@link teardownMountedGraph}. */\n\treadonly _mounts = new Map<string, Graph>();\n\t/**\n\t * @internal Parent graph if this instance is mounted. `undefined` when\n\t * this is the root or when the graph has been unmounted. Used for\n\t * reparenting rejection + O(depth) ancestor walks.\n\t */\n\t_parent: Graph | undefined = undefined;\n\tprivate readonly _storageDisposers = new Set<() => void>();\n\tprivate readonly _disposers = new Set<() => void>();\n\n\t/**\n\t * @param name - Non-empty graph id (must not contain `::` and must not\n\t * equal the reserved meta segment `__meta__`).\n\t * @param opts - See {@link GraphOptions}. Stored frozen on the instance.\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\tif (name === GRAPH_META_SEGMENT) {\n\t\t\tthrow new Error(`Graph name \"${GRAPH_META_SEGMENT}\" is reserved for meta companion paths`);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.opts = Object.freeze({ ...(opts ?? {}) });\n\t\tthis.config = opts?.config ?? defaultConfig;\n\t\tthis._traceRing = new RingBuffer<TraceEntry>(opts?.traceCapacity ?? 1000);\n\t\tif (opts?.versioning != null) {\n\t\t\t// No nodes yet, but keep the API consistent — apply at construction\n\t\t\t// so opts.versioning is honored as a startup default via this helper.\n\t\t\tthis.setVersioning(opts.versioning);\n\t\t}\n\t}\n\n\t/**\n\t * Walk ancestors up through `_parent`. Returns the chain starting at this\n\t * instance, ending at the root (a graph with no parent). O(depth).\n\t *\n\t * @param includeSelf - Include `this` in the chain (default `true`).\n\t */\n\tancestors(includeSelf = true): Graph[] {\n\t\tconst out: Graph[] = [];\n\t\tlet p: Graph | undefined = includeSelf ? this : this._parent;\n\t\twhile (p != null) {\n\t\t\tout.push(p);\n\t\t\tp = p._parent;\n\t\t}\n\t\treturn out;\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, the same node instance is already registered, or\n\t * the node is torn down.\n\t *\n\t * Returns the registered node so callers can chain:\n\t * `const counter = g.add(\"counter\", state(0))`.\n\t *\n\t * @param name - Local key (no `::`).\n\t * @param node - Node instance to own.\n\t */\n\tadd<T extends Node>(name: string, node: T): T {\n\t\tassertRegisterableName(name, this.name, \"add\");\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\tconst existingName = this._nodeToName.get(node);\n\t\tif (existingName !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": node instance already registered as \"${existingName}\"`,\n\t\t\t);\n\t\t}\n\t\tthis._nodes.set(name, node);\n\t\tthis._nodeToName.set(node, name);\n\t\t// Edges are derived on demand from node `_deps` (see `edges()`) — no\n\t\t// stored registry to keep in sync. See Unit 7 of the graph review.\n\t\treturn node;\n\t}\n\n\t/**\n\t * Bulk-apply a minimum versioning level to every currently-registered node\n\t * in this graph (roadmap §6.0). `_applyVersioning` is monotonic — nodes\n\t * already at a higher level are untouched. The method refuses to run\n\t * mid-wave; invoke at setup time before any external subscribers attach.\n\t *\n\t * **Not** a default-for-future-adds mechanism — that's what\n\t * `config.defaultVersioning` is for. Nodes added after this call do NOT\n\t * automatically inherit `level`; register new nodes with their own\n\t * `opts.versioning` or set `config.defaultVersioning` before construction.\n\t *\n\t * **Scope:** local only. Does not propagate to mounted subgraphs.\n\t *\n\t * @param level - `0` for V0, `1` for V1, or `undefined` to no-op.\n\t */\n\tsetVersioning(level: VersioningLevel | undefined): void {\n\t\tif (level == null) return;\n\t\tfor (const node of this._nodes.values()) {\n\t\t\tif (node instanceof NodeImpl) {\n\t\t\t\tnode._applyVersioning(level);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters a node or unmounts a subgraph and sends `[[TEARDOWN]]` to the\n\t * removed node or recursively through the mounted subtree (§3.2).\n\t *\n\t * @param name - Local mount or node name.\n\t * @returns Audit record of what was removed: `{kind, nodes, mounts}`.\n\t * `kind: \"node\"` → `nodes: [name]`, `mounts: []`. `kind: \"mount\"` →\n\t * `nodes` lists every primary node torn down across the subtree (sorted\n\t * qualified paths relative to the unmounted subgraph) and `mounts` lists\n\t * the mounted subgraphs in depth-first order including `name` itself.\n\t */\n\tremove(name: string): GraphRemoveAudit {\n\t\tassertRegisterableName(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\tconst audit: GraphRemoveAudit = { kind: \"mount\", nodes: [], mounts: [] };\n\t\t\tconst targets: [string, Node][] = [];\n\t\t\tchild._collectObserveTargets(\"\", targets);\n\t\t\tfor (const [p, n] of targets) {\n\t\t\t\t// Only primary nodes (not meta companions) — meta cascades via\n\t\t\t\t// the primary's TEARDOWN.\n\t\t\t\tif (!p.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`)) {\n\t\t\t\t\taudit.nodes.push(p);\n\t\t\t\t}\n\t\t\t\tvoid n;\n\t\t\t}\n\t\t\taudit.nodes.sort();\n\t\t\taudit.mounts.push(name);\n\t\t\taudit.mounts.push(...child._collectSubgraphs(`${name}${PATH_SEP}`));\n\t\t\tthis._mounts.delete(name);\n\t\t\tchild._parent = undefined;\n\t\t\tteardownMountedGraph(child);\n\t\t\treturn audit;\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\tthis._nodeToName.delete(node);\n\t\tnode.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\treturn { kind: \"node\", nodes: [name], mounts: [] };\n\t}\n\n\t/**\n\t * Bulk remove — invokes {@link Graph.remove} for every local name matching\n\t * `filter`. Audit records merge into a single result. Mounted subgraphs\n\t * are included via `filter` receiving the mount name; internal subtree\n\t * entries are not walked directly (use describe + scan for tree-level\n\t * queries).\n\t *\n\t * @param filter - Predicate or glob. Glob strings support `*` within a\n\t * segment and `**` across segments (same grammar as `restore({only})`).\n\t * @returns Combined audit of all nodes + mounts removed.\n\t */\n\tremoveAll(filter: ((name: string) => boolean) | string): GraphRemoveAudit {\n\t\tconst match =\n\t\t\ttypeof filter === \"function\"\n\t\t\t\t? filter\n\t\t\t\t: (() => {\n\t\t\t\t\t\tconst re = globToRegex(filter);\n\t\t\t\t\t\treturn (n: string) => re.test(n);\n\t\t\t\t\t})();\n\t\tconst audit: GraphRemoveAudit = { kind: \"mount\", nodes: [], mounts: [] };\n\t\t// Snapshot names first — remove mutates the maps.\n\t\tconst localNames = [...this._nodes.keys(), ...this._mounts.keys()].filter((n) => match(n));\n\t\tfor (const name of localNames) {\n\t\t\tconst sub = this.remove(name);\n\t\t\taudit.nodes.push(...sub.nodes);\n\t\t\taudit.mounts.push(...sub.mounts);\n\t\t}\n\t\taudit.nodes.sort();\n\t\taudit.mounts.sort();\n\t\treturn audit;\n\t}\n\n\t/**\n\t * Iterable over locally-registered `[localName, Node]` pairs (sorted).\n\t * Does not recurse into mounts.\n\t */\n\t[Symbol.iterator](): IterableIterator<[string, Node]> {\n\t\tconst sorted = [...this._nodes.keys()].sort();\n\t\tconst nodes = this._nodes;\n\t\tlet i = 0;\n\t\treturn {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tnext(): IteratorResult<[string, Node]> {\n\t\t\t\tif (i >= sorted.length) return { value: undefined, done: true };\n\t\t\t\tconst name = sorted[i++];\n\t\t\t\treturn { value: [name, nodes.get(name)!], done: false };\n\t\t\t},\n\t\t};\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).cache;\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 * Atomic multi-node DATA write. Wraps every {@link Graph.set} call in a\n\t * single `batch(...)` so downstream dependents see one coalesced wave\n\t * instead of N cascading ones.\n\t *\n\t * @param entries - `{name → value}` map or `[name, value]` pairs.\n\t * @param options - Passed to each underlying `set` call (same `actor` + `internal` semantics).\n\t */\n\tsetAll(\n\t\tentries: Record<string, unknown> | Iterable<readonly [string, unknown]>,\n\t\toptions?: GraphActorOptions,\n\t): void {\n\t\tconst iter: Iterable<readonly [string, unknown]> =\n\t\t\tSymbol.iterator in entries\n\t\t\t\t? (entries as Iterable<readonly [string, unknown]>)\n\t\t\t\t: Object.entries(entries as Record<string, unknown>);\n\t\tbatch(() => {\n\t\t\tfor (const [name, value] of iter) this.set(name, value, options);\n\t\t});\n\t}\n\n\t/**\n\t * Emit a single `[[INVALIDATE]]` (tier 1) on a node. Thin wrapper over\n\t * `node.down([[INVALIDATE]], …)` matching the {@link Graph.set} ergonomics.\n\t */\n\tinvalidate(name: string, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[INVALIDATE]] 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 * Emit a single `[[ERROR, err]]` (tier 4) on a node.\n\t */\n\terror(name: string, err: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[ERROR, err]] 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 * Emit a single `[[COMPLETE]]` (tier 4) on a node, declaring the stream\n\t * cleanly finished. Distinct from {@link Graph.remove} (which emits\n\t * TEARDOWN and unregisters the node).\n\t */\n\tcomplete(name: string, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[COMPLETE]] 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 (derived on-demand from node `_deps`)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Returns the full edge list for this graph tree, derived on demand from\n\t * each registered node's `_deps` (no stored registry). Local-only\n\t * (non-recursive) by default to match the historical `edges()` surface;\n\t * pass `{recursive: true}` to include mounted subgraphs with qualified\n\t * paths relative to this graph.\n\t *\n\t * Use {@link Graph.describe} for full-tree snapshots with edges already\n\t * qualified and paired with node metadata.\n\t */\n\tedges(opts?: { recursive?: boolean }): ReadonlyArray<[string, string]> {\n\t\tconst recursive = opts?.recursive === true;\n\t\tconst nodeToLocal = new Map<Node, string>();\n\t\tif (!recursive) {\n\t\t\tfor (const [localName, n] of this._nodes) nodeToLocal.set(n, localName);\n\t\t\tconst result: [string, string][] = [];\n\t\t\tfor (const [localName, n] of this._nodes) {\n\t\t\t\tif (!(n instanceof NodeImpl)) continue;\n\t\t\t\tfor (const dep of n._deps) {\n\t\t\t\t\tconst from = nodeToLocal.get(dep.node);\n\t\t\t\t\tif (from != null) result.push([from, localName]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult.sort((a, b) =>\n\t\t\t\ta[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0,\n\t\t\t);\n\t\t\treturn result;\n\t\t}\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) nodeToPath.set(n, p);\n\t\tconst result: [string, string][] = [];\n\t\tfor (const [path, n] of targets) {\n\t\t\tif (!(n instanceof NodeImpl)) continue;\n\t\t\tfor (const dep of n._deps) {\n\t\t\t\tconst from = nodeToPath.get(dep.node);\n\t\t\t\tif (from != null) result.push([from, path]);\n\t\t\t}\n\t\t}\n\t\tresult.sort((a, b) =>\n\t\t\ta[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0,\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 * @returns The mounted `child`, for chaining.\n\t */\n\tmount<G extends Graph>(name: string, child: G): G {\n\t\tassertRegisterableName(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 as Graph) === this) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot mount a graph into itself`);\n\t\t}\n\t\t// Reject reparenting (Unit 6 B): same child instance may only be\n\t\t// mounted once across the entire tree. Cheap O(1) check via the\n\t\t// back-pointer (replaces both the \"mounted twice on this parent\"\n\t\t// loop AND the O(G) cycle DFS).\n\t\tif (child._parent != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": this child graph is already mounted on \"${child._parent.name}\"`,\n\t\t\t);\n\t\t}\n\t\t// Cycle rejection — walk UP from `this` to detect if we are already in\n\t\t// `child`'s descendant tree. O(depth), independent of tree size.\n\t\tfor (let p: Graph | undefined = this; p != null; p = p._parent) {\n\t\t\tif (p === (child as Graph)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": mount(\"${name}\", …) would create a mount cycle`);\n\t\t\t}\n\t\t}\n\t\tthis._mounts.set(name, child);\n\t\tchild._parent = this;\n\t\treturn 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\"`). The strip\n\t * is applied **recursively** when descending into mounted children, so\n\t * `child.resolve(\"child::x\")` also works when `child.name === \"child\"`.\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\tconst segments = splitPath(path, this.name);\n\t\treturn this._resolveFromSegments(segments);\n\t}\n\n\t/**\n\t * Non-throwing {@link Graph.resolve}. Returns `undefined` instead of\n\t * throwing when the path does not resolve to a node.\n\t */\n\ttryResolve(path: string): Node | undefined {\n\t\ttry {\n\t\t\treturn this.resolve(path);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate _resolveFromSegments(segments: readonly string[]): Node {\n\t\t// Recursive self-name strip: if the first segment equals this graph's\n\t\t// own name, peel it off. Applied at every recursion level so nested\n\t\t// resolution of `child::x` inside `child` works uniformly.\n\t\tlet seg = segments;\n\t\tif (seg[0] === this.name) {\n\t\t\tseg = seg.slice(1);\n\t\t\tif (seg.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\tconst head = seg[0] as string;\n\t\tconst rest = seg.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, seg.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\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 * **Primary-vs-meta filter asymmetry (intentional):** primary nodes receive the\n\t * unfiltered `messages` batch — that's the canonical data-plane flow. Companion\n\t * `meta` nodes receive a filtered subset keyed by the per-type `metaPassthrough`\n\t * flag on {@link GraphReFlyConfig}. Built-in defaults: PAUSE / RESUME / DATA /\n\t * RESOLVED pass through to meta; INVALIDATE / COMPLETE / ERROR / TEARDOWN do\n\t * not.\n\t *\n\t * **Where lifecycle terminals reach meta:**\n\t * - **TEARDOWN** — primary's `_emit` cascades to meta children directly (see\n\t * `core/node.ts` \"Meta TEARDOWN fan-out\" block) so meta is torn down with\n\t * its primary regardless of the signal-level filter.\n\t * - **COMPLETE / ERROR / INVALIDATE** — scoped to primaries on the broadcast\n\t * path. Meta companions are an attribution side-channel, not a lifecycle\n\t * participant; address meta directly via `meta.down(...)` if you need to\n\t * forward these. Audit confirmed 2026-04-17: no current meta consumer\n\t * relies on broadcast COMPLETE/ERROR/INVALIDATE delivery.\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\t// Reject tier ≥ 3 (DATA / RESOLVED / COMPLETE / ERROR / TEARDOWN when\n\t\t// called externally — destroy() routes through signal with\n\t\t// `{internal: true}` which bypasses this check). Broadcasting per-flow\n\t\t// values to every node in the tree is almost always a mistake.\n\t\tif (options?.internal !== true) {\n\t\t\tfor (const m of messages) {\n\t\t\t\tconst tier = this.config.messageTier(m[0]);\n\t\t\t\t// Tier 3 (DATA / RESOLVED) is per-flow state — broadcasting it\n\t\t\t\t// to every node overwrites unrelated caches. Tier 4/5 stays\n\t\t\t\t// allowed: ERROR/COMPLETE/TEARDOWN have legitimate broadcast\n\t\t\t\t// use (graceful shutdown, error cascade).\n\t\t\t\tif (tier === 3) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Graph \"${this.name}\": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). ` +\n\t\t\t\t\t\t\t`Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). ` +\n\t\t\t\t\t\t\t`For per-node value writes, use Graph.set or graph.node(name).down(...).`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst errors: unknown[] = [];\n\t\tthis._signalDeliver(messages, options ?? {}, new Set(), errors);\n\t\t// Surface the first collected error so callers see failures without\n\t\t// aborting the rest of the broadcast. Guard denials are re-thrown\n\t\t// immediately in _signalDeliver (deliberate access-control rejections).\n\t\tif (errors.length > 0) throw errors[0];\n\t}\n\n\tprivate _signalDeliver(\n\t\tmessages: Messages,\n\t\topts: GraphActorOptions,\n\t\tvis: Set<Node>,\n\t\terrors: unknown[],\n\t): void {\n\t\tfor (const sub of this._mounts.values()) {\n\t\t\tsub._signalDeliver(messages, opts, vis, errors);\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, this.config);\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\ttry {\n\t\t\t\tn.down(messages, downOpts);\n\t\t\t} catch (err) {\n\t\t\t\t// Guard denials bubble — they're deliberate rejections, not\n\t\t\t\t// resilience failures. Other errors collect so one bad handler\n\t\t\t\t// doesn't abort the rest of the broadcast.\n\t\t\t\tif (err instanceof GuardDenied) throw err;\n\t\t\t\terrors.push(err);\n\t\t\t}\n\t\t\tif (metaMessages.length === 0) continue;\n\t\t\tthis._signalMetaSubtree(n, metaMessages, vis, downOpts, errors);\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\terrors: unknown[],\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\ttry {\n\t\t\t\tmnode.down(messages, downOpts);\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof GuardDenied) throw err;\n\t\t\t\terrors.push(err);\n\t\t\t}\n\t\t\tthis._signalMetaSubtree(mnode, messages, vis, downOpts, errors);\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 * `format` controls the return type:\n\t * - omitted or `\"spec\"` → {@link GraphDescribeOutput} object.\n\t * - `\"json\"` / `\"pretty\"` / `\"mermaid\"` / `\"d2\"` → rendered string.\n\t *\n\t * @param options - Optional `actor` for guard-scoped visibility, `filter` for\n\t * selective output, or `format` to render.\n\t *\n\t * @example\n\t * ```ts\n\t * graph.describe() // full snapshot object\n\t * graph.describe({ filter: { status: \"errored\" } }) // filtered object\n\t * graph.describe({ format: \"pretty\" }) // human-readable text\n\t * graph.describe({ format: \"mermaid\" }) // Mermaid flowchart\n\t * graph.describe({ format: \"d2\", direction: \"TD\" }) // D2 top-down\n\t * ```\n\t */\n\tdescribe(\n\t\toptions: GraphDescribeOptions & { format: \"json\" | \"pretty\" | \"mermaid\" | \"d2\" },\n\t): string;\n\tdescribe(options?: GraphDescribeOptions): GraphDescribeOutput;\n\tdescribe(options?: GraphDescribeOptions): GraphDescribeOutput | string {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst includeFields = resolveDescribeFields(options?.detail, options?.fields);\n\t\tconst isSpec = options?.format === \"spec\";\n\t\t// For spec format, force minimal fields (type + deps only, no status/value)\n\t\tconst effectiveFields = isSpec ? resolveDescribeFields(\"minimal\") : includeFields;\n\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, effectiveFields);\n\t\t\tconst deps =\n\t\t\t\tn instanceof NodeImpl\n\t\t\t\t\t? n._deps.map((d) => nodeToPath.get(d.node) ?? d.node.name ?? \"\")\n\t\t\t\t\t: [];\n\t\t\tconst { name: _name, ...rest } = raw;\n\t\t\tconst entry: DescribeNodeOutput = { ...rest, deps };\n\t\t\t// Unit 14 A: attach reason annotation from `trace(path, reason)`\n\t\t\t// when one exists. Skipped for the `\"spec\"` format (input-schema\n\t\t\t// use case — annotations don't round-trip through GraphSpec).\n\t\t\tif (!isSpec) {\n\t\t\t\tconst reason = this._annotations.get(p);\n\t\t\t\tif (reason != null) entry.reason = reason;\n\t\t\t}\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\t// Edges are derived from node `_deps` via `edges({recursive: true})`\n\t\t// (sorted, fully qualified relative to this graph).\n\t\tlet edges: { from: string; to: string }[] = this.edges({ recursive: true }).map(\n\t\t\t([from, to]) => ({ from, to }),\n\t\t);\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\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\n\t\t// Capture graph ref and base options for expand()\n\t\tconst graph = this;\n\t\tconst baseOpts = options;\n\n\t\tconst struct: GraphDescribeOutput = {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t\texpand(detailOrFields: DescribeDetail | DescribeField[]): GraphDescribeOutput {\n\t\t\t\tconst merged: GraphDescribeOptions = { ...baseOpts, format: undefined };\n\t\t\t\tif (Array.isArray(detailOrFields)) {\n\t\t\t\t\tmerged.fields = detailOrFields;\n\t\t\t\t\tmerged.detail = undefined;\n\t\t\t\t} else {\n\t\t\t\t\tmerged.detail = detailOrFields;\n\t\t\t\t\tmerged.fields = undefined;\n\t\t\t\t}\n\t\t\t\treturn graph.describe(merged);\n\t\t\t},\n\t\t};\n\n\t\t// Text-format dispatch. `\"spec\"` and undefined return the struct as-is.\n\t\tconst opts = options ?? {};\n\t\tconst fmt = opts.format;\n\t\tif (fmt === \"json\") return renderDescribeAsJson(struct, opts);\n\t\tif (fmt === \"pretty\") return renderDescribeAsPretty(struct, opts);\n\t\tif (fmt === \"mermaid\") return renderDescribeAsMermaid(struct, opts);\n\t\tif (fmt === \"d2\") return renderDescribeAsD2(struct, opts);\n\t\treturn struct;\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\t/**\n\t * Snapshot-based resource profile: per-node stats, orphan effect detection,\n\t * memory hotspots. Zero runtime overhead — walks nodes on demand.\n\t *\n\t * @param opts - Optional `topN` for hotspot limit (default 10).\n\t * @returns Aggregate profile with per-node details, hotspots, and orphan effects.\n\t */\n\tresourceProfile(opts?: GraphProfileOptions): GraphProfileResult {\n\t\treturn graphProfile(this, opts);\n\t}\n\n\t/**\n\t * Reachability query rooted at `from`. Instance convenience — wraps\n\t * `reachable(this.describe(), from, direction, opts)`. See\n\t * {@link reachable} for semantics.\n\t */\n\treachable(\n\t\tfrom: string,\n\t\tdirection: ReachableDirection,\n\t\topts: ReachableOptions & { withDetail: true },\n\t): ReachableResult;\n\treachable(from: string, direction: ReachableDirection, opts?: ReachableOptions): string[];\n\treachable(\n\t\tfrom: string,\n\t\tdirection: ReachableDirection,\n\t\topts: ReachableOptions = {},\n\t): string[] | ReachableResult {\n\t\tif (opts.withDetail === true) {\n\t\t\treturn reachable(this.describe(), from, direction, {\n\t\t\t\t...opts,\n\t\t\t\twithDetail: true,\n\t\t\t});\n\t\t}\n\t\treturn reachable(this.describe(), from, direction, opts);\n\t}\n\n\t/**\n\t * @internal Collect all qualified paths in this graph tree matching a\n\t * glob pattern. Used by scoped autoCheckpoint subscription.\n\t */\n\tprivate _pathsMatching(glob: string): string[] {\n\t\tconst re = globToRegex(glob);\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\treturn targets.map(([p]) => p).filter((p) => re.test(p));\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 * Two modes dispatched on first argument:\n\t * - `observe(path, options?)` — one node. Returns {@link GraphObserveOne}\n\t * (raw stream), or {@link ObserveResult} when `options` requests structured\n\t * accumulation (`structured`, `timeline`, `causal`, `derived`, `format`,\n\t * `detail: \"minimal\"|\"full\"`).\n\t * - `observe(options?)` — all nodes. Returns {@link GraphObserveAll} (raw),\n\t * or {@link ObserveResult} under the same structured trigger conditions.\n\t *\n\t * Structured mode subscribes in sorted path order (code-point). Inspector\n\t * extras (`causal`/`derived`) require `graph.config.inspectorEnabled`;\n\t * when disabled, those fields silently drop and the rest still works.\n\t *\n\t * `ObserveResult` is also an `AsyncIterable<ObserveEvent>` — use\n\t * `for await (const ev of result)` for pull-based consumption.\n\t */\n\tobserve(path: string, options?: ObserveOptions & StructuredTriggers): ObserveResult;\n\tobserve(path: string, options?: ObserveOptions): GraphObserveOne;\n\tobserve(options: ObserveOptions & StructuredTriggers): ObserveResult;\n\tobserve(options?: ObserveOptions): GraphObserveAll;\n\tobserve(\n\t\tpathOrOpts?: string | ObserveOptions,\n\t\toptions?: ObserveOptions,\n\t): GraphObserveOne | GraphObserveAll | ObserveResult {\n\t\tconst isPath = typeof pathOrOpts === \"string\";\n\t\tconst rawOpts = isPath ? options : (pathOrOpts as ObserveOptions | undefined);\n\t\tconst resolved = resolveObserveDetail(rawOpts);\n\t\tconst wantsStructured =\n\t\t\tresolved.structured === true ||\n\t\t\tresolved.timeline === true ||\n\t\t\tresolved.causal === true ||\n\t\t\tresolved.derived === true ||\n\t\t\tresolved.detail === \"minimal\" ||\n\t\t\tresolved.detail === \"full\" ||\n\t\t\tresolved.format != null;\n\t\tconst actor = resolved.actor;\n\n\t\tif (isPath) {\n\t\t\tconst path = pathOrOpts as string;\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\tif (wantsStructured) return this._buildStructuredObserver([[path, target]], resolved, \"one\");\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;\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\n\t\tconst collected: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", collected);\n\t\tcollected.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst picked =\n\t\t\tactor == null ? collected : collected.filter(([, nd]) => nd.allowsObserve(actor));\n\t\tif (wantsStructured) return this._buildStructuredObserver(picked, resolved, \"all\");\n\t\treturn {\n\t\t\tsubscribe: (sink: (nodePath: string, messages: Messages) => void) => {\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;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Dispatch helper — builds a unified observer + its expand closure. */\n\tprivate _buildStructuredObserver<T>(\n\t\ttargets: ReadonlyArray<[string, Node]>,\n\t\toptions: ObserveOptions,\n\t\tmode: \"one\" | \"all\",\n\t): ObserveResult<T> {\n\t\tconst firstPath = mode === \"one\" ? targets[0]?.[0] : undefined;\n\t\tconst expand = (merged: ObserveOptions): ObserveResult<T> => {\n\t\t\tif (mode === \"one\" && firstPath != null) {\n\t\t\t\tconst target = this.resolve(firstPath);\n\t\t\t\treturn this._buildStructuredObserver([[firstPath, target]], merged, \"one\");\n\t\t\t}\n\t\t\tconst collected: [string, Node][] = [];\n\t\t\tthis._collectObserveTargets(\"\", collected);\n\t\t\tcollected.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\t\tconst actor = merged.actor;\n\t\t\tconst picked =\n\t\t\t\tactor == null ? collected : collected.filter(([, nd]) => nd.allowsObserve(actor));\n\t\t\treturn this._buildStructuredObserver(picked, merged, \"all\");\n\t\t};\n\t\treturn this._createObserveResult<T>(targets, options, expand);\n\t}\n\n\t/**\n\t * Unified observer builder — replaces the four ex-creators\n\t * (`_createObserveResult` / `...ForAll` / `_createFallback…`). Accepts a\n\t * list of `[path, node]` targets (single-element for one-node observe,\n\t * N-element for all-nodes). Inspector hooks attach per-target when\n\t * `causal`/`derived` requested AND `config.inspectorEnabled`; otherwise\n\t * those fields gracefully drop.\n\t *\n\t * Events flow through a `recordEvent()` helper so the format logger,\n\t * ring-buffer, and async-iterable hooks all share one push path.\n\t */\n\tprivate _createObserveResult<T>(\n\t\ttargets: ReadonlyArray<[string, Node]>,\n\t\toptions: ObserveOptions,\n\t\texpand: (merged: ObserveOptions) => ObserveResult<T>,\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 minimal = options.detail === \"minimal\";\n\t\tconst inspectorOn = this.config.inspectorEnabled;\n\t\tconst wantInspector = (causal || derived) && inspectorOn;\n\n\t\t// Event buffer: unbounded array, or RingBuffer when maxEvents capped.\n\t\tconst maxEvents = options.maxEvents;\n\t\tconst ring =\n\t\t\tmaxEvents != null && maxEvents > 0 ? new RingBuffer<ObserveEvent>(maxEvents) : null;\n\t\tconst events: ObserveEvent[] = [];\n\n\t\t// Listener set — format logger, async iterable, and user `onEvent` hooks.\n\t\tconst listeners = new Set<(event: ObserveEvent) => void>();\n\n\t\tconst values: Record<string, T> = {};\n\t\tconst nodeErrored = new Set<string>();\n\t\tlet dirtyCount = 0;\n\t\tlet resolvedCount = 0;\n\t\tlet invalidateCount = 0;\n\t\tlet pauseCount = 0;\n\t\tlet resumeCount = 0;\n\t\tlet teardownCount = 0;\n\t\tlet anyCompletedCleanly = false;\n\t\tlet anyErrored = false;\n\t\tlet batchSeq = 0;\n\n\t\t// Per-target causal context (keyed by target index).\n\t\tconst lastTriggerDepIndex = new Map<Node, number>();\n\t\tconst lastRunDepValues = new Map<Node, readonly unknown[]>();\n\t\tconst lastRunDepBatches = new Map<Node, ReadonlyArray<ReadonlyArray<unknown> | undefined>>();\n\n\t\tconst recordEvent = (event: ObserveEvent): void => {\n\t\t\tif (ring) ring.push(event);\n\t\t\telse events.push(event);\n\t\t\tfor (const listener of listeners) listener(event);\n\t\t};\n\n\t\tconst baseMeta = (): Partial<ObserveEventBase> =>\n\t\t\ttimeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq } : {};\n\n\t\tconst attachInspector = (target: Node, path: string): (() => void) | undefined => {\n\t\t\tif (!wantInspector || !(target instanceof NodeImpl)) return undefined;\n\t\t\treturn target._setInspectorHook((ev) => {\n\t\t\t\tif (ev.kind === \"dep_message\") {\n\t\t\t\t\tlastTriggerDepIndex.set(target, ev.depIndex);\n\t\t\t\t} else if (ev.kind === \"run\") {\n\t\t\t\t\tconst effective = ev.batchData.map((b, i) =>\n\t\t\t\t\t\tb != null && b.length > 0 ? b.at(-1) : ev.prevData[i],\n\t\t\t\t\t);\n\t\t\t\t\tlastRunDepValues.set(target, effective);\n\t\t\t\t\t// Snapshot the full per-dep batches so multi-value waves stay\n\t\t\t\t\t// visible to observers. `ev.batchData` references run-local\n\t\t\t\t\t// arrays, so clone the outer array (inner arrays are\n\t\t\t\t\t// effectively immutable from the observer's POV).\n\t\t\t\t\tconst batches: ReadonlyArray<ReadonlyArray<unknown> | undefined> = ev.batchData.map(\n\t\t\t\t\t\t(b) => (b != null ? [...b] : undefined),\n\t\t\t\t\t);\n\t\t\t\t\tlastRunDepBatches.set(target, batches);\n\t\t\t\t\tif (derived) {\n\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\ttype: \"derived\",\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\tdep_values: effective,\n\t\t\t\t\t\t\tdep_batches: batches,\n\t\t\t\t\t\t\t...baseMeta(),\n\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\n\t\tconst buildCausal = (target: Node): ObserveCausalContext => {\n\t\t\tconst idx = lastTriggerDepIndex.get(target);\n\t\t\tconst depValues = lastRunDepValues.get(target);\n\t\t\tif (!causal || depValues == null) return {};\n\t\t\tconst triggerDep =\n\t\t\t\tidx != null && idx >= 0 && target instanceof NodeImpl ? target._deps[idx] : undefined;\n\t\t\tconst triggerNode = triggerDep?.node;\n\t\t\tconst tv = triggerNode?.v;\n\t\t\tconst depBatches = lastRunDepBatches.get(target);\n\t\t\treturn {\n\t\t\t\ttrigger_dep_index: idx,\n\t\t\t\ttrigger_dep_name: triggerNode?.name,\n\t\t\t\t...(tv != null ? { trigger_version: { id: tv.id, version: tv.version } } : {}),\n\t\t\t\tdep_values: [...depValues],\n\t\t\t\t...(depBatches != null ? { dep_batches: depBatches } : {}),\n\t\t\t};\n\t\t};\n\n\t\tconst inspectorDetaches: Array<() => void> = [];\n\t\tconst unsubs: Array<() => void> = [];\n\t\tfor (const [path, target] of targets) {\n\t\t\tconst detach = attachInspector(target, path);\n\t\t\tif (detach) inspectorDetaches.push(detach);\n\t\t\tunsubs.push(\n\t\t\t\ttarget.subscribe((msgs) => {\n\t\t\t\t\tbatchSeq++;\n\t\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\t\tconst t = m[0];\n\t\t\t\t\t\tconst base = baseMeta();\n\t\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\t\tvalues[path] = m[1] as T;\n\t\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\t\ttype: \"data\",\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\tdata: m[1],\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\t...buildCausal(target),\n\t\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t\t} else if (minimal) {\n\t\t\t\t\t\t\tif (t === DIRTY) dirtyCount++;\n\t\t\t\t\t\t\telse if (t === RESOLVED) resolvedCount++;\n\t\t\t\t\t\t\telse if (t === INVALIDATE) invalidateCount++;\n\t\t\t\t\t\t\telse if (t === PAUSE) pauseCount++;\n\t\t\t\t\t\t\telse if (t === RESUME) resumeCount++;\n\t\t\t\t\t\t\telse if (t === TEARDOWN) teardownCount++;\n\t\t\t\t\t\t\telse if (t === COMPLETE && !nodeErrored.has(path)) anyCompletedCleanly = true;\n\t\t\t\t\t\t\telse if (t === ERROR) {\n\t\t\t\t\t\t\t\tanyErrored = true;\n\t\t\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\t\t\tdirtyCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"dirty\", path, ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\t\tresolvedCount++;\n\t\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\t\ttype: \"resolved\",\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\t...buildCausal(target),\n\t\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t\t} else if (t === INVALIDATE) {\n\t\t\t\t\t\t\tinvalidateCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"invalidate\", path, ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === PAUSE) {\n\t\t\t\t\t\t\tpauseCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"pause\", path, lockId: m[1], ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === RESUME) {\n\t\t\t\t\t\t\tresumeCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"resume\", path, lockId: m[1], ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\t\tif (!nodeErrored.has(path)) anyCompletedCleanly = true;\n\t\t\t\t\t\t\trecordEvent({ type: \"complete\", path, ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\t\tanyErrored = true;\n\t\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\tdata: m[1],\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t\t} else if (t === TEARDOWN) {\n\t\t\t\t\t\t\tteardownCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"teardown\", path, ...base } as ObserveEvent);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tlet disposed = false;\n\t\tconst dispose = (): void => {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tfor (const u of unsubs) u();\n\t\t\tfor (const d of inspectorDetaches) d();\n\t\t\tfor (const resolve of asyncResolvers) resolve({ value: undefined, done: true });\n\t\t\tasyncResolvers.length = 0;\n\t\t};\n\n\t\t// AsyncIterator plumbing: queue events until a pull arrives, or wake\n\t\t// a pending pull when a new event lands.\n\t\tconst asyncQueue: ObserveEvent[] = [];\n\t\tconst asyncResolvers: Array<(r: IteratorResult<ObserveEvent>) => void> = [];\n\t\tlisteners.add((ev) => {\n\t\t\tconst resolve = asyncResolvers.shift();\n\t\t\tif (resolve) resolve({ value: ev, done: false });\n\t\t\telse asyncQueue.push(ev);\n\t\t});\n\n\t\tconst result: ObserveResult<T> = {\n\t\t\tget values() {\n\t\t\t\treturn values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn resolvedCount;\n\t\t\t},\n\t\t\tget invalidateCount() {\n\t\t\t\treturn invalidateCount;\n\t\t\t},\n\t\t\tget pauseCount() {\n\t\t\t\treturn pauseCount;\n\t\t\t},\n\t\t\tget resumeCount() {\n\t\t\t\treturn resumeCount;\n\t\t\t},\n\t\t\tget teardownCount() {\n\t\t\t\treturn teardownCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn ring ? ring.toArray() : [...events];\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn anyCompletedCleanly && !anyErrored;\n\t\t\t},\n\t\t\tonEvent(listener) {\n\t\t\t\tlisteners.add(listener);\n\t\t\t\treturn () => listeners.delete(listener);\n\t\t\t},\n\t\t\tdispose,\n\t\t\texpand(extra) {\n\t\t\t\tdispose();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\treturn expand(resolveObserveDetail(merged));\n\t\t\t},\n\t\t\t[Symbol.asyncIterator](): AsyncIterator<ObserveEvent> {\n\t\t\t\treturn {\n\t\t\t\t\tnext(): Promise<IteratorResult<ObserveEvent>> {\n\t\t\t\t\t\tif (asyncQueue.length > 0) {\n\t\t\t\t\t\t\treturn Promise.resolve({ value: asyncQueue.shift()!, done: false });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (disposed) return Promise.resolve({ value: undefined, done: true });\n\t\t\t\t\t\treturn new Promise((resolve) => asyncResolvers.push(resolve));\n\t\t\t\t\t},\n\t\t\t\t\treturn(): Promise<IteratorResult<ObserveEvent>> {\n\t\t\t\t\t\tdispose();\n\t\t\t\t\t\treturn Promise.resolve({ value: undefined, done: true });\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\n\t\t// Format logger: subscribes to event stream, renders via theme/format.\n\t\tif (options.format != null) this._attachFormatLogger(result, options);\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Attach format-rendering logger to an ObserveResult by subscribing to its\n\t * event stream (no monkey-patching). Renders each event per `format` and\n\t * `theme`, filtered by `includeTypes` / `excludeTypes`.\n\t */\n\tprivate _attachFormatLogger(result: ObserveResult, options: ObserveOptions): void {\n\t\tconst format = options.format;\n\t\tif (format == null) return;\n\t\tconst logger = options.logger ?? ((line: string) => console.log(line));\n\t\t// Compile include/exclude predicates once.\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 shouldLog =\n\t\t\tinclude == null && exclude == null\n\t\t\t\t? () => true\n\t\t\t\t: (type: ObserveEvent[\"type\"]): boolean =>\n\t\t\t\t\t\t(include == null || include.has(type)) && (exclude == null || !exclude.has(type));\n\t\tconst theme = resolveObserveTheme(options.theme);\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 isDataBearing = event.type === \"data\" || event.type === \"error\";\n\t\t\tconst isLockBearing = event.type === \"pause\" || event.type === \"resume\";\n\t\t\tconst dataPart = isDataBearing\n\t\t\t\t? ` ${describeData((event as { data: unknown }).data)}`\n\t\t\t\t: isLockBearing\n\t\t\t\t\t? ` ${describeData((event as { lockId: unknown }).lockId)}`\n\t\t\t\t\t: \"\";\n\t\t\tconst causal =\n\t\t\t\tevent.type === \"data\" || event.type === \"resolved\" || event.type === \"derived\"\n\t\t\t\t\t? (event as ObserveCausalContext)\n\t\t\t\t\t: undefined;\n\t\t\tconst triggerPart =\n\t\t\t\tcausal?.trigger_dep_name != null\n\t\t\t\t\t? ` <- ${causal.trigger_dep_name}`\n\t\t\t\t\t: causal?.trigger_dep_index != null\n\t\t\t\t\t\t? ` <- #${causal.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\tresult.onEvent((event) => {\n\t\t\tif (shouldLog(event.type)) logger(renderEvent(event), event);\n\t\t});\n\t}\n\n\t// `dumpGraph` is folded into `describe({format: \"pretty\" | \"json\"})` (Unit 12).\n\t// `toMermaid` / `toD2` are folded into `describe({format: \"mermaid\" | \"d2\"})` (Unit 20).\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Lifecycle & persistence (§3.7–§3.8)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Register a cleanup function to be called on {@link Graph.destroy}.\n\t *\n\t * Factories use this to attach teardown logic for internal nodes, keepalive\n\t * subscriptions, or other resources that are not registered on the graph and\n\t * would otherwise leak on repeated create/destroy cycles.\n\t *\n\t * Returns a removal function — call it to unregister the disposer early.\n\t */\n\taddDisposer(fn: () => void): () => void {\n\t\tthis._disposers.add(fn);\n\t\treturn () => {\n\t\t\tthis._disposers.delete(fn);\n\t\t};\n\t}\n\n\t/**\n\t * Drains disposers (registered via {@link addDisposer}), then sends `[[TEARDOWN]]` to all\n\t * nodes and clears registries on this graph and every mounted subgraph (§3.7).\n\t * The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\t// Drain disposers (keepalive unsubs etc.) BEFORE TEARDOWN so that\n\t\t// internal effect nodes are disconnected before the cascade fires.\n\t\t// Drain iteratively so disposers registered mid-drain also run; cap\n\t\t// iterations to guard against a disposer that re-registers itself.\n\t\tdrainDisposers(this._disposers, this.name);\n\t\t// TEARDOWN is tier 5 — below `attachStorage`'s `tier < 5` gate, so no\n\t\t// final checkpoint fires; storage disposers unsubscribe after TEARDOWN\n\t\t// has propagated through the subscription pipeline.\n\t\tthis.signal([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tdrainDisposers(this._storageDisposers, this.name);\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._parent = undefined;\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._parent = undefined;\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._parent = undefined;\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._parent = undefined;\n\t}\n\n\t/**\n\t * Serializes structure and current values to JSON-shaped data (§3.8). Same\n\t * information as {@link Graph.describe} plus a `version` field for format\n\t * evolution.\n\t *\n\t * The overload path supports three outputs:\n\t * - no arg → `GraphPersistSnapshot` (plain JS object).\n\t * - `{format: \"json-string\"}` → deterministic JSON `string`\n\t * (key-sorted; safe for hashing or file write).\n\t * - `{format: \"bytes\", codec: name}` → `Uint8Array` wrapped in the v1\n\t * envelope from {@link encodeEnvelope}. The codec must be registered\n\t * on this graph's {@link GraphReFlyConfig} via `config.registerCodec`.\n\t * Paired with {@link Graph.decode} for auto-dispatch on the read side.\n\t */\n\tsnapshot(): GraphPersistSnapshot;\n\tsnapshot(opts: { format: \"json-string\" }): string;\n\tsnapshot(opts: { format: \"bytes\"; codec: string }): Uint8Array;\n\tsnapshot(opts?: {\n\t\tformat?: \"json-string\" | \"bytes\";\n\t\tcodec?: string;\n\t}): GraphPersistSnapshot | string | Uint8Array {\n\t\tconst { expand: _, ...d } = this.describe({ detail: \"full\" });\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\t// Strip non-restorable fields (runtime attribution) so snapshot → restore → snapshot\n\t\t// is idempotent. Use describe({ detail: \"full\" }) for audit snapshots instead.\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = d.nodes[key]!;\n\t\t\tsortedNodes[key] = node;\n\t\t}\n\t\tconst sortedSubgraphs = [...d.subgraphs].sort();\n\t\tconst snap: GraphPersistSnapshot = {\n\t\t\t...d,\n\t\t\tversion: 1,\n\t\t\tnodes: sortedNodes,\n\t\t\tsubgraphs: sortedSubgraphs,\n\t\t};\n\t\tif (opts?.format == null) return snap;\n\t\tif (opts.format === \"json-string\") return JSON.stringify(snap);\n\t\tif (opts.format === \"bytes\") {\n\t\t\tif (opts.codec == null) {\n\t\t\t\tthrow new Error(\"snapshot({format: 'bytes'}) requires a `codec` name\");\n\t\t\t}\n\t\t\tconst codec = this.config.lookupCodec<GraphCodec>(opts.codec);\n\t\t\tif (codec == null) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`snapshot: codec \"${opts.codec}\" is not registered on this graph's config. ` +\n\t\t\t\t\t\t`Call config.registerCodec(...) before creating nodes.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn encodeEnvelope(codec, codec.encode(snap));\n\t\t}\n\t\tthrow new Error(`snapshot: unknown format \"${String(opts.format)}\"`);\n\t}\n\n\t/**\n\t * Auto-dispatch a byte buffer produced by {@link Graph.snapshot} with\n\t * `{format: \"bytes\", codec: name}`. Reads the v1 envelope, resolves the\n\t * named codec on `config` (defaults to `defaultConfig`), and returns the\n\t * decoded snapshot. Combine with {@link Graph.fromSnapshot} to rehydrate\n\t * a full graph topology from bytes.\n\t *\n\t * @throws If the envelope is malformed or the named codec isn't\n\t * registered on the target config.\n\t */\n\tstatic decode(bytes: Uint8Array, opts?: { config?: GraphReFlyConfig }): GraphPersistSnapshot {\n\t\tconst cfg = opts?.config ?? defaultConfig;\n\t\tconst { codec, codecVersion, payload } = decodeEnvelope(bytes, cfg);\n\t\treturn codec.decode(payload, codecVersion);\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` entries with a `value` field\n\t * are written by default; `derived` / `operator` / `effect` are always skipped so\n\t * deps drive recomputation. `producer` entries are skipped unless `includeProducers`\n\t * is set (producers recompute on activation, so restoring is usually a no-op\n\t * overwritten on the next wave — opt in for audit / forensic round-trip use cases).\n\t * 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(\n\t\tdata: GraphPersistSnapshot,\n\t\toptions?: {\n\t\t\tonly?: string | readonly string[];\n\t\t\t/**\n\t\t\t * Fires per failing write. Default behavior (omitted) is silent —\n\t\t\t * missing paths and guard denials are swallowed to match the\n\t\t\t * historical semantics. Provide a callback to surface failures\n\t\t\t * without aborting the remaining restores.\n\t\t\t */\n\t\t\tonError?: (path: string, err: unknown) => void;\n\t\t\t/**\n\t\t\t * Restore `producer` node values alongside `state`. Default `false`:\n\t\t\t * producers are reactive sources whose value recomputes on\n\t\t\t * activation, so restoring from a snapshot is usually a no-op\n\t\t\t * overwritten on the next wave. Audit / forensic round-trip use\n\t\t\t * cases that need the stored value to survive restoration can\n\t\t\t * opt in. Does not change `derived` / `effect` handling — those\n\t\t\t * are always skipped.\n\t\t\t */\n\t\t\tincludeProducers?: boolean;\n\t\t},\n\t): 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\tconst includeProducers = options?.includeProducers === true;\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) continue;\n\t\t\tif (!(\"value\" in slice) || slice.value === undefined) {\n\t\t\t\t// Value absent (valid slice with no snapshotted value) or\n\t\t\t\t// value === undefined (malformed — undefined is the global\n\t\t\t\t// SENTINEL per spec §2.5, not valid DATA). Surface the\n\t\t\t\t// malformed case so torn snapshots don't round-trip silently.\n\t\t\t\tif (\"value\" in slice && slice.value === undefined) {\n\t\t\t\t\toptions?.onError?.(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`restore: slice.value is undefined for \"${path}\" (undefined is the global SENTINEL; not valid DATA)`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (slice.type === \"derived\" || slice.type === \"effect\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (slice.type === \"producer\" && !includeProducers) {\n\t\t\t\t// Reactive producers recompute on activation — restoring would\n\t\t\t\t// be overwritten on the first wave. Opt in via\n\t\t\t\t// `{includeProducers: true}` for audit use cases.\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// V0 shortcut: if the snapshot slice and the live node both carry\n\t\t\t// matching versioning info (`v.id` + `v.version`), skip the\n\t\t\t// `set()` — the state is already what the snapshot represents.\n\t\t\t// Avoids redundant DATA waves on idempotent restores.\n\t\t\tif (slice.v != null) {\n\t\t\t\tconst live = this.tryResolve(path);\n\t\t\t\tconst lv = live?.v;\n\t\t\t\tif (lv != null && lv.id === slice.v.id && lv.version === slice.v.version) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.set(path, slice.value);\n\t\t\t} catch (err) {\n\t\t\t\toptions?.onError?.(path, err);\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 opts - Either a legacy `build(g)` callback, or an options object:\n\t * - `build?` — topology constructor; skips auto-hydration when present.\n\t * - `factories?` — map from glob pattern to {@link GraphNodeFactory},\n\t * used by auto-hydration to reconstruct non-state nodes. Per-call (no\n\t * process-global registry). First matching pattern wins.\n\t * @returns Hydrated `Graph` instance.\n\t */\n\tstatic fromSnapshot(\n\t\tdata: GraphPersistSnapshot,\n\t\topts?:\n\t\t\t| ((g: Graph) => void)\n\t\t\t| { build?: (g: Graph) => void; factories?: Record<string, GraphNodeFactory> },\n\t): Graph {\n\t\tparseSnapshotEnvelope(data);\n\t\tconst build = typeof opts === \"function\" ? opts : opts?.build;\n\t\tconst factoryMap = typeof opts === \"function\" ? undefined : opts?.factories;\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\t// Compile factory glob patterns once. First match in insertion order wins.\n\t\tconst factories = factoryMap\n\t\t\t? Object.entries(factoryMap).map(([pattern, factory]) => ({\n\t\t\t\t\tre: globToRegex(pattern),\n\t\t\t\t\tfactory,\n\t\t\t\t}))\n\t\t\t: [];\n\t\tconst factoryForPath = (path: string): GraphNodeFactory | undefined => {\n\t\t\tfor (const entry of factories) {\n\t\t\t\tif (entry.re.test(path)) return entry.factory;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t};\n\n\t\t// Resolve the owning graph + local name for a qualified snapshot path.\n\t\tconst ownerForPath = (path: string): [Graph, string] => {\n\t\t\tconst segments = path.split(PATH_SEP);\n\t\t\tconst local = segments.pop();\n\t\t\tif (local == null || local.length === 0) {\n\t\t\t\tthrow new Error(`invalid snapshot path \"${path}\"`);\n\t\t\t}\n\t\t\tlet owner: Graph = g;\n\t\t\tfor (const seg of segments) {\n\t\t\t\tconst next = owner._mounts.get(seg);\n\t\t\t\tif (!next) throw new Error(`unknown mount \"${seg}\" in path \"${path}\"`);\n\t\t\t\towner = next;\n\t\t\t}\n\t\t\treturn [owner, local];\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] = ownerForPath(path);\n\t\t\t\tconst meta: Record<string, unknown> = { ...(slice?.meta ?? {}) };\n\t\t\t\tconst factory = 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`Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`,\n\t\t\t);\n\t\t}\n\t\t// Edges are derived from node `_deps` reconstructed during node\n\t\t// creation above — no explicit edge replay needed (Unit 7).\n\t\tg.restore(data);\n\t\treturn g;\n\t}\n\n\t/**\n\t * ECMAScript `JSON.stringify` hook — returns the same object as\n\t * {@link Graph.snapshot}. Makes `JSON.stringify(graph)` \"just work\"\n\t * without double-encoding.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * Unified persistence surface (§3.8). Cascades snapshot records through\n\t * one or more {@link StorageTier}s, each with its own `debounceMs` /\n\t * `compactEvery` cadence and independent diff baseline.\n\t *\n\t * Subscription gates on {@link messageTier} ≥ 3 (DATA/RESOLVED/terminal),\n\t * never on tier-0/1/2 control waves (START/DIRTY/INVALIDATE/PAUSE/RESUME)\n\t * or tier-5 TEARDOWN (graceful shutdown is the caller's responsibility).\n\t *\n\t * Per-tier cadence lets the hot tier stay sync while cold tiers absorb\n\t * async writes without blocking the hot path. Each tier holds its own\n\t * `{lastSnapshot, lastVersionFingerprint}` so cold-tier diff baselines\n\t * aren't polluted by hot-tier flushes. Tiers with `debounceMs === 0`\n\t * share a single snapshot computation per observe event; debounced tiers\n\t * compute their own snapshot when their timer fires.\n\t */\n\tattachStorage(\n\t\ttiers: readonly StorageTier[],\n\t\toptions: GraphAttachStorageOptions = {},\n\t): StorageHandle {\n\t\ttype TierState = {\n\t\t\ttier: StorageTier;\n\t\t\tdebounceMs: number;\n\t\t\tcompactEvery: number;\n\t\t\ttimer: ResettableTimer | undefined;\n\t\t\tseq: number;\n\t\t\tlastSnapshot: GraphPersistSnapshot | undefined;\n\t\t\tlastFingerprint: string;\n\t\t\tdisposed: boolean;\n\t\t\t// Chain of pending async saves for this tier. Each flush awaits the\n\t\t\t// previous one so baseline advances only after persistence confirms;\n\t\t\t// on rejection the chain resets (next flush starts from the last\n\t\t\t// successfully-persisted baseline). Sync tiers never populate this.\n\t\t\tsavePending: Promise<void> | undefined;\n\t\t};\n\t\tconst states: TierState[] = tiers.map((tier) => ({\n\t\t\ttier,\n\t\t\tdebounceMs: Math.max(0, tier.debounceMs ?? 0),\n\t\t\tcompactEvery: Math.max(1, tier.compactEvery ?? 10),\n\t\t\ttimer: undefined,\n\t\t\tseq: 0,\n\t\t\tlastSnapshot: undefined,\n\t\t\tlastFingerprint: \"\",\n\t\t\tdisposed: false,\n\t\t\tsavePending: undefined,\n\t\t}));\n\n\t\tif (options.autoRestore === true) {\n\t\t\t// Fire-and-forget cascade restore; errors surface via onError with\n\t\t\t// the specific tier that failed.\n\t\t\tvoid this._cascadeRestore(tiers, options.onError);\n\t\t}\n\n\t\tconst runFlush = (s: TierState, snapshot: GraphPersistSnapshot): void => {\n\t\t\tif (s.disposed) return;\n\t\t\tconst fingerprint = computeVersionFingerprint(snapshot.nodes);\n\t\t\tif (s.lastSnapshot != null && fingerprint !== \"\" && fingerprint === s.lastFingerprint) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nextSeq = s.seq + 1;\n\t\t\tconst timestamp_ns = monotonicNs();\n\t\t\tconst isFirst = s.lastSnapshot == null;\n\t\t\tconst shouldCompact = isFirst || nextSeq % s.compactEvery === 0;\n\t\t\tconst record: GraphCheckpointRecord = shouldCompact\n\t\t\t\t? {\n\t\t\t\t\t\tmode: \"full\",\n\t\t\t\t\t\tsnapshot,\n\t\t\t\t\t\tseq: nextSeq,\n\t\t\t\t\t\ttimestamp_ns,\n\t\t\t\t\t\tformat_version: SNAPSHOT_VERSION,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tmode: \"diff\",\n\t\t\t\t\t\tdiff: diffForWAL(s.lastSnapshot!, snapshot),\n\t\t\t\t\t\tseq: nextSeq,\n\t\t\t\t\t\ttimestamp_ns,\n\t\t\t\t\t\tformat_version: SNAPSHOT_VERSION,\n\t\t\t\t\t};\n\t\t\tif (s.tier.filter && !s.tier.filter(this.name, record)) {\n\t\t\t\t// Filter rejected — don't advance seq or baseline.\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet result: void | Promise<void>;\n\t\t\ttry {\n\t\t\t\tresult = s.tier.save(this.name, record);\n\t\t\t} catch (error) {\n\t\t\t\t// Synchronous throw — baseline untouched; surface and bail.\n\t\t\t\toptions.onError?.(error, s.tier);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result && typeof (result as Promise<void>).then === \"function\") {\n\t\t\t\t// Async tier: defer baseline + seq advance until the promise\n\t\t\t\t// settles. Chain saves per-tier so they land in order without\n\t\t\t\t// overlapping baselines. On rejection, baseline is left intact\n\t\t\t\t// so the next flush diffs against the last successfully\n\t\t\t\t// persisted snapshot.\n\t\t\t\tconst prev = s.savePending ?? Promise.resolve();\n\t\t\t\tconst chained = prev.then(\n\t\t\t\t\t() => result as Promise<void>,\n\t\t\t\t\t// Previous rejection already surfaced; don't block this save.\n\t\t\t\t\t() => result as Promise<void>,\n\t\t\t\t);\n\t\t\t\tconst final = chained.then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tif (s.disposed) return;\n\t\t\t\t\t\ts.seq = nextSeq;\n\t\t\t\t\t\ts.lastSnapshot = snapshot;\n\t\t\t\t\t\ts.lastFingerprint = fingerprint;\n\t\t\t\t\t},\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\toptions.onError?.(err, s.tier);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\ts.savePending = final.finally(() => {\n\t\t\t\t\tif (s.savePending === final) s.savePending = undefined;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ts.seq = nextSeq;\n\t\t\t\ts.lastSnapshot = snapshot;\n\t\t\t\ts.lastFingerprint = fingerprint;\n\t\t\t}\n\t\t};\n\n\t\tconst flushTier = (s: TierState, snapshot: GraphPersistSnapshot): void => {\n\t\t\ttry {\n\t\t\t\trunFlush(s, snapshot);\n\t\t\t} catch (error) {\n\t\t\t\toptions.onError?.(error, s.tier);\n\t\t\t}\n\t\t};\n\n\t\tconst onEvent = (path: string, messages: Messages): void => {\n\t\t\tconst triggeredByTier = messages.some((m) => {\n\t\t\t\tconst tier = this.config.messageTier(m[0]);\n\t\t\t\treturn tier >= 3 && tier < 5;\n\t\t\t});\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst nd = this.tryResolve(path);\n\t\t\t\tif (nd == null) return;\n\t\t\t\tconst described = describeNode(nd, resolveDescribeFields(\"standard\"));\n\t\t\t\tif (!options.filter(path, described)) return;\n\t\t\t}\n\t\t\t// Shared snapshot for all sync (debounceMs=0) tiers firing on this event.\n\t\t\tlet sharedSnapshot: GraphPersistSnapshot | undefined;\n\t\t\tconst getSnapshot = (): GraphPersistSnapshot => {\n\t\t\t\tif (sharedSnapshot == null) sharedSnapshot = this.snapshot();\n\t\t\t\treturn sharedSnapshot;\n\t\t\t};\n\t\t\tfor (const s of states) {\n\t\t\t\tif (s.disposed) continue;\n\t\t\t\tif (s.debounceMs === 0) {\n\t\t\t\t\tflushTier(s, getSnapshot());\n\t\t\t\t} else {\n\t\t\t\t\tif (s.timer == null) s.timer = new ResettableTimer();\n\t\t\t\t\ts.timer.start(s.debounceMs, () => {\n\t\t\t\t\t\tif (s.disposed) return;\n\t\t\t\t\t\tflushTier(s, this.snapshot());\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tlet off: () => void;\n\t\tif (options.paths != null) {\n\t\t\tconst paths =\n\t\t\t\ttypeof options.paths === \"string\"\n\t\t\t\t\t? this._pathsMatching(options.paths)\n\t\t\t\t\t: (options.paths as readonly string[]);\n\t\t\tconst unsubs = paths.map((p) => {\n\t\t\t\tconst nd = this.tryResolve(p);\n\t\t\t\tif (nd == null) return () => {};\n\t\t\t\treturn nd.subscribe((msgs) => onEvent(p, msgs));\n\t\t\t});\n\t\t\toff = () => {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t};\n\t\t} else {\n\t\t\toff = this.observe().subscribe((path, messages) => onEvent(path, messages));\n\t\t}\n\n\t\tconst dispose = () => {\n\t\t\toff();\n\t\t\tfor (const s of states) {\n\t\t\t\ts.disposed = true;\n\t\t\t\ts.timer?.cancel();\n\t\t\t}\n\t\t\tthis._storageDisposers.delete(dispose);\n\t\t};\n\t\tthis._storageDisposers.add(dispose);\n\t\treturn { dispose };\n\t}\n\n\t/**\n\t * Try tiers in order (hottest first); apply the first record that hits\n\t * via {@link Graph.restore}. Returns `true` if any tier produced a\n\t * restorable snapshot, `false` if all missed.\n\t *\n\t * Resilience: a tier that returns data which cannot be restored (load\n\t * throws, shape unrecognized, or `restore()` itself throws) does not abort\n\t * the cascade — the error is routed through `onError` (if supplied) and\n\t * the next colder tier is tried. This mirrors how a multi-tier cache\n\t * falls through on a corrupt hot entry.\n\t *\n\t * Note: `restore()` mutates state incrementally. If a restore throws\n\t * partway through, the graph may hold a mixed state (some slices from\n\t * the bad tier, some pre-existing). A subsequent successful tier's\n\t * `restore()` overwrites the overlapping slices.\n\t *\n\t * Internal helper shared by {@link Graph.attachStorage}'s `autoRestore`\n\t * option and the static {@link Graph.fromStorage} factory.\n\t */\n\tprivate async _cascadeRestore(\n\t\ttiers: readonly StorageTier[],\n\t\tonError?: (err: unknown, tier: StorageTier) => void,\n\t): Promise<boolean> {\n\t\tfor (const tier of tiers) {\n\t\t\tlet raw: unknown;\n\t\t\ttry {\n\t\t\t\traw = await tier.load(this.name);\n\t\t\t} catch (err) {\n\t\t\t\tonError?.(err, tier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (raw == null) continue;\n\t\t\tif (typeof raw !== \"object\" || Array.isArray(raw)) continue;\n\t\t\tconst record = raw as Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\t// Accept both a `GraphCheckpointRecord` envelope\n\t\t\t\t// (`mode === \"full\"`) and a bare `GraphPersistSnapshot` (the\n\t\t\t\t// shape written by `saveGraphCheckpoint`). Bare snapshots\n\t\t\t\t// carry `version: 1`.\n\t\t\t\tif (record.mode === \"full\" && record.snapshot != null) {\n\t\t\t\t\tthis.restore(record.snapshot as GraphPersistSnapshot);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (record.version === SNAPSHOT_VERSION && record.nodes != null) {\n\t\t\t\t\tthis.restore(record as GraphPersistSnapshot);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tonError?.(err, tier);\n\t\t\t\t// Fall through to the next tier.\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Construct a fresh {@link Graph} pre-hydrated from the first tier that\n\t * hits. Delegates topology reconstruction to {@link Graph.fromSnapshot}\n\t * on `\"full\"` records and direct {@link Graph.restore} on bare snapshots.\n\t *\n\t * Always asynchronous — awaits `tier.load()` for async tier support even\n\t * when all tiers are sync. Callers that know they only pass sync tiers\n\t * can safely `await` immediately.\n\t *\n\t * @throws If no tier holds a restorable record matching `name` *and* no\n\t * `factories` override is provided for dynamic nodes.\n\t */\n\tstatic async fromStorage(\n\t\tname: string,\n\t\ttiers: readonly StorageTier[],\n\t\topts?: GraphOptions & {\n\t\t\tfactories?: Record<string, GraphNodeFactory>;\n\t\t\t/**\n\t\t\t * Called when a tier throws during `load()` or when\n\t\t\t * {@link Graph.fromSnapshot} rejects a tier's record. The cascade\n\t\t\t * falls through to the next colder tier regardless.\n\t\t\t */\n\t\t\tonError?: (err: unknown, tier: StorageTier) => void;\n\t\t},\n\t): Promise<Graph> {\n\t\tfor (const tier of tiers) {\n\t\t\tlet raw: unknown;\n\t\t\ttry {\n\t\t\t\traw = await tier.load(name);\n\t\t\t} catch (err) {\n\t\t\t\topts?.onError?.(err, tier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (raw == null) continue;\n\t\t\tif (typeof raw !== \"object\" || Array.isArray(raw)) continue;\n\t\t\tconst record = raw as Record<string, unknown>;\n\t\t\tconst snapshot: GraphPersistSnapshot | undefined =\n\t\t\t\trecord.mode === \"full\" && record.snapshot != null\n\t\t\t\t\t? (record.snapshot as GraphPersistSnapshot)\n\t\t\t\t\t: record.version === SNAPSHOT_VERSION && record.nodes != null\n\t\t\t\t\t\t? (record as GraphPersistSnapshot)\n\t\t\t\t\t\t: undefined;\n\t\t\tif (snapshot == null) continue;\n\t\t\ttry {\n\t\t\t\treturn Graph.fromSnapshot(snapshot, opts);\n\t\t\t} catch (err) {\n\t\t\t\topts?.onError?.(err, tier);\n\t\t\t\t// Fall through to colder tier.\n\t\t\t}\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Graph.fromStorage: no tier held a restorable record for \"${name}\" across ${tiers.length} tier(s)`,\n\t\t);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Inspector (roadmap 3.3) — reasoning trace, overhead gating\n\t// ——————————————————————————————————————————————————————————————\n\n\t// Inspector gating lives on `this.config.inspectorEnabled` (see\n\t// `core/config.ts`). Default: `true` outside `NODE_ENV === \"production\"`.\n\n\tprivate _annotations = new Map<string, string>();\n\tprivate readonly _traceRing: RingBuffer<TraceEntry>;\n\n\t/**\n\t * Unified reasoning trace: write annotations or read the ring buffer.\n\t *\n\t * Write: `graph.trace(\"path\", \"reason\")` — attaches a reasoning annotation\n\t * to a node, capturing *why* an AI agent set a value. Unknown paths are\n\t * silently dropped (matching `observe` resilience). No-op when\n\t * `config.inspectorEnabled` is `false`.\n\t *\n\t * Read: `graph.trace()` — returns a chronological log of all annotations.\n\t * Returns `[]` when `config.inspectorEnabled` is `false`.\n\t */\n\ttrace(path: string, reason: string, opts?: { actor?: Actor }): void;\n\ttrace(): readonly TraceEntry[];\n\ttrace(\n\t\tpath?: string,\n\t\treason?: string,\n\t\topts?: { actor?: Actor },\n\t): undefined | readonly TraceEntry[] {\n\t\tif (path != null && reason != null) {\n\t\t\tif (!this.config.inspectorEnabled) return;\n\t\t\t// Silent-drop unknown paths — matches `observe` resilience. Callers\n\t\t\t// with robust path-hygiene needs can pre-check via `tryResolve`.\n\t\t\tif (this.tryResolve(path) == null) return;\n\t\t\tthis._annotations.set(path, reason);\n\t\t\tconst entry: TraceEntry = {\n\t\t\t\tpath,\n\t\t\t\treason,\n\t\t\t\ttimestamp_ns: monotonicNs(),\n\t\t\t\t...(opts?.actor != null ? { actor: opts.actor } : {}),\n\t\t\t};\n\t\t\tthis._traceRing.push(entry);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.config.inspectorEnabled) return [];\n\t\treturn this._traceRing.toArray();\n\t}\n\n\t/**\n\t * Latest reason annotation attached to `path` via {@link Graph.trace},\n\t * or `undefined` if none. `describe()` surfaces this via the `reason`\n\t * field on each node entry (when present).\n\t */\n\tannotation(path: string): string | undefined {\n\t\treturn this._annotations.get(path);\n\t}\n\n\t/**\n\t * Clear all reasoning-trace state (both the per-path annotations map and\n\t * the ring buffer). Useful for long-running processes that want periodic\n\t * resets, or tests that need a clean slate.\n\t */\n\tclearTrace(): void {\n\t\tthis._annotations.clear();\n\t\tthis._traceRing.clear();\n\t}\n\n\t/**\n\t * Remove trace entries matching `predicate`. Returns the number of\n\t * entries removed. Does not touch the per-path annotations map — call\n\t * {@link Graph.clearTrace} for a full reset.\n\t */\n\tpruneTrace(predicate: (entry: TraceEntry) => boolean): number {\n\t\tconst kept = this._traceRing.toArray().filter((e) => !predicate(e));\n\t\tconst removed = this._traceRing.size - kept.length;\n\t\tthis._traceRing.clear();\n\t\tfor (const e of kept) this._traceRing.push(e);\n\t\treturn removed;\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\t\tconst versionChanges: GraphVersionChange[] = [];\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\tconst av = na.v;\n\t\t\tconst bv = nb.v;\n\t\t\t// Surface version bumps (even if value is identical, the bump itself\n\t\t\t// is meaningful for audit / wire-efficient sync).\n\t\t\tif (av != null && bv != null && av.id === bv.id && av.version !== bv.version) {\n\t\t\t\tversionChanges.push({\n\t\t\t\t\tpath: key,\n\t\t\t\t\tid: av.id,\n\t\t\t\t\tfrom: av.version,\n\t\t\t\t\tto: bv.version,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst versionMatches =\n\t\t\t\tav != null && bv != null && av.id === bv.id && av.version === bv.version;\n\t\t\t// V0 fast path: when versions match, skip value / meta compare —\n\t\t\t// upstream is guaranteed unchanged by protocol. Only type/status\n\t\t\t// (cheap string compare) + sentinel flip are possible.\n\t\t\tfor (const field of [\"type\", \"status\", \"sentinel\"] 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 (va !== 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\tif (versionMatches) continue;\n\t\t\t// Full slow-path: deep-equal on value + meta.\n\t\t\tfor (const field of [\"value\", \"meta\"] 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 (!deepEqual(va, 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\tversionChanges,\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\t/**\n\t * Actor that produced the annotation (optional). Enables multi-agent\n\t * attribution: distinguish \"LLM set this rootCause\" from \"human approved\n\t * this intervention\" in the trace log.\n\t */\n\tactor?: Actor;\n};\n\n/** Result of {@link Graph.diff}. */\nexport type GraphDiffResult = {\n\tnodesAdded: string[];\n\tnodesRemoved: string[];\n\tnodesChanged: GraphDiffChange[];\n\t/**\n\t * V0 version bumps (same `v.id`, different `v.version`). Surfaced even\n\t * when values are identical — the bump itself is audit-meaningful.\n\t */\n\tversionChanges: GraphVersionChange[];\n\tedgesAdded: Array<{ from: string; to: string }>;\n\tedgesRemoved: Array<{ from: string; to: string }>;\n\tsubgraphsAdded: string[];\n\tsubgraphsRemoved: string[];\n};\n\n/**\n * WAL-oriented diff — extends {@link GraphDiffResult} with the full node\n * slice for each added path so {@link replayWAL} can reconstruct nodes added\n * between full anchors (topology mutations inside a `compactEvery` window).\n *\n * `Graph.diff()` returns the audit shape (no payload); `attachStorage` writes\n * this WAL shape. The two shapes stay structurally compatible — `GraphWALDiff`\n * is a superset.\n */\nexport type GraphWALDiff = GraphDiffResult & {\n\t/**\n\t * Full node slices for every path in `nodesAdded`, keyed by path. Applied\n\t * verbatim to `snapshot.nodes[path]` during replay.\n\t */\n\tnodesAddedFull: Record<string, DescribeNodeOutput>;\n};\n\n/**\n * Build a WAL-ready diff between two snapshots: the structural diff from\n * {@link Graph.diff} plus the full node slice for each added path (pulled\n * from `b.nodes`). Callers that only need the audit shape should use\n * `Graph.diff` directly.\n */\nexport function diffForWAL(a: GraphDescribeOutput, b: GraphDescribeOutput): GraphWALDiff {\n\tconst base = Graph.diff(a, b);\n\tconst nodesAddedFull: Record<string, DescribeNodeOutput> = {};\n\tfor (const path of base.nodesAdded) {\n\t\tconst slice = b.nodes[path];\n\t\tif (slice != null) nodesAddedFull[path] = slice;\n\t}\n\treturn { ...base, nodesAddedFull };\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/** A single V0 version bump within a diff. */\nexport type GraphVersionChange = {\n\tpath: string;\n\tid: string;\n\tfrom: number;\n\tto: number;\n};\n\n/** Audit record returned by {@link Graph.remove}. */\nexport type GraphRemoveAudit = {\n\t/** Whether the removed entry was a local node or a mount. */\n\tkind: \"node\" | \"mount\";\n\t/**\n\t * Primary nodes torn down by this `remove()`. For `kind: \"node\"` contains\n\t * just the removed name; for `kind: \"mount\"` lists every primary node in\n\t * the unmounted subtree (qualified paths relative to the mount point,\n\t * sorted).\n\t */\n\tnodes: string[];\n\t/**\n\t * Mounted subgraphs that were unmounted. For `kind: \"node\"` this is empty;\n\t * for `kind: \"mount\"` starts with the top-level mount name and lists its\n\t * descendants in depth-first order.\n\t */\n\tmounts: string[];\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\t/**\n\t * Traverse both directions in one pass (union of upstream + downstream).\n\t * Ignores the `direction` arg when set.\n\t */\n\tboth?: boolean;\n\t/**\n\t * Return the richer {@link ReachableResult} shape (paths + per-path\n\t * hop depth + truncation flag) instead of the flat sorted string array.\n\t */\n\twithDetail?: boolean;\n};\n\n/** Rich reachable result (opt-in via `{withDetail: true}`). */\nexport type ReachableResult = {\n\t/** Reachable paths, sorted lexicographically. */\n\tpaths: string[];\n\t/** Hop depth from `from` to each reachable path. */\n\tdepths: Map<string, number>;\n\t/** True when traversal hit `maxDepth` and some neighbors were not explored. */\n\ttruncated: boolean;\n};\n\n/**\n * Reachability query over a {@link Graph.describe} snapshot.\n *\n * Traversal follows `deps` (upstream) and reverse-`deps` (downstream). Edges\n * are derived from deps post Unit 7, so `edges[]` in the snapshot is\n * redundant with deps — it's walked defensively in case a caller supplied a\n * pre-Unit-7 snapshot.\n *\n * @param described - `graph.describe()` output to traverse.\n * @param from - Start path (qualified node path).\n * @param direction - Traversal direction (ignored when `opts.both` is `true`).\n * @param options - Optional `maxDepth`, `both`, `withDetail`.\n * @returns Sorted paths (flat) — or {@link ReachableResult} when `withDetail: true`.\n */\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions?: ReachableOptions & { withDetail: true },\n): ReachableResult;\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions?: ReachableOptions,\n): string[];\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions: ReachableOptions = {},\n): string[] | ReachableResult {\n\tconst empty: ReachableResult = { paths: [], depths: new Map(), truncated: false };\n\tif (!from) return options.withDetail ? empty : [];\n\tif (!options.both && 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 options.withDetail ? empty : [];\n\n\tconst depsByPath = new Map<string, readonly 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\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\tif (!path) continue;\n\t\tuniverse.add(path);\n\t\tconst deps = node.deps ?? [];\n\t\tdepsByPath.set(path, deps);\n\t\tfor (const dep of deps) {\n\t\t\tif (!dep) continue;\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\t// Edges are normally derived from deps post Unit 7, but synthetic snapshots\n\t// (e.g. test fixtures) may declare edges independently — walk both for\n\t// compatibility. Minimal null/string checks for malformed JSON.\n\tfor (const edge of described.edges) {\n\t\tif (edge == null || typeof edge !== \"object\") continue;\n\t\tconst from = typeof edge.from === \"string\" ? edge.from : \"\";\n\t\tconst to = typeof edge.to === \"string\" ? edge.to : \"\";\n\t\tif (!from || !to) continue;\n\t\tuniverse.add(from);\n\t\tuniverse.add(to);\n\t\tif (!outgoingEdges.has(from)) outgoingEdges.set(from, new Set());\n\t\toutgoingEdges.get(from)!.add(to);\n\t\tif (!incomingEdges.has(to)) incomingEdges.set(to, new Set());\n\t\tincomingEdges.get(to)!.add(from);\n\t}\n\n\tif (!universe.has(from)) return options.withDetail ? empty : [];\n\n\tconst doBoth = options.both === true;\n\tconst visit = (path: string): readonly string[] => {\n\t\tif (doBoth) {\n\t\t\tconst up = depsByPath.get(path) ?? [];\n\t\t\tconst upEdges = incomingEdges.get(path);\n\t\t\tconst down = reverseDeps.get(path);\n\t\t\tconst downEdges = outgoingEdges.get(path);\n\t\t\tconst acc: string[] = [...up];\n\t\t\tif (upEdges) acc.push(...upEdges);\n\t\t\tif (down) acc.push(...down);\n\t\t\tif (downEdges) acc.push(...downEdges);\n\t\t\treturn acc;\n\t\t}\n\t\tif (direction === \"upstream\") {\n\t\t\tconst up = depsByPath.get(path) ?? [];\n\t\t\tconst upEdges = incomingEdges.get(path);\n\t\t\tif (!upEdges) return up;\n\t\t\treturn [...up, ...upEdges];\n\t\t}\n\t\tconst down = reverseDeps.get(path);\n\t\tconst downEdges = outgoingEdges.get(path);\n\t\tconst acc: string[] = down ? [...down] : [];\n\t\tif (downEdges) acc.push(...downEdges);\n\t\treturn acc;\n\t};\n\n\t// Head-index BFS — avoids O(n²) from `Array.prototype.shift`.\n\tconst visited = new Set<string>([from]);\n\tconst depths = new Map<string, number>();\n\tconst queue: Array<{ path: string; depth: number }> = [{ path: from, depth: 0 }];\n\tlet head = 0;\n\tlet truncated = false;\n\twhile (head < queue.length) {\n\t\tconst next = queue[head++]!;\n\t\tif (maxDepth != null && next.depth >= maxDepth) {\n\t\t\t// Flag truncation only if this node actually has unexplored neighbors.\n\t\t\tif (visit(next.path).length > 0) truncated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const nb of visit(next.path)) {\n\t\t\tif (!nb || visited.has(nb)) continue;\n\t\t\tvisited.add(nb);\n\t\t\tdepths.set(nb, next.depth + 1);\n\t\t\tqueue.push({ path: nb, depth: next.depth + 1 });\n\t\t}\n\t}\n\n\tconst paths = [...depths.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n\tif (options.withDetail) return { paths, depths, truncated };\n\treturn paths;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcO,IAAM,WAAW;AAAA,EACvB,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,MAAM;AAAA,EACN,WAAW;AAAA,EACX,QAAQ;AAAA,EACR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