@graphrefly/graphrefly 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +234 -0
- package/dist/chunk-5X3LAO3B.js +1571 -0
- package/dist/chunk-5X3LAO3B.js.map +1 -0
- package/dist/chunk-6W5SGIGB.js +1793 -0
- package/dist/chunk-6W5SGIGB.js.map +1 -0
- package/dist/chunk-CP6MNKAA.js +97 -0
- package/dist/chunk-CP6MNKAA.js.map +1 -0
- package/dist/chunk-HP7OKEOE.js +107 -0
- package/dist/chunk-HP7OKEOE.js.map +1 -0
- package/dist/chunk-KWXPDASV.js +781 -0
- package/dist/chunk-KWXPDASV.js.map +1 -0
- package/dist/chunk-O3PI7W45.js +68 -0
- package/dist/chunk-O3PI7W45.js.map +1 -0
- package/dist/chunk-QW7H3ICI.js +1372 -0
- package/dist/chunk-QW7H3ICI.js.map +1 -0
- package/dist/chunk-VPS7L64N.js +4785 -0
- package/dist/chunk-VPS7L64N.js.map +1 -0
- package/dist/chunk-Z4Y4FMQN.js +1097 -0
- package/dist/chunk-Z4Y4FMQN.js.map +1 -0
- package/dist/compat/nestjs/index.cjs +4883 -0
- package/dist/compat/nestjs/index.cjs.map +1 -0
- package/dist/compat/nestjs/index.d.cts +7 -0
- package/dist/compat/nestjs/index.d.ts +7 -0
- package/dist/compat/nestjs/index.js +84 -0
- package/dist/compat/nestjs/index.js.map +1 -0
- package/dist/core/index.cjs +1632 -0
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.cts +2 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +90 -0
- package/dist/core/index.js.map +1 -0
- package/dist/extra/index.cjs +6885 -0
- package/dist/extra/index.cjs.map +1 -0
- package/dist/extra/index.d.cts +5 -0
- package/dist/extra/index.d.ts +5 -0
- package/dist/extra/index.js +290 -0
- package/dist/extra/index.js.map +1 -0
- package/dist/graph/index.cjs +3225 -0
- package/dist/graph/index.cjs.map +1 -0
- package/dist/graph/index.d.cts +3 -0
- package/dist/graph/index.d.ts +3 -0
- package/dist/graph/index.js +25 -0
- package/dist/graph/index.js.map +1 -0
- package/dist/graph-CL_ZDAj9.d.cts +605 -0
- package/dist/graph-D18qmsNm.d.ts +605 -0
- package/dist/index-B6SsZs2h.d.cts +3463 -0
- package/dist/index-B7eOdgEx.d.ts +449 -0
- package/dist/index-BHUvlQ3v.d.ts +3463 -0
- package/dist/index-BtK55IE2.d.ts +231 -0
- package/dist/index-BvhgZRHK.d.cts +231 -0
- package/dist/index-Bvy_6CaN.d.ts +452 -0
- package/dist/index-C3BMRmmp.d.cts +449 -0
- package/dist/index-C5mqLhMX.d.cts +452 -0
- package/dist/index-CP_QvbWu.d.ts +940 -0
- package/dist/index-D_geH2Bm.d.cts +940 -0
- package/dist/index.cjs +14843 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1517 -0
- package/dist/index.d.ts +1517 -0
- package/dist/index.js +3649 -0
- package/dist/index.js.map +1 -0
- package/dist/meta-BsF6Sag9.d.cts +607 -0
- package/dist/meta-BsF6Sag9.d.ts +607 -0
- package/dist/patterns/reactive-layout/index.cjs +4143 -0
- package/dist/patterns/reactive-layout/index.cjs.map +1 -0
- package/dist/patterns/reactive-layout/index.d.cts +3 -0
- package/dist/patterns/reactive-layout/index.d.ts +3 -0
- package/dist/patterns/reactive-layout/index.js +38 -0
- package/dist/patterns/reactive-layout/index.js.map +1 -0
- package/dist/reactive-log-BfvfNWQh.d.cts +137 -0
- package/dist/reactive-log-ohLmTXoZ.d.ts +137 -0
- package/package.json +256 -0
|
@@ -0,0 +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.ts","../../src/core/dynamic-node.ts","../../src/core/meta.ts","../../src/core/sugar.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 GraphDescribeOutput,\n\ttype GraphDiagramDirection,\n\ttype GraphDiagramOptions,\n\ttype GraphDiffChange,\n\ttype GraphDiffResult,\n\ttype GraphDumpOptions,\n\ttype GraphFactoryContext,\n\ttype GraphNodeFactory,\n\ttype GraphObserveAll,\n\ttype GraphObserveOne,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n\ttype GraphSpyHandle,\n\ttype GraphSpyOptions,\n\ttype GraphSpyTheme,\n\ttype GraphSpyThemeName,\n\ttype ObserveEvent,\n\ttype ObserveOptions,\n\ttype ObserveResult,\n\ttype ReachableDirection,\n\ttype ReachableOptions,\n\treachable,\n\ttype TraceEntry,\n} from \"./graph.js\";\n","/**\n * GraphCodec — pluggable serialization for graph snapshots (Phase 8.6).\n *\n * Design reference: `archive/docs/SESSION-serialization-memory-footprint.md`\n *\n * The codec interface decouples snapshot format from graph internals.\n * Default is JSON (current behavior). DAG-CBOR and compressed variants\n * ship as optional codecs. FlatBuffers/Arrow for advanced tiers.\n *\n * Tiered representation:\n * HOT — JS objects (live propagation, no codec involved)\n * WARM — DAG-CBOR in-memory buffer (lazy hydration, delta checkpoints)\n * COLD — Arrow/Parquet (bulk storage, ML pipelines, archival)\n * PEEK — FlatBuffers (zero-copy read from dormant graph)\n */\n\nimport type { GraphPersistSnapshot } from \"./graph.js\";\n\n// ---------------------------------------------------------------------------\n// Core codec interface\n// ---------------------------------------------------------------------------\n\n/**\n * Encode/decode graph snapshots to/from binary.\n *\n * Implementations must be deterministic: `encode(x)` always produces the\n * same bytes for the same input. This is critical for CID computation (V1)\n * and snapshot hash-comparison.\n */\nexport interface GraphCodec {\n\t/** MIME-like content type identifier (e.g. \"application/dag-cbor+zstd\"). */\n\treadonly contentType: string;\n\n\t/** Human-readable name for diagnostics. */\n\treadonly name: string;\n\n\t/** Encode a snapshot to binary. */\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array;\n\n\t/**\n\t * Decode binary back to a snapshot.\n\t *\n\t * For lazy codecs, this may return a proxy that decodes nodes on access\n\t * (see {@link LazyGraphCodec}).\n\t */\n\tdecode(buffer: Uint8Array): GraphPersistSnapshot;\n}\n\n/**\n * Extended codec that supports lazy (on-demand) node decoding.\n *\n * `decodeLazy` returns a snapshot where `nodes` is a Proxy — individual\n * nodes are decoded only when accessed. This enables near-zero cold-start\n * for large graphs (decode envelope + topology, skip node values until read).\n */\nexport interface LazyGraphCodec extends GraphCodec {\n\t/** Decode envelope and topology; defer node value decoding to access time. */\n\tdecodeLazy(buffer: Uint8Array): GraphPersistSnapshot;\n}\n\n// ---------------------------------------------------------------------------\n// Delta checkpoint types (requires V0 — Phase 6.0)\n// ---------------------------------------------------------------------------\n\n/**\n * A delta checkpoint: only the nodes that changed since last checkpoint.\n *\n * Append-only: each delta is identified by `seq` (monotonic). A full\n * snapshot is taken every `compactEvery` deltas for WAL compaction.\n */\nexport interface DeltaCheckpoint {\n\t/** Monotonic sequence number. */\n\tseq: number;\n\t/** Graph name. */\n\tname: string;\n\t/** Base snapshot seq this delta applies to (0 = initial full snapshot). */\n\tbaseSec: number;\n\t/** Only nodes with version > lastCheckpoint. Keyed by node name. */\n\tnodes: Record<\n\t\tstring,\n\t\t{\n\t\t\t/** V0 version at time of checkpoint. */\n\t\t\tversion: number;\n\t\t\t/** Serialized node value (codec-dependent). */\n\t\t\tvalue: unknown;\n\t\t\t/** Meta snapshot (only if materialized). */\n\t\t\tmeta?: Record<string, unknown>;\n\t\t}\n\t>;\n\t/** Nodes removed since last checkpoint. */\n\tremoved: string[];\n\t/** Edges added since last checkpoint. */\n\tedgesAdded: ReadonlyArray<{ from: string; to: string }>;\n\t/** Edges removed since last checkpoint. */\n\tedgesRemoved: ReadonlyArray<{ from: string; to: string }>;\n\t/** Timestamp (wall-clock ns) of this checkpoint. */\n\ttimestampNs: bigint;\n}\n\n/**\n * WAL entry: either a full snapshot or a delta.\n */\nexport type WALEntry =\n\t| { type: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { type: \"delta\"; delta: DeltaCheckpoint };\n\n// ---------------------------------------------------------------------------\n// Eviction policy (dormant subgraph management)\n// ---------------------------------------------------------------------------\n\n/**\n * Policy for evicting dormant subgraphs to reduce memory.\n *\n * When a subgraph hasn't propagated for `idleTimeoutMs`, it is serialized\n * using the graph's codec and JS objects are released. Re-hydrated on next\n * access (read, propagation, describe).\n */\nexport interface EvictionPolicy {\n\t/** Milliseconds of inactivity before eviction. */\n\tidleTimeoutMs: number;\n\t/** Codec to use for serializing evicted subgraphs (default: graph's codec). */\n\tcodec?: GraphCodec;\n}\n\n/** Metadata about an evicted subgraph, exposed via describe(). */\nexport interface EvictedSubgraphInfo {\n\t/** True if currently evicted (serialized, JS objects released). */\n\tevicted: true;\n\t/** Wall-clock ns of last propagation before eviction. */\n\tlastActiveNs: bigint;\n\t/** Size of serialized buffer in bytes. */\n\tserializedBytes: number;\n\t/** Codec used for serialization. */\n\tcodecName: string;\n}\n\n// ---------------------------------------------------------------------------\n// JSON codec (default — wraps current behavior)\n// ---------------------------------------------------------------------------\n\n/**\n * Default JSON codec. Wraps `JSON.stringify`/`JSON.parse` with deterministic\n * key ordering (matching current `snapshot()` behavior).\n */\nexport const JsonCodec: GraphCodec = {\n\tcontentType: \"application/json\",\n\tname: \"json\",\n\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array {\n\t\t// Deterministic: snapshot() already sorts keys.\n\t\tconst json = JSON.stringify(snapshot);\n\t\treturn new TextEncoder().encode(json);\n\t},\n\n\tdecode(buffer: Uint8Array): GraphPersistSnapshot {\n\t\tconst json = new TextDecoder().decode(buffer);\n\t\treturn JSON.parse(json) as GraphPersistSnapshot;\n\t},\n};\n\n// ---------------------------------------------------------------------------\n// DAG-CBOR codec (stub — requires @ipld/dag-cbor)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a DAG-CBOR codec.\n *\n * Requires `@ipld/dag-cbor` as a peer dependency. ~40-50% smaller than JSON,\n * deterministic encoding (required for V1 CID), CID links as native type.\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * const codec = createDagCborCodec(dagCbor);\n * const bytes = codec.encode(graph.snapshot());\n * ```\n */\nexport function createDagCborCodec(dagCbor: {\n\tencode: (value: unknown) => Uint8Array;\n\tdecode: (bytes: Uint8Array) => unknown;\n}): GraphCodec {\n\treturn {\n\t\tcontentType: \"application/dag-cbor\",\n\t\tname: \"dag-cbor\",\n\t\tencode: (snapshot) => dagCbor.encode(snapshot),\n\t\tdecode: (buffer) => dagCbor.decode(buffer) as GraphPersistSnapshot,\n\t};\n}\n\n/**\n * Create a DAG-CBOR + zstd codec. ~80-90% smaller than JSON.\n *\n * Requires `@ipld/dag-cbor` and a zstd implementation (e.g. `fzstd` for\n * browser, `node:zlib` for Node.js).\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * import { compressSync, decompressSync } from \"fzstd\";\n * const codec = createDagCborZstdCodec(dagCbor, { compressSync, decompressSync });\n * ```\n */\nexport function createDagCborZstdCodec(\n\tdagCbor: {\n\t\tencode: (value: unknown) => Uint8Array;\n\t\tdecode: (bytes: Uint8Array) => unknown;\n\t},\n\tzstd: {\n\t\tcompressSync: (data: Uint8Array) => Uint8Array;\n\t\tdecompressSync: (data: Uint8Array) => Uint8Array;\n\t},\n): GraphCodec {\n\treturn {\n\t\tcontentType: \"application/dag-cbor+zstd\",\n\t\tname: \"dag-cbor-zstd\",\n\t\tencode: (snapshot) => zstd.compressSync(dagCbor.encode(snapshot)),\n\t\tdecode: (buffer) => dagCbor.decode(zstd.decompressSync(buffer)) as GraphPersistSnapshot,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Codec negotiation (for peerGraph)\n// ---------------------------------------------------------------------------\n\n/**\n * Negotiate a common codec between two peers.\n *\n * Each peer advertises its supported codecs (ordered by preference).\n * Returns the first codec supported by both, or null if none.\n */\nexport function negotiateCodec(\n\tlocalPreference: readonly GraphCodec[],\n\tremoteContentTypes: readonly string[],\n): GraphCodec | null {\n\tconst remoteSet = new Set(remoteContentTypes);\n\tfor (const codec of localPreference) {\n\t\tif (remoteSet.has(codec.contentType)) return codec;\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// WAL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Reconstruct a snapshot from a WAL (full snapshot + sequence of deltas).\n *\n * Applies deltas in order on top of the base snapshot. Validates that\n * delta `baseSec` chains correctly.\n */\nexport function replayWAL(entries: readonly WALEntry[]): GraphPersistSnapshot {\n\tif (entries.length === 0) {\n\t\tthrow new Error(\"WAL is empty — need at least one full snapshot\");\n\t}\n\n\tconst first = entries[0]!;\n\tif (first.type !== \"full\") {\n\t\tthrow new Error(\"WAL must start with a full snapshot\");\n\t}\n\n\t// Deep clone the base snapshot so we can mutate it.\n\tconst result: GraphPersistSnapshot = JSON.parse(JSON.stringify(first.snapshot));\n\n\tfor (let i = 1; i < entries.length; i++) {\n\t\tconst entry = entries[i]!;\n\t\tif (entry.type === \"full\") {\n\t\t\t// A compaction point — replace the entire result.\n\t\t\tObject.assign(result, JSON.parse(JSON.stringify(entry.snapshot)));\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst delta = entry.delta;\n\n\t\t// Apply node changes.\n\t\tfor (const [name, patch] of Object.entries(delta.nodes)) {\n\t\t\tif (result.nodes[name]) {\n\t\t\t\tresult.nodes[name]!.value = patch.value;\n\t\t\t\tif (patch.meta) {\n\t\t\t\t\tresult.nodes[name]!.meta = patch.meta;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Apply removals.\n\t\tfor (const name of delta.removed) {\n\t\t\tdelete result.nodes[name];\n\t\t}\n\n\t\t// Apply edge changes.\n\t\tconst edges = [...result.edges];\n\t\tfor (const edge of delta.edgesRemoved) {\n\t\t\tconst idx = edges.findIndex((e) => e.from === edge.from && e.to === edge.to);\n\t\t\tif (idx !== -1) edges.splice(idx, 1);\n\t\t}\n\t\tfor (const edge of delta.edgesAdded) {\n\t\t\tedges.push(edge);\n\t\t}\n\t\t(result as unknown as { edges: typeof edges }).edges = edges;\n\t}\n\n\treturn result;\n}\n","/**\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 | DIRTY, INVALIDATE | Notification | Immediate (never deferred) |\n * | 1 | PAUSE, RESUME | Flow control | Immediate (never deferred) |\n * | 2 | DATA, RESOLVED | Value settlement | Deferred inside `batch()` |\n * | 3 | COMPLETE, ERROR | Terminal lifecycle | Deferred to after phase-2 |\n * | 4 | TEARDOWN | Destruction | Immediate (usually sent alone) |\n *\n * **Rule:** Within `emitWithBatch`, 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 0 (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/** Value delivery (`DATA`, value). Tier 2 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 0 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 2 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 0 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 1 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 1 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 4 — immediate (usually sent alone). */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 3 — delivered after phase-2 in the same batch. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 3 — 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\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tINVALIDATE,\n\tPAUSE,\n\tRESUME,\n\tTEARDOWN,\n\tCOMPLETE,\n\tERROR,\n];\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 knownMessageTypes.includes(t);\n}\n\n/**\n * Returns the signal tier for a message type (see module-level ordering table).\n *\n * - 0: notification (DIRTY, INVALIDATE) — immediate\n * - 1: flow control (PAUSE, RESUME) — immediate\n * - 2: value (DATA, RESOLVED) — deferred inside `batch()`\n * - 3: terminal (COMPLETE, ERROR) — delivered after phase-2\n * - 4: destruction (TEARDOWN) — immediate, usually alone\n * - 0 for unknown types (forward-compat: immediate)\n *\n * @param t — Message type symbol.\n * @returns Tier number (0–4).\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, TEARDOWN, messageTier } from \"@graphrefly/graphrefly-ts\";\n *\n * messageTier(DIRTY); // 0\n * messageTier(DATA); // 2\n * messageTier(COMPLETE); // 3\n * messageTier(TEARDOWN); // 4\n * ```\n */\nexport function messageTier(t: symbol): number {\n\tif (t === DIRTY || t === INVALIDATE) return 0;\n\tif (t === PAUSE || t === RESUME) return 1;\n\tif (t === DATA || t === RESOLVED) return 2;\n\tif (t === COMPLETE || t === ERROR) return 3;\n\tif (t === TEARDOWN) return 4;\n\treturn 0; // unknown → immediate\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` 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\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 `emitWithBatch`\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 `emitWithBatch` / `node.down()`.\n * @returns `void` — all side-effects happen through `emitWithBatch` 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.emitWithBatch(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\tlet firstError: unknown;\n\tlet hasError = false;\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\tif (!hasError) {\n\t\t\t\t\t\t\tfirstError = e;\n\t\t\t\t\t\t\thasError = true;\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// 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\tif (!hasError) {\n\t\t\t\t\t\t\tfirstError = e;\n\t\t\t\t\t\t\thasError = true;\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\t} finally {\n\t\tif (ownsFlush) {\n\t\t\tflushInProgress = false;\n\t\t}\n\t}\n\tif (hasError) {\n\t\tthrow firstError;\n\t}\n}\n\n/**\n * Splits a message array into three groups by signal tier (see `messages.ts`):\n *\n * - **immediate** — tier 0–1: DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN, unknown\n * - **deferred** — tier 2: DATA, RESOLVED (phase-2, deferred inside `batch()`)\n * - **terminal** — tier 3: 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 through `emit`, applying batch semantics and canonical\n * tier-based ordering (see `messages.ts`):\n *\n * 1. **Immediate** (tier 0–1, 4): DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN,\n * unknown — emitted synchronously.\n * 2. **Phase-2** (tier 2): DATA, RESOLVED — deferred while `isBatching()`.\n * 3. **Terminal** (tier 3): 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 emitted 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 emit — 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 emission.\n * @returns `void` — delivery is performed through `emit` 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.emitWithBatch((msgs) => console.log(msgs), [[core.DIRTY], [core.DATA, 42]]);\n * ```\n *\n * @category core\n */\nexport function emitWithBatch(\n\temit: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n): void {\n\tif (messages.length === 0) {\n\t\treturn;\n\t}\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(() => emit(messages));\n\t\t\t} else {\n\t\t\t\temit(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(() => emit(messages));\n\t\t\t} else {\n\t\t\t\temit(messages);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate: emit synchronously.\n\t\t\temit(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–1, 4) — emit synchronously now.\n\tif (immediate.length > 0) {\n\t\temit(immediate);\n\t}\n\n\t// 2. Deferred (tier 2) + Terminal (tier 3) — canonical order preserved.\n\tif (isBatching()) {\n\t\tif (deferred.length > 0) {\n\t\t\tqueue.push(() => emit(deferred));\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tqueue.push(() => emit(terminal));\n\t\t}\n\t} else {\n\t\tif (deferred.length > 0) {\n\t\t\temit(deferred);\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\temit(terminal);\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","import type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { emitWithBatch } 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\tPAUSE,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, NodeVersionInfo, VersioningLevel } from \"./versioning.js\";\nimport { advanceVersion, createVersioning, defaultHash } from \"./versioning.js\";\n\n/** Lifecycle status of a node. */\nexport type NodeStatus =\n\t| \"disconnected\"\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 * Compute function passed to `node()`.\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/** Imperative actions available inside a {@link NodeFn}. */\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.\n *\n * Called for every message from every dep. Return `true` to consume the\n * message (skip default handling), or `false` to let default dispatch run.\n *\n * @param msg — The message tuple `[Type, Data?]`.\n * @param depIndex — Which dep sent it (index into the deps array).\n * @param actions — `{ down(), emit(), up() }` — same as `NodeFn` receives.\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} / {@link describeNode} (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\n/** Options for {@link node}. */\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 disconnects upstream 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/**\n\t * Opt-in versioning level (GRAPHREFLY-SPEC §7).\n\t * - `0` (V0): `id` + `version` — identity & change detection.\n\t * - `1` (V1): + `cid` + `prev` — content addressing & linked history.\n\t */\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/**\n * Options for {@link Node.down} / {@link Node.up} (actor context, graph delivery mode, internal bypass).\n */\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} and direct `down`.\n\t */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/**\n * Optional hints passed to {@link Node.subscribe} to enable per-sink\n * optimizations.\n */\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 via `onDepSettled`.\n\t */\n\tsingleDep?: boolean;\n\t/**\n\t * Actor to check against the node's `observe` guard.\n\t * When set, `subscribe()` throws {@link GuardDenied} if the actor is not\n\t * permitted to observe this node. Aligned with graphrefly-py `subscribe(actor=)`.\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 {@link NodeTransportOptions.actor | actor} may {@link Graph.observe | 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// --- Bitmask helpers: integer for <=31 deps, Uint32Array for >31 ---\n\ninterface BitSet {\n\tset(index: number): void;\n\tclear(index: number): void;\n\thas(index: number): boolean;\n\t/**\n\t * True when all bits in `other` are also set in `this`.\n\t * IMPORTANT: `other` must be the same concrete type (both IntBitSet or both\n\t * ArrayBitSet). Cross-type calls will crash. Within `node()`, all masks for\n\t * a given node share the same `createBitSet(deps.length)` factory, so this\n\t * is always satisfied.\n\t */\n\tcovers(other: BitSet): boolean;\n\t/** True when at least one bit is set. */\n\tany(): boolean;\n\treset(): void;\n}\n\nfunction createIntBitSet(): BitSet {\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\treturn (\n\t\t\t\t(bits & (other as unknown as { _bits(): number })._bits()) ===\n\t\t\t\t(other as unknown as { _bits(): number })._bits()\n\t\t\t);\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\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\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\t_words: words,\n\t} as unknown as BitSet;\n}\n\nfunction createBitSet(size: number): BitSet {\n\treturn size <= 31 ? createIntBitSet() : createArrayBitSet(size);\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\nconst isCleanupFn = (value: unknown): value is () => void => typeof value === \"function\";\n\nconst 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// --- NodeImpl: class-based for V8 hidden class optimization and prototype method sharing ---\n\n/**\n * Class-based implementation of the {@link Node} interface.\n *\n * All internal state lives on instance fields (`_` prefix, private by convention)\n * so that introspection (e.g. {@link describeNode}) can read them directly via\n * `instanceof NodeImpl` — no side-channel registry needed.\n *\n * Follows callbag-recharge's `ProducerImpl` pattern: V8 hidden class stability,\n * prototype method sharing, selective binding for commonly detached methods.\n */\nexport class NodeImpl<T = unknown> implements Node<T> {\n\t// --- Configuration (set once, never reassigned) ---\n\tprivate readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\t/** @internal — read by {@link describeNode} before inference. */\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\t_deps: readonly Node[];\n\t_fn: NodeFn<T> | undefined;\n\t_opts: NodeOptions;\n\t_equals: (a: unknown, b: unknown) => boolean;\n\t_onMessage: OnMessageHandler | undefined;\n\t/** @internal — read by {@link describeNode} for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\tprivate _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\t_hasDeps: boolean;\n\t_autoComplete: boolean;\n\t_isSingleDep: boolean;\n\n\t// --- Mutable state ---\n\t_cached: T | undefined;\n\t_status: NodeStatus;\n\t_terminal = false;\n\t_connected = false;\n\t_producerStarted = false;\n\t_connecting = false;\n\t_manualEmitUsed = false;\n\t_sinkCount = 0;\n\t_singleDepSinkCount = 0;\n\n\t// --- Object/collection state ---\n\t_depDirtyMask: BitSet;\n\t_depSettledMask: BitSet;\n\t_depCompleteMask: BitSet;\n\t_allDepsCompleteMask: BitSet;\n\t_lastDepValues: readonly unknown[] | undefined;\n\t_cleanup: (() => void) | undefined;\n\t_sinks: NodeSink | Set<NodeSink> | null = null;\n\t_singleDepSinks = new WeakSet<NodeSink>();\n\t_upstreamUnsubs: Array<() => void> = [];\n\t_actions: NodeActions;\n\t_boundEmitToSinks: (messages: Messages) => void;\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\tprivate _versioning: NodeVersionInfo | undefined;\n\tprivate _hashFn: HashFn;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn<T> | undefined, opts: NodeOptions) {\n\t\tthis._deps = deps;\n\t\tthis._fn = fn;\n\t\tthis._opts = opts;\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._guard = opts.guard;\n\t\tthis._hasDeps = deps.length > 0;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._isSingleDep = deps.length === 1 && fn != null;\n\n\t\tthis._cached = opts.initial as T | undefined;\n\t\tthis._status = this._hasDeps ? \"disconnected\" : \"settled\";\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, {\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\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// Build companion meta nodes\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = node({\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\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t\t});\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions object: created once, references `this` methods.\n\t\t// Captures `this` via arrow-in-object so manualEmitUsed is set on the instance.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._manualEmitUsed = true;\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._manualEmitUsed = true;\n\t\t\t\tself._emitAutoValue(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\t// Bind commonly detached protocol methods\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t\tthis._boundEmitToSinks = this._emitToSinks.bind(this);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/**\n\t * When a node is registered with {@link Graph.add} without an options `name`,\n\t * the graph assigns the registry local name for introspection (parity with graphrefly-py).\n\t */\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// --- Public interface (Node<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/**\n\t * Retroactively apply versioning to a node that was created without it.\n\t * No-op if versioning is already enabled.\n\t *\n\t * Version starts at 0 regardless of prior DATA emissions — it tracks\n\t * changes from the moment versioning is enabled, not historical ones.\n\t *\n\t * @internal — used by {@link Graph.setVersioning}.\n\t */\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(level, this._cached, {\n\t\t\tid: opts?.id,\n\t\t\thash: this._hashFn,\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\tget(): T | undefined {\n\t\treturn 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._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\tprivate _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet lifecycleMessages = messages;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._opts.resubscribable) {\n\t\t\tconst terminalPassthrough = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (terminalPassthrough.length === 0) return;\n\t\t\tlifecycleMessages = terminalPassthrough;\n\t\t\tsinkMessages = terminalPassthrough;\n\t\t}\n\t\tthis._handleLocalLifecycle(lifecycleMessages);\n\t\t// Single-dep optimization: skip DIRTY to sinks when sole subscriber is single-dep\n\t\t// AND the batch contains a phase-2 message (DATA/RESOLVED). Standalone DIRTY\n\t\t// (without follow-up) must pass through so downstream is notified.\n\t\tif (this._canSkipDirty()) {\n\t\t\t// Inline check: does the batch contain DATA or RESOLVED?\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\t// Inline filter: remove DIRTY messages\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\temitWithBatch(this._boundEmitToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\temitWithBatch(this._boundEmitToSinks, sinkMessages);\n\t}\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\tif (this._terminal && this._opts.resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._status = this._hasDeps ? \"disconnected\" : \"settled\";\n\t\t\tthis._opts.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\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\tif (this._hasDeps) {\n\t\t\tthis._connectUpstream();\n\t\t} else if (this._fn) {\n\t\t\tthis._startProducer();\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._disconnectUpstream();\n\t\t\t\tthis._stopProducer();\n\t\t\t}\n\t\t};\n\t}\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._lastMutation = { actor, timestamp_ns: wallClockNs() };\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\tprivate _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// --- Private methods (prototype, _ prefix) ---\n\n\t_emitToSinks(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_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\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\t// GRAPHREFLY-SPEC §1.2: clear cached state; do not auto-emit from here.\n\t\t\t\tconst cleanupFn = this._cleanup;\n\t\t\t\tthis._cleanup = undefined;\n\t\t\t\tcleanupFn?.();\n\t\t\t\tthis._cached = undefined;\n\t\t\t\tthis._lastDepValues = undefined;\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._opts.resetOnTeardown) {\n\t\t\t\t\tthis._cached = undefined;\n\t\t\t\t}\n\t\t\t\t// Invoke cleanup for compute nodes (deps+fn) — spec §2.4\n\t\t\t\t// requires cleanup on teardown, not just before next invocation.\n\t\t\t\t// _stopProducer handles cleanup for producer nodes separately.\n\t\t\t\tconst teardownCleanup = this._cleanup;\n\t\t\t\tthis._cleanup = undefined;\n\t\t\t\tteardownCleanup?.();\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._disconnectUpstream();\n\t\t\t\t\tthis._stopProducer();\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Propagate other meta-eligible signals (centralized in messages.ts).\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/** Propagate a signal to all companion meta nodes (best-effort). */\n\t_propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\t(metaNode as NodeImpl)._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_canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\t_emitAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tconst unchanged = this._equals(this._cached, value);\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._cached = value as T;\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n\n\t_runFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._terminal && !this._opts.resubscribable) return;\n\t\tif (this._connecting) 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\t\t\t// Identity check BEFORE cleanup: if all dep values are unchanged,\n\t\t\t// skip cleanup+fn entirely 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\t\t\tconst prevCleanup = this._cleanup;\n\t\t\tthis._cleanup = undefined;\n\t\t\tprevCleanup?.();\n\t\t\tthis._manualEmitUsed = false;\n\t\t\tthis._lastDepValues = depValues;\n\t\t\tthis._inspectorHook?.({ kind: \"run\", depValues });\n\t\t\tconst out = this._fn(depValues, this._actions);\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._emitAutoValue(out);\n\t\t} catch (err) {\n\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t}\n\t}\n\n\t_onDepDirty(index: number): void {\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\t_onDepSettled(index: number): void {\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\t_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_handleDepMessages(index: number, messages: Messages): void {\n\t\tfor (const msg of messages) {\n\t\t\tthis._inspectorHook?.({ 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\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!this._fn) {\n\t\t\t\t// Passthrough: forward all messages except COMPLETE when multi-dep.\n\t\t\t\t// Multi-dep passthrough must wait 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\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\t// Complete implies no longer pending — clear dirty/settled bits\n\t\t\t\t// so a preceding DIRTY from this dep doesn't block settlement.\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 — node was marked\n\t\t\t\t\t// dirty but no settlement came. Recompute so downstream\n\t\t\t\t\t// gets RESOLVED (value unchanged) or DATA (value 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\t_connectUpstream(): void {\n\t\tif (!this._hasDeps || this._connected) return;\n\t\tthis._connected = true;\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\tthis._status = \"settled\";\n\t\tconst subHints: SubscribeHints | undefined = this._isSingleDep\n\t\t\t? { singleDep: true }\n\t\t\t: undefined;\n\t\tthis._connecting = true;\n\t\ttry {\n\t\t\tfor (let i = 0; i < this._deps.length; i += 1) {\n\t\t\t\tconst dep = this._deps[i];\n\t\t\t\tthis._upstreamUnsubs.push(\n\t\t\t\t\tdep.subscribe((msgs) => this._handleDepMessages(i, msgs), subHints),\n\t\t\t\t);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._connecting = false;\n\t\t}\n\t\tif (this._fn) {\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\t_stopProducer(): void {\n\t\tif (!this._producerStarted) return;\n\t\tthis._producerStarted = false;\n\t\tconst producerCleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tproducerCleanup?.();\n\t}\n\n\t_startProducer(): void {\n\t\tif (this._deps.length !== 0 || !this._fn || this._producerStarted) return;\n\t\tthis._producerStarted = true;\n\t\tthis._runFn();\n\t}\n\n\t_disconnectUpstream(): void {\n\t\tif (!this._connected) return;\n\t\tfor (const unsub of this._upstreamUnsubs.splice(0)) {\n\t\t\tunsub();\n\t\t}\n\t\tthis._connected = false;\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\tthis._status = \"disconnected\";\n\t}\n}\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (GRAPHREFLY-SPEC §2).\n *\n * Typical shapes: `node([])` / `node([], opts)` for a manual source; `node(producerFn, opts)` for a\n * producer; `node(deps, computeFn, opts)` for 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>` - Configured node instance (lazy until subscribed).\n *\n * @remarks\n * **Protocol:** DIRTY / DATA / RESOLVED ordering, completion, and batch deferral follow `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\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 * @seeAlso [Specification](/spec)\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` discovers\n * deps at runtime via a tracking `get()` proxy. After each recompute, deps are\n * diffed: new deps are connected, removed deps are disconnected, and bitmasks\n * are rebuilt. Kept deps retain their subscriptions (no teardown/reconnect churn).\n *\n * This ports callbag-recharge's `dynamicDerived` pattern to GraphReFly's protocol.\n */\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { emitWithBatch } 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\tPAUSE,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport {\n\tnode as createNode,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeInspectorHook,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node.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/**\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 * - Bitmasks are rebuilt to match the new dep set\n *\n * The node participates fully in diamond resolution via the standard two-phase\n * DIRTY/RESOLVED protocol across all dynamically-tracked deps.\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 * // Deps change based on cond's value\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/** @internal — exported for {@link describeNode} `instanceof` check. */\nexport class DynamicNodeImpl<T = unknown> implements Node<T> {\n\tprivate readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\tprivate readonly _fn: DynamicNodeFn<T>;\n\tprivate readonly _equals: (a: unknown, b: unknown) => boolean;\n\tprivate readonly _resubscribable: boolean;\n\tprivate readonly _resetOnTeardown: boolean;\n\tprivate readonly _autoComplete: boolean;\n\tprivate readonly _onMessage: OnMessageHandler | undefined;\n\tprivate readonly _onResubscribe: (() => void) | undefined;\n\t/** @internal — read by {@link describeNode} for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\tprivate _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\n\t// Sink tracking\n\tprivate _sinkCount = 0;\n\tprivate _singleDepSinkCount = 0;\n\tprivate _singleDepSinks = new WeakSet<NodeSink>();\n\n\t// Actions object (for onMessage handler)\n\tprivate readonly _actions: NodeActions;\n\tprivate readonly _boundEmitToSinks: (messages: Messages) => void;\n\n\t// Mutable state\n\tprivate _cached: T | undefined;\n\tprivate _status: NodeStatus = \"disconnected\";\n\tprivate _terminal = false;\n\tprivate _connected = false;\n\tprivate _rewiring = false; // re-entrancy guard\n\n\t// Dynamic deps tracking\n\tprivate _deps: Node[] = [];\n\tprivate _depUnsubs: Array<() => void> = [];\n\tprivate _depIndexMap = new Map<Node, number>(); // node → index in _deps\n\tprivate _dirtyBits = new Set<number>();\n\tprivate _settledBits = new Set<number>();\n\tprivate _completeBits = new Set<number>();\n\n\t// Sinks\n\tprivate _sinks: NodeSink | Set<NodeSink> | null = null;\n\n\tconstructor(fn: DynamicNodeFn<T>, opts: DynamicNodeOptions) {\n\t\tthis._fn = fn;\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._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._onResubscribe = opts.onResubscribe;\n\t\tthis._guard = opts.guard;\n\t\tthis._inspectorHook = undefined;\n\n\t\t// Build companion meta nodes (same pattern as NodeImpl)\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = createNode({\n\t\t\t\tinitial: v,\n\t\t\t\tname: `${opts.name ?? \"dynamicNode\"}:meta:${k}`,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t\t});\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions object: created once, references `this` methods.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._emitAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tfor (const dep of self._deps) {\n\t\t\t\t\tdep.up?.(messages, { internal: true });\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\n\t\t// Bind commonly detached protocol methods\n\t\tthis._boundEmitToSinks = this._emitToSinks.bind(this);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/** @internal */\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\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\t/** Versioning not yet supported on DynamicNodeImpl. */\n\tget v(): undefined {\n\t\treturn undefined;\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\tget(): T | undefined {\n\t\treturn 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._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\tprivate _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\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 optimization: skip DIRTY to sinks when sole subscriber is single-dep\n\t\t// AND the batch contains a phase-2 message (DATA/RESOLVED). Standalone DIRTY\n\t\t// (without follow-up) must pass through so downstream is notified.\n\t\tif (this._canSkipDirty()) {\n\t\t\t// Inline check: does the batch contain DATA or RESOLVED?\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\t// Inline filter: remove DIRTY messages\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\temitWithBatch(this._boundEmitToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\temitWithBatch(this._boundEmitToSinks, sinkMessages);\n\t}\n\n\tprivate _canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\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\tif (this._terminal && this._resubscribable) {\n\t\t\tthis._terminal = false;\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\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\tif (!this._connected) {\n\t\t\tthis._connect();\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._disconnect();\n\t\t\t}\n\t\t};\n\t}\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._lastMutation = { actor, timestamp_ns: wallClockNs() };\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\tunsubscribe(): void {\n\t\tthis._disconnect();\n\t}\n\n\t// --- Private methods ---\n\n\tprivate _emitToSinks(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\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\tprivate _handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) this._cached = m[1] as T;\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\tthis._cached = undefined;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._status = \"settled\";\n\t\t\t} else if (t === DIRTY) {\n\t\t\t\tthis._status = \"dirty\";\n\t\t\t} else if (t === COMPLETE) {\n\t\t\t\tthis._status = \"completed\";\n\t\t\t\tthis._terminal = true;\n\t\t\t} else if (t === ERROR) {\n\t\t\t\tthis._status = \"errored\";\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._resetOnTeardown) this._cached = undefined;\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._disconnect();\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Propagate other meta-eligible signals (centralized in messages.ts).\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/** Propagate a signal to all companion meta nodes (best-effort). */\n\tprivate _propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\tmetaNode.down([[t]], { internal: true });\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\tprivate _emitAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tconst unchanged = this._equals(this._cached, value);\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._cached = value as T;\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n\n\tprivate _connect(): void {\n\t\tif (this._connected) return;\n\t\tthis._connected = true;\n\t\tthis._status = \"settled\";\n\t\tthis._dirtyBits.clear();\n\t\tthis._settledBits.clear();\n\t\tthis._completeBits.clear();\n\t\tthis._runFn();\n\t}\n\n\tprivate _disconnect(): void {\n\t\tif (!this._connected) return;\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._dirtyBits.clear();\n\t\tthis._settledBits.clear();\n\t\tthis._completeBits.clear();\n\t\tthis._connected = false;\n\t\tthis._status = \"disconnected\";\n\t}\n\n\tprivate _runFn(): void {\n\t\tif (this._terminal && !this._resubscribable) return;\n\t\tif (this._rewiring) return;\n\n\t\t// Track deps during fn execution\n\t\tconst trackedDeps: Node[] = [];\n\t\tconst trackedSet = new Set<Node>();\n\n\t\tconst get: DynGet = <V>(dep: Node<V>): V | undefined => {\n\t\t\tif (!trackedSet.has(dep)) {\n\t\t\t\ttrackedSet.add(dep);\n\t\t\t\ttrackedDeps.push(dep);\n\t\t\t}\n\t\t\treturn dep.get();\n\t\t};\n\n\t\ttry {\n\t\t\t// Collect dep values for inspector hook\n\t\t\tconst depValues: unknown[] = [];\n\t\t\tfor (const dep of this._deps) {\n\t\t\t\tdepValues.push(dep.get());\n\t\t\t}\n\t\t\tthis._inspectorHook?.({ kind: \"run\", depValues });\n\n\t\t\tconst result = this._fn(get);\n\t\t\tthis._rewire(trackedDeps);\n\t\t\tif (result === undefined) return;\n\t\t\tthis._emitAutoValue(result);\n\t\t} catch (err) {\n\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t}\n\t}\n\n\tprivate _rewire(newDeps: Node[]): void {\n\t\tthis._rewiring = true;\n\t\ttry {\n\t\t\tconst oldMap = this._depIndexMap;\n\t\t\tconst newMap = new Map<Node, number>();\n\t\t\tconst newUnsubs: Array<() => void> = [];\n\n\t\t\t// Reuse or create subscriptions\n\t\t\tfor (let i = 0; i < newDeps.length; i++) {\n\t\t\t\tconst dep = newDeps[i];\n\t\t\t\tnewMap.set(dep, i);\n\t\t\t\tconst oldIdx = oldMap.get(dep);\n\t\t\t\tif (oldIdx !== undefined) {\n\t\t\t\t\t// Kept dep — reuse subscription but update index\n\t\t\t\t\tnewUnsubs.push(this._depUnsubs[oldIdx]);\n\t\t\t\t\t// Mark old unsub as consumed\n\t\t\t\t\tthis._depUnsubs[oldIdx] = () => {};\n\t\t\t\t} else {\n\t\t\t\t\t// New dep — subscribe\n\t\t\t\t\tconst idx = i;\n\t\t\t\t\tconst unsub = dep.subscribe((msgs) => this._handleDepMessages(idx, msgs));\n\t\t\t\t\tnewUnsubs.push(unsub);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Disconnect removed deps\n\t\t\tfor (const [dep, oldIdx] of oldMap) {\n\t\t\t\tif (!newMap.has(dep)) {\n\t\t\t\t\tthis._depUnsubs[oldIdx]();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._deps = newDeps;\n\t\t\tthis._depUnsubs = newUnsubs;\n\t\t\tthis._depIndexMap = newMap;\n\t\t\tthis._dirtyBits.clear();\n\t\t\tthis._settledBits.clear();\n\t\t\t// Preserve complete bits for deps that are still present\n\t\t\tconst newCompleteBits = new Set<number>();\n\t\t\tfor (const oldIdx of this._completeBits) {\n\t\t\t\tconst dep = [...oldMap.entries()].find(([, idx]) => idx === oldIdx)?.[0];\n\t\t\t\tif (dep && newMap.has(dep)) {\n\t\t\t\t\tnewCompleteBits.add(newMap.get(dep)!);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._completeBits = newCompleteBits;\n\t\t} finally {\n\t\t\tthis._rewiring = false;\n\t\t}\n\t}\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\tif (this._rewiring) return; // suppress signals during rewire\n\n\t\tfor (const msg of messages) {\n\t\t\tthis._inspectorHook?.({ 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\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._dirtyBits.add(index);\n\t\t\t\tthis._settledBits.delete(index);\n\t\t\t\tif (this._dirtyBits.size === 1) {\n\t\t\t\t\t// First dirty — propagate\n\t\t\t\t\temitWithBatch(this._boundEmitToSinks, [[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._dirtyBits.has(index)) {\n\t\t\t\t\tthis._dirtyBits.add(index);\n\t\t\t\t\temitWithBatch(this._boundEmitToSinks, [[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tthis._settledBits.add(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._dirtyBits.clear();\n\t\t\t\t\tthis._settledBits.clear();\n\t\t\t\t\tthis._runFn();\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._completeBits.add(index);\n\t\t\t\tthis._dirtyBits.delete(index);\n\t\t\t\tthis._settledBits.delete(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._dirtyBits.clear();\n\t\t\t\t\tthis._settledBits.clear();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tthis._autoComplete &&\n\t\t\t\t\tthis._completeBits.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\tprivate _allDirtySettled(): boolean {\n\t\tif (this._dirtyBits.size === 0) return false;\n\t\tfor (const idx of this._dirtyBits) {\n\t\t\tif (!this._settledBits.has(idx)) return false;\n\t\t}\n\t\treturn true;\n\t}\n}\n","import { DynamicNodeImpl } from \"./dynamic-node.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { 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/** Node versioning info (GRAPHREFLY-SPEC §7). Present only when versioning is enabled. */\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\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 */\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 */\nexport function describeNode(node: Node): DescribeNodeOutput {\n\tconst meta: Record<string, unknown> = { ...metaSnapshot(node) };\n\n\t// Guard-derived access hint (NodeImpl or DynamicNodeImpl)\n\tconst guard =\n\t\t(node instanceof NodeImpl && node._guard) ||\n\t\t(node instanceof DynamicNodeImpl && node._guard) ||\n\t\tundefined;\n\tif (guard != null && meta.access === undefined) {\n\t\tmeta.access = accessHintForGuard(guard);\n\t}\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 = {\n\t\ttype,\n\t\tstatus: node.status,\n\t\tdeps,\n\t\tmeta,\n\t};\n\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\ttry {\n\t\tout.value = node.get();\n\t} catch {\n\t\t/* omit value */\n\t}\n\n\t// Versioning (GRAPHREFLY-SPEC §7)\n\tif (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\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.\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(deps: readonly Node[], fn: NodeFn<unknown>): Node<unknown> {\n\treturn node(deps, fn, { describeKind: \"effect\" });\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","import type { Actor } from \"../core/actor.js\";\nimport { isBatching } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { GuardDenied } from \"../core/guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport { type DescribeNodeOutput, describeNode } from \"../core/meta.js\";\nimport {\n\ttype Node,\n\tNodeImpl,\n\ttype NodeInspectorHookEvent,\n\ttype NodeSink,\n\ttype NodeTransportOptions,\n} from \"../core/node.js\";\nimport { state as stateNode } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\n\n/** The separator used for qualified paths in {@link Graph.resolve} et al. */\nconst PATH_SEP = \"::\";\n\n/**\n * Reserved segment for meta companion paths: `nodeName::__meta__::metaKey` (GRAPHREFLY-SPEC §3.6).\n * Forbidden as a local node or mount name.\n */\nexport const GRAPH_META_SEGMENT = \"__meta__\";\n\n/** Options for {@link Graph} (reserved for future hooks). */\nexport type GraphOptions = Record<string, unknown>;\n\n/** Filter for {@link Graph.describe} — object-style partial match or predicate. */\nexport type DescribeFilter =\n\t| Partial<Pick<DescribeNodeOutput, \"type\" | \"status\">>\n\t| {\n\t\t\ttype?: DescribeNodeOutput[\"type\"];\n\t\t\tstatus?: DescribeNodeOutput[\"status\"];\n\t\t\t/** Keep nodes whose `deps` includes this qualified path. */\n\t\t\tdepsIncludes?: string;\n\t\t\t/** Snake-case alias for `depsIncludes` (Python parity). */\n\t\t\tdeps_includes?: string;\n\t\t\t/** Keep nodes whose `meta` contains this key. */\n\t\t\tmetaHas?: string;\n\t\t\t/** Snake-case alias for `metaHas` (Python parity). */\n\t\t\tmeta_has?: string;\n\t }\n\t| ((node: DescribeNodeOutput) => boolean)\n\t| ((nodePath: string, node: DescribeNodeOutput) => boolean);\n\n/** Options for {@link Graph.signal} and {@link Graph.set} (actor context, internal lifecycle). */\nexport type GraphActorOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips node guards (graph lifecycle TEARDOWN, unmount teardown, etc.).\n\t */\n\tinternal?: boolean;\n};\n\n/** JSON snapshot from {@link Graph.describe} (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type GraphDescribeOutput = {\n\tname: string;\n\tnodes: Record<string, DescribeNodeOutput>;\n\tedges: ReadonlyArray<{ from: string; to: string }>;\n\tsubgraphs: string[];\n};\n\n/**\n * Persisted graph snapshot: {@link GraphDescribeOutput} plus optional format version\n * ({@link Graph.snapshot}, {@link Graph.restore}, {@link Graph.fromSnapshot}, {@link Graph.toJSON},\n * {@link Graph.toJSONString} — §3.8).\n */\nexport type GraphPersistSnapshot = GraphDescribeOutput & {\n\tversion?: number;\n};\n\nexport type GraphFactoryContext = {\n\tpath: string;\n\ttype: DescribeNodeOutput[\"type\"];\n\tvalue: unknown;\n\tmeta: Record<string, unknown>;\n\tdeps: readonly string[];\n\tresolvedDeps: readonly Node[];\n};\n\nexport type GraphNodeFactory = (name: string, context: GraphFactoryContext) => Node;\n\nexport type AutoCheckpointAdapter = {\n\tsave(data: unknown): void;\n};\n\nexport type GraphCheckpointRecord =\n\t| { mode: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { mode: \"diff\"; diff: GraphDiffResult; snapshot: GraphPersistSnapshot; seq: number };\n\nexport type GraphAutoCheckpointOptions = {\n\tdebounceMs?: number;\n\tcompactEvery?: number;\n\tfilter?: (name: string, described: DescribeNodeOutput) => boolean;\n\tonError?: (error: unknown) => void;\n};\n\nexport type GraphAutoCheckpointHandle = {\n\tdispose(): void;\n};\n\n/** Direction options for diagram export helpers. */\nexport type GraphDiagramDirection = \"TD\" | \"LR\" | \"BT\" | \"RL\";\n\n/** Options for {@link Graph.toMermaid} / {@link Graph.toD2}. */\nexport type GraphDiagramOptions = {\n\t/**\n\t * Diagram flow direction.\n\t * - `TD`: top-down\n\t * - `LR`: left-right (default)\n\t * - `BT`: bottom-top\n\t * - `RL`: right-left\n\t */\n\tdirection?: GraphDiagramDirection;\n};\n\n/** Snapshot format version (§3.8). */\nconst SNAPSHOT_VERSION = 1;\n\n/**\n * Validate the snapshot envelope: version, required keys, types. Aligned with\n * Python `_parse_snapshot_envelope`. Throws on invalid data.\n */\nfunction parseSnapshotEnvelope(data: GraphPersistSnapshot): void {\n\tif (data.version !== SNAPSHOT_VERSION) {\n\t\tthrow new Error(\n\t\t\t`unsupported snapshot version ${String(data.version)} (expected ${SNAPSHOT_VERSION})`,\n\t\t);\n\t}\n\tfor (const key of [\"name\", \"nodes\", \"edges\", \"subgraphs\"] as const) {\n\t\tif (!(key in data)) {\n\t\t\tthrow new Error(`snapshot missing required key \"${key}\"`);\n\t\t}\n\t}\n\tif (typeof data.name !== \"string\") {\n\t\tthrow new TypeError(`snapshot 'name' must be a string`);\n\t}\n\tif (typeof data.nodes !== \"object\" || data.nodes === null || Array.isArray(data.nodes)) {\n\t\tthrow new TypeError(`snapshot 'nodes' must be an object`);\n\t}\n\tif (!Array.isArray(data.edges)) {\n\t\tthrow new TypeError(`snapshot 'edges' must be an array`);\n\t}\n\tif (!Array.isArray(data.subgraphs)) {\n\t\tthrow new TypeError(`snapshot 'subgraphs' must be an array`);\n\t}\n}\n\n/** Recursively sort object keys for deterministic JSON (git-diffable). */\nfunction sortJsonValue(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sortJsonValue);\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\tconst out: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tout[k] = sortJsonValue(obj[k]);\n\t}\n\treturn out;\n}\n\nfunction stableJsonStringify(value: unknown): string {\n\treturn `${JSON.stringify(sortJsonValue(value))}\\n`;\n}\n\nfunction escapeMermaidLabel(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction escapeD2Label(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction d2DirectionFromGraphDirection(direction: GraphDiagramDirection): string {\n\tif (direction === \"TD\") return \"down\";\n\tif (direction === \"BT\") return \"up\";\n\tif (direction === \"RL\") return \"left\";\n\treturn \"right\";\n}\n\n/** Collect deduplicated (from, to) arrows from deps + edges. */\nfunction collectDiagramArrows(described: GraphDescribeOutput): [string, string][] {\n\tconst seen = new Set<string>();\n\tconst arrows: [string, string][] = [];\n\tfunction add(from: string, to: string): void {\n\t\tconst key = `${from}\\0${to}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tarrows.push([from, to]);\n\t}\n\tfor (const [path, info] of Object.entries(described.nodes)) {\n\t\tconst deps: string[] | undefined = (info as Record<string, unknown>).deps as\n\t\t\t| string[]\n\t\t\t| undefined;\n\t\tif (deps) {\n\t\t\tfor (const dep of deps) add(dep, path);\n\t\t}\n\t}\n\tfor (const edge of described.edges) add(edge.from, edge.to);\n\treturn arrows;\n}\n\nfunction normalizeDiagramDirection(direction: unknown): GraphDiagramDirection {\n\tif (direction === undefined) return \"LR\";\n\tif (direction === \"TD\" || direction === \"LR\" || direction === \"BT\" || direction === \"RL\") {\n\t\treturn direction;\n\t}\n\tthrow new Error(\n\t\t`invalid diagram direction ${String(direction)}; expected one of: TD, LR, BT, RL`,\n\t);\n}\n\nfunction escapeRegexLiteral(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet re = \"^\";\n\tfor (let i = 0; i < pattern.length; i += 1) {\n\t\tconst ch = pattern[i]!;\n\t\tif (ch === \"*\") {\n\t\t\tre += \".*\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"?\") {\n\t\t\tre += \".\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tconst end = pattern.indexOf(\"]\", i + 1);\n\t\t\tif (end <= i + 1) {\n\t\t\t\tre += \"\\\\[\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet cls = pattern.slice(i + 1, end);\n\t\t\tif (cls.startsWith(\"!\")) cls = `^${cls.slice(1)}`;\n\t\t\tcls = cls.replace(/\\\\/g, \"\\\\\\\\\");\n\t\t\tre += `[${cls}]`;\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tre += escapeRegexLiteral(ch);\n\t}\n\tre += \"$\";\n\treturn new RegExp(re);\n}\n\n/** Fixed-capacity ring buffer — O(1) push and eviction. */\nclass RingBuffer<T> {\n\tprivate buf: (T | undefined)[];\n\tprivate head = 0;\n\tprivate _size = 0;\n\tconstructor(private capacity: number) {\n\t\tthis.buf = new Array(capacity);\n\t}\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\tpush(item: T): void {\n\t\tconst idx = (this.head + this._size) % this.capacity;\n\t\tthis.buf[idx] = item;\n\t\tif (this._size < this.capacity) this._size++;\n\t\telse this.head = (this.head + 1) % this.capacity;\n\t}\n\ttoArray(): T[] {\n\t\tconst result: T[] = [];\n\t\tfor (let i = 0; i < this._size; i++) result.push(this.buf[(this.head + i) % this.capacity]!);\n\t\treturn result;\n\t}\n}\n\nconst SPY_ANSI_THEME: Required<GraphSpyTheme> = {\n\tdata: \"\\u001b[32m\",\n\tdirty: \"\\u001b[33m\",\n\tresolved: \"\\u001b[36m\",\n\tcomplete: \"\\u001b[34m\",\n\terror: \"\\u001b[31m\",\n\tderived: \"\\u001b[35m\",\n\tpath: \"\\u001b[90m\",\n\treset: \"\\u001b[0m\",\n};\n\nconst SPY_NO_COLOR_THEME: Required<GraphSpyTheme> = {\n\tdata: \"\",\n\tdirty: \"\",\n\tresolved: \"\",\n\tcomplete: \"\",\n\terror: \"\",\n\tderived: \"\",\n\tpath: \"\",\n\treset: \"\",\n};\n\nfunction describeData(value: unknown): string {\n\tif (typeof value === \"string\") return JSON.stringify(value);\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || value == null)\n\t\treturn String(value);\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction resolveSpyTheme(theme: GraphSpyOptions[\"theme\"]): Required<GraphSpyTheme> {\n\tif (theme === \"none\") return SPY_NO_COLOR_THEME;\n\tif (theme === \"ansi\" || theme == null) return SPY_ANSI_THEME;\n\treturn {\n\t\tdata: theme.data ?? \"\",\n\t\tdirty: theme.dirty ?? \"\",\n\t\tresolved: theme.resolved ?? \"\",\n\t\tcomplete: theme.complete ?? \"\",\n\t\terror: theme.error ?? \"\",\n\t\tderived: theme.derived ?? \"\",\n\t\tpath: theme.path ?? \"\",\n\t\treset: theme.reset ?? \"\",\n\t};\n}\n\n/** {@link Graph.observe} on a single node or meta path — sink receives plain message batches. */\nexport type GraphObserveOne = {\n\tsubscribe(sink: NodeSink): () => void;\n\t/** Send messages upstream toward the observed node's sources (e.g. PAUSE/RESUME). */\n\tup(messages: Messages): void;\n};\n\n/**\n * {@link Graph.observe} on the whole graph — sink receives each batch with the qualified source path.\n * Subscription order follows code-point sort on paths (mounts-first walk, then sorted locals/meta).\n */\nexport type GraphObserveAll = {\n\tsubscribe(sink: (nodePath: string, messages: Messages) => void): () => void;\n\t/** Send messages upstream toward a specific observed node's sources (e.g. PAUSE/RESUME). */\n\tup(path: string, messages: Messages): void;\n};\n\n/** Options for structured observation modes on {@link Graph.observe}. */\nexport type ObserveOptions = {\n\tactor?: Actor;\n\t/** Return an {@link ObserveResult} accumulator instead of a raw stream. */\n\tstructured?: boolean;\n\t/** Include causal trace info (which dep triggered each recomputation). */\n\tcausal?: boolean;\n\t/** Include timestamps and batch context on each event. */\n\ttimeline?: boolean;\n\t/** Include per-evaluation dep snapshots for compute/derived nodes. */\n\tderived?: boolean;\n};\n\n/** Accumulated observation result (structured mode). */\nexport type ObserveResult<T = unknown> = {\n\t/** Latest DATA value by observed path. */\n\treadonly values: Record<string, T>;\n\t/** Number of DIRTY messages received. */\n\treadonly dirtyCount: number;\n\t/** Number of RESOLVED messages received. */\n\treadonly resolvedCount: number;\n\t/** All events in order. */\n\treadonly events: ObserveEvent[];\n\t/** True if COMPLETE received without prior ERROR. */\n\treadonly completedCleanly: boolean;\n\t/** True if ERROR received. */\n\treadonly errored: boolean;\n\t/** Stop observing. */\n\tdispose(): void;\n};\n\n/** A single event in the structured observation log. */\nexport type ObserveEvent = {\n\ttype: \"data\" | \"dirty\" | \"resolved\" | \"complete\" | \"error\" | \"derived\";\n\tpath?: string;\n\tdata?: unknown;\n\ttimestamp_ns?: number;\n\tin_batch?: boolean;\n\ttrigger_dep_index?: number;\n\ttrigger_dep_name?: string;\n\t/**\n\t * V0 version of the triggering dep at observation time (§6.0b).\n\t * This is the dep's post-emission version (after its own `advanceVersion`),\n\t * not the pre-emission version that caused this node's recomputation.\n\t */\n\ttrigger_version?: { id: string; version: number };\n\tdep_values?: unknown[];\n};\n\n/** Built-in color presets for {@link Graph.spy}. */\nexport type GraphSpyThemeName = \"none\" | \"ansi\";\n\n/** ANSI/style overrides for {@link Graph.spy} event rendering. */\nexport type GraphSpyTheme = Partial<Record<ObserveEvent[\"type\"] | \"path\" | \"reset\", string>>;\n\n/** Options for {@link Graph.spy}. */\nexport type GraphSpyOptions = ObserveOptions & {\n\t/** Observe one path; omit for graph-wide mode. */\n\tpath?: string;\n\t/** Keep only these event types in spy output. */\n\tincludeTypes?: ObserveEvent[\"type\"][];\n\t/** Exclude these event types from spy output. */\n\texcludeTypes?: ObserveEvent[\"type\"][];\n\t/** Built-in color preset (`ansi` default) or explicit color tokens. */\n\ttheme?: GraphSpyThemeName | GraphSpyTheme;\n\t/** One-line `pretty` output (default) or JSON-per-event. */\n\tformat?: \"pretty\" | \"json\";\n\t/** Optional sink for rendered lines (`console.log` by default). */\n\tlogger?: (line: string, event: ObserveEvent) => void;\n};\n\n/** Handle returned by {@link Graph.spy}. */\nexport type GraphSpyHandle = {\n\treadonly result: ObserveResult;\n\tdispose(): void;\n};\n\n/** Options for {@link Graph.dumpGraph}. */\nexport type GraphDumpOptions = {\n\tactor?: Actor;\n\tfilter?: DescribeFilter;\n\tformat?: \"pretty\" | \"json\";\n\tindent?: number;\n\tincludeEdges?: boolean;\n\tincludeSubgraphs?: boolean;\n\tlogger?: (text: string) => void;\n};\n\nfunction assertLocalName(name: string, graphName: string, label: string): void {\n\tif (name === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": ${label} name must be non-empty`);\n\t}\n}\n\nfunction assertNoPathSep(name: string, graphName: string, label: string): void {\n\tif (name.includes(PATH_SEP)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} \"${name}\" must not contain '${PATH_SEP}' (path separator)`,\n\t\t);\n\t}\n}\n\nfunction assertNotReservedMetaSegment(name: string, graphName: string, label: string): void {\n\tif (name === GRAPH_META_SEGMENT) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} name \"${GRAPH_META_SEGMENT}\" is reserved for meta companion paths`,\n\t\t);\n\t}\n}\n\n/** `connect` / `disconnect` endpoints must be registered graph nodes, not meta paths (graphrefly-py parity). */\nfunction assertConnectPathNotMeta(path: string, graphName: string): void {\n\tif (path.split(PATH_SEP).includes(GRAPH_META_SEGMENT)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": connect/disconnect endpoints must be registered graph nodes, not meta paths (got \"${path}\")`,\n\t\t);\n\t}\n}\n\nfunction splitPath(path: string, graphName: string): string[] {\n\tif (path === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": resolve path must be non-empty`);\n\t}\n\tconst segments = path.split(PATH_SEP);\n\tfor (const s of segments) {\n\t\tif (s === \"\") {\n\t\t\tthrow new Error(`Graph \"${graphName}\": resolve path has empty segment`);\n\t\t}\n\t}\n\treturn segments;\n}\n\n/** Canonical string key for an edge pair (deterministic, splittable). */\nfunction edgeKey(from: string, to: string): string {\n\treturn `${from}\\t${to}`;\n}\n\nfunction parseEdgeKey(key: string): [string, string] {\n\tconst i = key.indexOf(\"\\t\");\n\treturn [key.slice(0, i), key.slice(i + 1)];\n}\n\n/**\n * Lifecycle-destructive message types that meta companion nodes ignore\n * during graph-wide signal propagation (spec §2.3 Companion lifecycle).\n * TEARDOWN: parent already cascades explicitly.\n * INVALIDATE/COMPLETE/ERROR: meta stores outlive these lifecycle events.\n * To target a meta node directly, call `meta.down(...)` on it.\n */\nconst META_FILTERED_TYPES = new Set([TEARDOWN, INVALIDATE, COMPLETE, ERROR]);\n\n/** Strip lifecycle-destructive messages; returns empty array when nothing remains. */\nfunction filterMetaMessages(messages: Messages): Messages {\n\tconst kept = messages.filter((m) => !META_FILTERED_TYPES.has(m[0]));\n\treturn kept as unknown as Messages;\n}\n\n/** TEARDOWN every node in a mounted graph tree (depth-first into mounts). */\nfunction teardownMountedGraph(root: Graph): void {\n\tfor (const child of root._mounts.values()) {\n\t\tteardownMountedGraph(child);\n\t}\n\tfor (const n of root._nodes.values()) {\n\t\tn.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n}\n\n/**\n * Named container for nodes and explicit edges (GRAPHREFLY-SPEC §3.1–§3.7).\n *\n * Qualified paths use `::` as the segment separator (for example `parent::child::node`).\n *\n * Edges are pure wires: `connect` only validates wiring — the target must already list the source in\n * its dependency array; no transforms run on the edge.\n *\n * @example\n * ```ts\n * import { Graph, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * g.add(\"counter\", state(0));\n * ```\n *\n * @category graph\n */\nexport class Graph {\n\tprivate static readonly _factories: Array<{\n\t\tpattern: string;\n\t\tre: RegExp;\n\t\tfactory: GraphNodeFactory;\n\t}> = [];\n\n\treadonly name: string;\n\treadonly opts: Readonly<GraphOptions>;\n\t/** @internal — exposed for {@link teardownMountedGraph} and cross-graph helpers. */\n\treadonly _nodes = new Map<string, Node>();\n\tprivate readonly _edges = new Set<string>();\n\t/** @internal — exposed for {@link teardownMountedGraph}. */\n\treadonly _mounts = new Map<string, Graph>();\n\tprivate readonly _autoCheckpointDisposers = new Set<() => void>();\n\tprivate _defaultVersioningLevel: VersioningLevel | undefined;\n\n\tstatic registerFactory(pattern: string, factory: GraphNodeFactory): void {\n\t\tif (!pattern) {\n\t\t\tthrow new Error(\"Graph.registerFactory requires a non-empty pattern\");\n\t\t}\n\t\tGraph.unregisterFactory(pattern);\n\t\tGraph._factories.push({ pattern, re: globToRegex(pattern), factory });\n\t}\n\n\tstatic unregisterFactory(pattern: string): void {\n\t\tconst i = Graph._factories.findIndex((entry) => entry.pattern === pattern);\n\t\tif (i >= 0) Graph._factories.splice(i, 1);\n\t}\n\n\t/**\n\t * @param name - Non-empty graph id (must not contain `::`).\n\t * @param opts - Reserved for future hooks; currently unused.\n\t */\n\tconstructor(name: string, opts?: GraphOptions) {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(\"Graph name must be non-empty\");\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\tthrow new Error(`Graph name must not contain '${PATH_SEP}' (got \"${name}\")`);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.opts = opts ?? {};\n\t}\n\n\tprivate static _factoryForPath(path: string): GraphNodeFactory | undefined {\n\t\tfor (let i = Graph._factories.length - 1; i >= 0; i -= 1) {\n\t\t\tconst entry = Graph._factories[i]!;\n\t\t\tif (entry.re.test(path)) return entry.factory;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate static _ownerForPath(root: Graph, path: string): [Graph, string] {\n\t\tconst segments = path.split(PATH_SEP);\n\t\tconst local = segments.pop();\n\t\tif (local == null || local.length === 0) {\n\t\t\tthrow new Error(`invalid snapshot path \"${path}\"`);\n\t\t}\n\t\tlet owner = root;\n\t\tfor (const seg of segments) {\n\t\t\tconst next = owner._mounts.get(seg);\n\t\t\tif (!next) throw new Error(`unknown mount \"${seg}\" in path \"${path}\"`);\n\t\t\towner = next;\n\t\t}\n\t\treturn [owner, local];\n\t}\n\n\t/**\n\t * Graphs reachable from this instance via nested {@link Graph.mount} (includes `this`).\n\t */\n\tprivate _graphsReachableViaMounts(seen = new Set<Graph>()): Set<Graph> {\n\t\tif (seen.has(this)) return seen;\n\t\tseen.add(this);\n\t\tfor (const child of this._mounts.values()) {\n\t\t\tchild._graphsReachableViaMounts(seen);\n\t\t}\n\t\treturn seen;\n\t}\n\n\t/**\n\t * Resolve an endpoint: returns `[owningGraph, localName, node]`.\n\t * Accepts both local names and `::` qualified paths.\n\t */\n\tprivate _resolveEndpoint(path: string): [Graph, string, Node] {\n\t\tif (!path.includes(PATH_SEP)) {\n\t\t\tconst n = this._nodes.get(path);\n\t\t\tif (!n) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${path}\"`);\n\t\t\t}\n\t\t\treturn [this, path, n];\n\t\t}\n\t\tconst segments = splitPath(path, this.name);\n\t\treturn this._resolveEndpointFromSegments(segments, path);\n\t}\n\n\tprivate _resolveEndpointFromSegments(\n\t\tsegments: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return [this, head, n];\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${head}\" (from path \"${fullPath}\")`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaEndpointKeys(localN, head, rest, fullPath);\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\t\treturn child._resolveEndpointFromSegments(rest, fullPath);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Node registry\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Registers a node under a local name. Fails if the name is already used,\n\t * reserved by a mount, or the same node instance is already registered.\n\t *\n\t * @param name - Local key (no `::`).\n\t * @param node - Node instance to own.\n\t */\n\tadd(name: string, node: Node): void {\n\t\tassertLocalName(name, this.name, \"add\");\n\t\tassertNoPathSep(name, this.name, \"add\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"node\");\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": name \"${name}\" is already a mount point`);\n\t\t}\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node \"${name}\" already exists`);\n\t\t}\n\t\tfor (const [existingName, existing] of this._nodes) {\n\t\t\tif (existing === node) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": node instance already registered as \"${existingName}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._nodes.set(name, node);\n\t\tif (node instanceof NodeImpl) {\n\t\t\tnode._assignRegistryName(name);\n\t\t\tif (this._defaultVersioningLevel != null) {\n\t\t\t\tnode._applyVersioning(this._defaultVersioningLevel);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Set a default versioning level for all nodes added to this graph (roadmap §6.0).\n\t *\n\t * Nodes already registered are retroactively upgraded. Nodes added later via\n\t * {@link add} will inherit this level unless they already have versioning.\n\t *\n\t * **Scope:** Does not propagate to mounted subgraphs. Call `setVersioning`\n\t * on each child graph separately if needed.\n\t *\n\t * @param level - `0` for V0, `1` for V1, or `undefined` to clear.\n\t */\n\tsetVersioning(level: VersioningLevel | undefined): void {\n\t\tthis._defaultVersioningLevel = level;\n\t\tif (level == null) return;\n\t\tfor (const n of this._nodes.values()) {\n\t\t\tif (n instanceof NodeImpl) {\n\t\t\t\tn._applyVersioning(level);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters a node or unmounts a subgraph, drops incident edges, and sends\n\t * `[[TEARDOWN]]` to the removed node or recursively through the mounted subtree (§3.2).\n\t *\n\t * @param name - Local mount or node name.\n\t */\n\tremove(name: string): void {\n\t\tassertLocalName(name, this.name, \"remove\");\n\t\tassertNoPathSep(name, this.name, \"remove\");\n\n\t\t// Case 1: unmount a subgraph\n\t\tconst child = this._mounts.get(name);\n\t\tif (child) {\n\t\t\tthis._mounts.delete(name);\n\t\t\t// Drop edges touching this mount name or qualified paths under it.\n\t\t\tconst prefix = `${name}${PATH_SEP}`;\n\t\t\tfor (const key of [...this._edges]) {\n\t\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\t\tif (from === name || to === name || from.startsWith(prefix) || to.startsWith(prefix)) {\n\t\t\t\t\tthis._edges.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tteardownMountedGraph(child);\n\t\t\treturn;\n\t\t}\n\n\t\t// Case 2: remove a local node\n\t\tconst node = this._nodes.get(name);\n\t\tif (!node) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node or mount \"${name}\"`);\n\t\t}\n\t\tthis._nodes.delete(name);\n\t\tfor (const key of [...this._edges]) {\n\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\tif (from === name || to === name) this._edges.delete(key);\n\t\t}\n\t\tnode.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n\n\t/**\n\t * Returns a node by local name or `::` qualified path.\n\t * Local names are looked up directly; paths with `::` delegate to {@link resolve}.\n\t *\n\t * @param name - Local name or qualified path.\n\t */\n\tnode(name: string): Node {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node name must be non-empty`);\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\treturn this.resolve(name);\n\t\t}\n\t\tconst n = this._nodes.get(name);\n\t\tif (!n) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${name}\"`);\n\t\t}\n\t\treturn n;\n\t}\n\n\t/**\n\t * Reads `graph.node(name).get()` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @returns Cached value or `undefined`.\n\t */\n\tget(name: string): unknown {\n\t\treturn this.node(name).get();\n\t}\n\n\t/**\n\t * Shorthand for `graph.node(name).down([[DATA, value]], { actor })` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @param value - Next `DATA` payload.\n\t * @param options - Optional `actor` and `internal` guard bypass.\n\t */\n\tset(name: string, value: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[DATA, value]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Edges\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Record a wire from `fromPath` → `toPath` (§3.3). Accepts local names or\n\t * `::` qualified paths. The target must be a {@link NodeImpl} whose `_deps`\n\t * includes the source node (same reference). Idempotent.\n\t *\n\t * Same-owner edges are stored on the owning child graph; cross-subgraph edges\n\t * are stored on this (parent) graph's registry.\n\t *\n\t * @param fromPath - Source endpoint (local or qualified).\n\t * @param toPath - Target endpoint whose deps already include the source node.\n\t */\n\tconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": connect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal, fromNode] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal, toNode] = this._resolveEndpoint(toPath);\n\n\t\tif (fromNode === toNode) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot connect a node to itself`);\n\t\t}\n\n\t\tif (!(toNode instanceof NodeImpl)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) requires the target to be a graphrefly NodeImpl so deps can be validated`,\n\t\t\t);\n\t\t}\n\t\tif (!toNode._deps.includes(fromNode)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) — target must include source in its constructor deps (same node reference)`,\n\t\t\t);\n\t\t}\n\n\t\tif (fromGraph === toGraph) {\n\t\t\t// Same-owner: store on the child graph\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tfromGraph._edges.add(key);\n\t\t} else {\n\t\t\t// Cross-subgraph: store on this (parent) graph\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tthis._edges.add(key);\n\t\t}\n\t}\n\n\t/**\n\t * Remove a registered edge (§3.3). Accepts local names or `::` qualified paths.\n\t *\n\t * **Registry-only (§C resolved):** This drops the edge from the graph's edge\n\t * registry only. It does **not** mutate the target node's constructor-time\n\t * dependency list, bitmasks, or upstream subscriptions. Message flow follows\n\t * constructor-time deps, not the edge registry. For runtime dep rewiring, use\n\t * {@link dynamicNode}.\n\t *\n\t * @param fromPath - Registered edge tail.\n\t * @param toPath - Registered edge head.\n\t */\n\tdisconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": disconnect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal] = this._resolveEndpoint(toPath);\n\n\t\tif (fromGraph === toGraph) {\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tif (!fromGraph._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tif (!this._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns registered `[from, to]` edge pairs (read-only snapshot).\n\t *\n\t * @returns Edge pairs recorded on this graph instance’s local `_edges` set.\n\t */\n\tedges(): ReadonlyArray<[string, string]> {\n\t\tconst result: [string, string][] = [];\n\t\tfor (const key of this._edges) {\n\t\t\tresult.push(parseEdgeKey(key));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Composition\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Embed a child graph at a local mount name (§3.4). Child nodes are reachable via\n\t * {@link Graph.resolve} using `::` delimited paths (§3.5). Lifecycle\n\t * {@link Graph.signal} visits mounted subgraphs recursively.\n\t *\n\t * Rejects: same name as existing node or mount, self-mount, mount cycles,\n\t * and the same child graph instance mounted twice on one parent.\n\t *\n\t * @param name - Local mount point.\n\t * @param child - Nested `Graph` instance.\n\t */\n\tmount(name: string, child: Graph): void {\n\t\tassertLocalName(name, this.name, \"mount\");\n\t\tassertNoPathSep(name, this.name, \"mount\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"mount\");\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": cannot mount at \"${name}\" — node with that name exists`,\n\t\t\t);\n\t\t}\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount \"${name}\" already exists`);\n\t\t}\n\t\tif (child === this) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot mount a graph into itself`);\n\t\t}\n\t\t// Reject same child instance mounted twice on this parent.\n\t\tfor (const existing of this._mounts.values()) {\n\t\t\tif (existing === child) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": this child graph is already mounted on this graph`);\n\t\t\t}\n\t\t}\n\t\tif (child._graphsReachableViaMounts().has(this)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount(\"${name}\", …) would create a mount cycle`);\n\t\t}\n\t\tthis._mounts.set(name, child);\n\t}\n\n\t/**\n\t * Look up a node by qualified path (§3.5). Segments are separated by `::`.\n\t *\n\t * If the first segment equals this graph's {@link Graph.name}, it is stripped\n\t * (so `root.resolve(\"app::a\")` works when `root.name === \"app\"`).\n\t *\n\t * @param path - Qualified `::` path or local name.\n\t * @returns The resolved `Node`.\n\t */\n\tresolve(path: string): Node {\n\t\tlet segments = splitPath(path, this.name);\n\t\tif (segments[0] === this.name) {\n\t\t\tsegments = segments.slice(1);\n\t\t\tif (segments.length === 0) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": resolve path ends at graph name only`);\n\t\t\t}\n\t\t}\n\t\treturn this._resolveFromSegments(segments);\n\t}\n\n\tprivate _resolveFromSegments(segments: readonly string[]): Node {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return n;\n\t\t\tif (this._mounts.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": path ends at subgraph \"${head}\" — not a node (GRAPHREFLY-SPEC §3.5)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown name \"${head}\"`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaChainFromNode(localN, rest, segments.join(PATH_SEP));\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\n\t\treturn child.resolve(rest.join(PATH_SEP));\n\t}\n\n\t/**\n\t * Resolve `::__meta__::key` segments from a registered primary node (possibly chained).\n\t */\n\tprivate _resolveMetaChainFromNode(n: Node, parts: readonly string[], fullPath: string): Node {\n\t\tlet current = n;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = p[i + 1] as string;\n\t\t\tconst next = current.meta[key];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown meta \"${key}\" in path \"${fullPath}\"`);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate _resolveMetaEndpointKeys(\n\t\tbaseNode: Node,\n\t\tbaseLocalKey: string,\n\t\tparts: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tlet current = baseNode;\n\t\tlet localKey = baseLocalKey;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst metaKey = p[i + 1] as string;\n\t\t\tconst next = current.meta[metaKey];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": unknown meta \"${metaKey}\" on node (in \"${fullPath}\")`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlocalKey = `${localKey}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${metaKey}`;\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn [this, localKey, current];\n\t}\n\n\t/**\n\t * Deliver a message batch to every registered node in this graph and, recursively,\n\t * in mounted child graphs (§3.7). Recurses into mounts first, then delivers to\n\t * local nodes (sorted by name). Each {@link Node} receives at most one delivery\n\t * per call (deduped by reference).\n\t *\n\t * Companion `meta` nodes receive the same batch for control-plane types (e.g.\n\t * PAUSE) that the primary does not forward. **TEARDOWN-only** batches skip the\n\t * extra meta pass — the primary’s `down()` already cascades TEARDOWN to meta.\n\t *\n\t * @param messages - Batch to deliver to every registered node (and mounts, recursively).\n\t * @param options - Optional `actor` / `internal` for transport.\n\t */\n\tsignal(messages: Messages, options?: GraphActorOptions): void {\n\t\tthis._signalDeliver(messages, options ?? {}, new Set());\n\t}\n\n\tprivate _signalDeliver(messages: Messages, opts: GraphActorOptions, vis: Set<Node>): void {\n\t\tfor (const sub of this._mounts.values()) {\n\t\t\tsub._signalDeliver(messages, opts, vis);\n\t\t}\n\t\tconst internal = opts.internal === true;\n\t\tconst downOpts: NodeTransportOptions = internal\n\t\t\t? { internal: true }\n\t\t\t: { actor: opts.actor, delivery: \"signal\" };\n\t\tconst metaMessages = filterMetaMessages(messages);\n\t\tfor (const localName of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(localName)!;\n\t\t\tif (vis.has(n)) continue;\n\t\t\tvis.add(n);\n\t\t\tn.down(messages, downOpts);\n\t\t\tif (metaMessages.length === 0) continue;\n\t\t\tthis._signalMetaSubtree(n, metaMessages, vis, downOpts);\n\t\t}\n\t}\n\n\tprivate _signalMetaSubtree(\n\t\troot: Node,\n\t\tmessages: Messages,\n\t\tvis: Set<Node>,\n\t\tdownOpts: NodeTransportOptions,\n\t): void {\n\t\tfor (const mk of Object.keys(root.meta).sort()) {\n\t\t\tconst mnode = root.meta[mk];\n\t\t\tif (vis.has(mnode)) continue;\n\t\t\tvis.add(mnode);\n\t\t\tmnode.down(messages, downOpts);\n\t\t\tthis._signalMetaSubtree(mnode, messages, vis, downOpts);\n\t\t}\n\t}\n\n\t/**\n\t * Static structure snapshot: qualified node keys, edges, mount names (GRAPHREFLY-SPEC §3.6, Appendix B).\n\t *\n\t * @param options - Optional `actor` for guard-scoped visibility and/or `filter` for selective output.\n\t * @returns JSON-shaped describe payload for this graph tree.\n\t *\n\t * @example\n\t * ```ts\n\t * graph.describe() // full snapshot\n\t * graph.describe({ actor: llm }) // guard-scoped\n\t * graph.describe({ filter: { status: \"errored\" } }) // only errored nodes\n\t * graph.describe({ filter: (n) => n.type === \"state\" }) // predicate filter\n\t * ```\n\t */\n\tdescribe(options?: { actor?: Actor; filter?: DescribeFilter }): GraphDescribeOutput {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\tconst nodeToPath = new Map<Node, string>();\n\t\tfor (const [p, n] of targets) {\n\t\t\tnodeToPath.set(n, p);\n\t\t}\n\t\tconst nodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const [p, n] of targets) {\n\t\t\tif (actor != null && !n.allowsObserve(actor)) continue;\n\t\t\tconst raw = describeNode(n);\n\t\t\tconst deps =\n\t\t\t\tn instanceof NodeImpl ? n._deps.map((d) => nodeToPath.get(d) ?? d.name ?? \"\") : [];\n\t\t\tconst { name: _name, ...rest } = raw;\n\t\t\tconst entry: DescribeNodeOutput = { ...rest, deps };\n\t\t\tif (filter != null) {\n\t\t\t\tif (typeof filter === \"function\") {\n\t\t\t\t\tconst fn = filter as\n\t\t\t\t\t\t| ((nodePath: string, node: DescribeNodeOutput) => boolean)\n\t\t\t\t\t\t| ((node: DescribeNodeOutput) => boolean);\n\t\t\t\t\tconst pass =\n\t\t\t\t\t\tfn.length >= 2\n\t\t\t\t\t\t\t? (fn as (nodePath: string, node: DescribeNodeOutput) => boolean)(p, entry)\n\t\t\t\t\t\t\t: (fn as (node: DescribeNodeOutput) => boolean)(entry);\n\t\t\t\t\tif (!pass) continue;\n\t\t\t\t} else {\n\t\t\t\t\tlet match = true;\n\t\t\t\t\tfor (const [fk, fv] of Object.entries(filter)) {\n\t\t\t\t\t\tconst normalizedKey =\n\t\t\t\t\t\t\tfk === \"deps_includes\" ? \"depsIncludes\" : fk === \"meta_has\" ? \"metaHas\" : fk;\n\t\t\t\t\t\tif (normalizedKey === \"depsIncludes\") {\n\t\t\t\t\t\t\tif (!entry.deps.includes(String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (normalizedKey === \"metaHas\") {\n\t\t\t\t\t\t\tif (!Object.hasOwn(entry.meta, String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((entry as Record<string, unknown>)[normalizedKey] !== fv) {\n\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) continue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodes[p] = entry;\n\t\t}\n\t\tconst nodeKeys = new Set(Object.keys(nodes));\n\t\tlet edges = this._collectAllEdges(\"\");\n\t\tif (actor != null || filter != null) {\n\t\t\tedges = edges.filter((e) => nodeKeys.has(e.from) && nodeKeys.has(e.to));\n\t\t}\n\t\tedges.sort((a, b) => {\n\t\t\tif (a.from < b.from) return -1;\n\t\t\tif (a.from > b.from) return 1;\n\t\t\tif (a.to < b.to) return -1;\n\t\t\tif (a.to > b.to) return 1;\n\t\t\treturn 0;\n\t\t});\n\t\tconst allSubgraphs = this._collectSubgraphs(\"\");\n\t\tconst subgraphs =\n\t\t\tactor != null || filter != null\n\t\t\t\t? allSubgraphs.filter((sg) => {\n\t\t\t\t\t\tconst prefix = `${sg}${PATH_SEP}`;\n\t\t\t\t\t\treturn [...nodeKeys].some((k) => k === sg || k.startsWith(prefix));\n\t\t\t\t\t})\n\t\t\t\t: allSubgraphs;\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t};\n\t}\n\n\tprivate _collectSubgraphs(prefix: string): string[] {\n\t\tconst out: string[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst q = prefix === \"\" ? m : `${prefix}${m}`;\n\t\t\tout.push(q);\n\t\t\tout.push(...this._mounts.get(m)!._collectSubgraphs(`${q}${PATH_SEP}`));\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _collectAllEdges(prefix: string): { from: string; to: string }[] {\n\t\tconst out: { from: string; to: string }[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tout.push(...this._mounts.get(m)!._collectAllEdges(p2));\n\t\t}\n\t\tfor (const [f, t] of this.edges()) {\n\t\t\tout.push({\n\t\t\t\tfrom: this._qualifyEdgeEndpoint(f, prefix),\n\t\t\t\tto: this._qualifyEdgeEndpoint(t, prefix),\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _qualifyEdgeEndpoint(part: string, prefix: string): string {\n\t\tif (part.includes(PATH_SEP)) return part;\n\t\treturn prefix === \"\" ? part : `${prefix}${PATH_SEP}${part}`;\n\t}\n\n\tprivate _collectObserveTargets(prefix: string, out: [string, Node][]): void {\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tthis._mounts.get(m)!._collectObserveTargets(p2, out);\n\t\t}\n\t\tfor (const loc of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(loc)!;\n\t\t\tconst p = prefix === \"\" ? loc : `${prefix}${PATH_SEP}${loc}`;\n\t\t\tout.push([p, n]);\n\t\t\tthis._appendMetaObserveTargets(p, n, out);\n\t\t}\n\t}\n\n\tprivate _appendMetaObserveTargets(basePath: string, n: Node, out: [string, Node][]): void {\n\t\tfor (const mk of Object.keys(n.meta).sort()) {\n\t\t\tconst m = n.meta[mk];\n\t\t\tconst mp = `${basePath}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${mk}`;\n\t\t\tout.push([mp, m]);\n\t\t\tthis._appendMetaObserveTargets(mp, m, out);\n\t\t}\n\t}\n\n\t/**\n\t * Live message stream from one node (or meta path), or from the whole graph (§3.6).\n\t *\n\t * Overloads: `(path, options?)` for one node; `(options?)` for all nodes. Whole-graph mode\n\t * subscribes in **sorted path order** (code-point order). With structured options\n\t * (`structured`, `timeline`, `causal`, `derived`), returns an {@link ObserveResult}.\n\t * Inspector-gated extras (`causal` / `derived`) require {@link Graph.inspectorEnabled}.\n\t *\n\t * @param pathOrOpts - Qualified `path` string, or omit and pass only `options` for graph-wide observation.\n\t * @param options - Optional `actor`, `structured`, `causal`, `timeline` (inspector-gated).\n\t * @returns `GraphObserveOne`, `GraphObserveAll`, or `ObserveResult` depending on overload/options.\n\t */\n\tobserve(\n\t\tpath: string,\n\t\toptions?: ObserveOptions & {\n\t\t\tstructured?: true;\n\t\t\ttimeline?: true;\n\t\t\tcausal?: true;\n\t\t\tderived?: true;\n\t\t},\n\t): ObserveResult;\n\tobserve(path: string, options?: ObserveOptions): GraphObserveOne;\n\tobserve(\n\t\toptions: ObserveOptions & { structured?: true; timeline?: true; causal?: true; derived?: true },\n\t): ObserveResult;\n\tobserve(options?: ObserveOptions): GraphObserveAll;\n\tobserve(\n\t\tpathOrOpts?: string | ObserveOptions,\n\t\toptions?: ObserveOptions,\n\t): GraphObserveOne | GraphObserveAll | ObserveResult {\n\t\tif (typeof pathOrOpts === \"string\") {\n\t\t\tconst path = pathOrOpts;\n\t\t\tconst actor = options?.actor;\n\t\t\tconst target = this.resolve(path);\n\t\t\tif (actor != null && !target.allowsObserve(actor)) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: path });\n\t\t\t}\n\t\t\tconst wantsStructured =\n\t\t\t\toptions?.structured === true ||\n\t\t\t\toptions?.timeline === true ||\n\t\t\t\toptions?.causal === true ||\n\t\t\t\toptions?.derived === true;\n\t\t\tif (wantsStructured && Graph.inspectorEnabled) {\n\t\t\t\treturn this._createObserveResult(path, target, options);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsubscribe(sink: NodeSink) {\n\t\t\t\t\treturn target.subscribe(sink);\n\t\t\t\t},\n\t\t\t\tup(messages: Messages) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttarget.up?.(messages);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst opts = pathOrOpts as ObserveOptions | undefined;\n\t\tconst actor = opts?.actor;\n\t\tconst wantsStructured =\n\t\t\topts?.structured === true ||\n\t\t\topts?.timeline === true ||\n\t\t\topts?.causal === true ||\n\t\t\topts?.derived === true;\n\t\tif (wantsStructured && Graph.inspectorEnabled) {\n\t\t\treturn this._createObserveResultForAll(opts ?? {});\n\t\t}\n\t\treturn {\n\t\t\tsubscribe: (sink: (nodePath: string, messages: Messages) => void) => {\n\t\t\t\tconst targets: [string, Node][] = [];\n\t\t\t\tthis._collectObserveTargets(\"\", targets);\n\t\t\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\t\t\tconst picked =\n\t\t\t\t\tactor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\t\t\tconst unsubs = picked.map(([p, nd]) =>\n\t\t\t\t\tnd.subscribe((msgs) => {\n\t\t\t\t\t\tsink(p, msgs);\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn () => {\n\t\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\t};\n\t\t\t},\n\t\t\tup: (upPath: string, messages: Messages) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst nd = this.resolve(upPath);\n\t\t\t\t\tnd.up?.(messages);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResult<T>(\n\t\tpath: string,\n\t\ttarget: Node<T>,\n\t\toptions: ObserveOptions,\n\t): ObserveResult<T> {\n\t\tconst timeline = options.timeline === true;\n\t\tconst causal = options.causal === true;\n\t\tconst derived = options.derived === true;\n\t\tconst result: {\n\t\t\tvalues: Record<string, T>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tcompletedCleanly: boolean;\n\t\t\terrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tcompletedCleanly: false,\n\t\t\terrored: false,\n\t\t};\n\n\t\tlet lastTriggerDepIndex: number | undefined;\n\t\tlet lastRunDepValues: unknown[] | undefined;\n\t\tlet detachInspectorHook: (() => void) | undefined;\n\t\tif ((causal || derived) && target instanceof NodeImpl) {\n\t\t\tdetachInspectorHook = target._setInspectorHook((event: NodeInspectorHookEvent) => {\n\t\t\t\tif (event.kind === \"dep_message\") {\n\t\t\t\t\tlastTriggerDepIndex = event.depIndex;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlastRunDepValues = [...event.depValues];\n\t\t\t\tif (derived) {\n\t\t\t\t\tresult.events.push({\n\t\t\t\t\t\ttype: \"derived\",\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tdep_values: [...event.depValues],\n\t\t\t\t\t\t...(timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {}),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst unsub = target.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst t = m[0];\n\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\tconst withCausal =\n\t\t\t\t\tcausal && lastRunDepValues != null\n\t\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\t\tconst triggerDep =\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex != null &&\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex >= 0 &&\n\t\t\t\t\t\t\t\t\ttarget instanceof NodeImpl\n\t\t\t\t\t\t\t\t\t\t? target._deps[lastTriggerDepIndex]\n\t\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\t\tconst tv = triggerDep?.v;\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\ttrigger_dep_index: lastTriggerDepIndex,\n\t\t\t\t\t\t\t\t\ttrigger_dep_name: triggerDep?.name,\n\t\t\t\t\t\t\t\t\t...(tv != null ? { trigger_version: { id: tv.id, version: tv.version } } : {}),\n\t\t\t\t\t\t\t\t\tdep_values: [...lastRunDepValues],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t})()\n\t\t\t\t\t\t: {};\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tresult.values[path] = m[1] as T;\n\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base, ...withCausal });\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base, ...withCausal });\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!result.errored) result.completedCleanly = true;\n\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tresult.errored = true;\n\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget completedCleanly() {\n\t\t\t\treturn result.completedCleanly;\n\t\t\t},\n\t\t\tget errored() {\n\t\t\t\treturn result.errored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tunsub();\n\t\t\t\tdetachInspectorHook?.();\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResultForAll(options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline === true;\n\t\tconst result: {\n\t\t\tvalues: Record<string, unknown>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tcompletedCleanly: boolean;\n\t\t\terrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tcompletedCleanly: false,\n\t\t\terrored: false,\n\t\t};\n\t\tconst actor = options.actor;\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst picked = actor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\tconst unsubs = picked.map(([path, nd]) =>\n\t\t\tnd.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tconst t = m[0];\n\t\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tresult.values[path] = m[1];\n\t\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base });\n\t\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\tif (!result.errored) result.completedCleanly = true;\n\t\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tresult.errored = true;\n\t\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget completedCleanly() {\n\t\t\t\treturn result.completedCleanly;\n\t\t\t},\n\t\t\tget errored() {\n\t\t\t\treturn result.errored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Convenience live debugger over {@link Graph.observe}. Logs protocol events as they flow.\n\t *\n\t * Supports one-node (`path`) and graph-wide modes, event filtering, and JSON/pretty rendering.\n\t * Color themes are built in (`ansi` / `none`) to avoid external dependencies.\n\t *\n\t * @param options - Spy configuration.\n\t * @returns Disposable handle plus a structured observation accumulator.\n\t */\n\tspy(options: GraphSpyOptions = {}): GraphSpyHandle {\n\t\tconst include = options.includeTypes ? new Set(options.includeTypes) : null;\n\t\tconst exclude = options.excludeTypes ? new Set(options.excludeTypes) : null;\n\t\tconst theme = resolveSpyTheme(options.theme);\n\t\tconst format = options.format ?? \"pretty\";\n\t\tconst logger = options.logger ?? ((line: string) => console.log(line));\n\n\t\tconst shouldLog = (type: ObserveEvent[\"type\"]): boolean => {\n\t\t\tif (include?.has(type) === false) return false;\n\t\t\tif (exclude?.has(type) === true) return false;\n\t\t\treturn true;\n\t\t};\n\n\t\tconst renderEvent = (event: ObserveEvent): string => {\n\t\t\tif (format === \"json\") {\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.stringify(event);\n\t\t\t\t} catch {\n\t\t\t\t\treturn JSON.stringify({\n\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\tpath: event.path,\n\t\t\t\t\t\tdata: \"[unserializable]\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst color = theme[event.type] ?? \"\";\n\t\t\tconst pathPart = event.path ? `${theme.path}${event.path}${theme.reset} ` : \"\";\n\t\t\tconst dataPart = event.data !== undefined ? ` ${describeData(event.data)}` : \"\";\n\t\t\tconst triggerPart =\n\t\t\t\tevent.trigger_dep_name != null\n\t\t\t\t\t? ` <- ${event.trigger_dep_name}`\n\t\t\t\t\t: event.trigger_dep_index != null\n\t\t\t\t\t\t? ` <- #${event.trigger_dep_index}`\n\t\t\t\t\t\t: \"\";\n\t\t\tconst batchPart = event.in_batch ? \" [batch]\" : \"\";\n\t\t\treturn `${pathPart}${color}${event.type.toUpperCase()}${theme.reset}${dataPart}${triggerPart}${batchPart}`;\n\t\t};\n\n\t\tif (!Graph.inspectorEnabled) {\n\t\t\tconst timeline = options.timeline ?? true;\n\t\t\tconst acc: {\n\t\t\t\tvalues: Record<string, unknown>;\n\t\t\t\tdirtyCount: number;\n\t\t\t\tresolvedCount: number;\n\t\t\t\tevents: ObserveEvent[];\n\t\t\t\tcompletedCleanly: boolean;\n\t\t\t\terrored: boolean;\n\t\t\t} = {\n\t\t\t\tvalues: {},\n\t\t\t\tdirtyCount: 0,\n\t\t\t\tresolvedCount: 0,\n\t\t\t\tevents: [],\n\t\t\t\tcompletedCleanly: false,\n\t\t\t\terrored: false,\n\t\t\t};\n\t\t\tlet stop: () => void = () => {};\n\t\t\tconst result: ObserveResult = {\n\t\t\t\tget values() {\n\t\t\t\t\treturn acc.values;\n\t\t\t\t},\n\t\t\t\tget dirtyCount() {\n\t\t\t\t\treturn acc.dirtyCount;\n\t\t\t\t},\n\t\t\t\tget resolvedCount() {\n\t\t\t\t\treturn acc.resolvedCount;\n\t\t\t\t},\n\t\t\t\tget events() {\n\t\t\t\t\treturn acc.events;\n\t\t\t\t},\n\t\t\t\tget completedCleanly() {\n\t\t\t\t\treturn acc.completedCleanly;\n\t\t\t\t},\n\t\t\t\tget errored() {\n\t\t\t\t\treturn acc.errored;\n\t\t\t\t},\n\t\t\t\tdispose() {\n\t\t\t\t\tstop();\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tconst pushEvent = (path: string | undefined, message: Messages[number]) => {\n\t\t\t\tconst t = message[0];\n\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\tlet event: ObserveEvent | undefined;\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tif (path != null) acc.values[path] = message[1];\n\t\t\t\t\tevent = { type: \"data\", ...(path != null ? { path } : {}), data: message[1], ...base };\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tacc.dirtyCount += 1;\n\t\t\t\t\tevent = { type: \"dirty\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tacc.resolvedCount += 1;\n\t\t\t\t\tevent = { type: \"resolved\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!acc.errored) acc.completedCleanly = true;\n\t\t\t\t\tevent = { type: \"complete\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tacc.errored = true;\n\t\t\t\t\tevent = {\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t...(path != null ? { path } : {}),\n\t\t\t\t\t\tdata: message[1],\n\t\t\t\t\t\t...base,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!event) return;\n\t\t\t\tacc.events.push(event);\n\t\t\t\tif (!shouldLog(event.type)) return;\n\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t};\n\n\t\t\tif (options.path != null) {\n\t\t\t\tconst stream = this.observe(options.path, {\n\t\t\t\t\tactor: options.actor,\n\t\t\t\t\tstructured: false,\n\t\t\t\t});\n\t\t\t\tstop = stream.subscribe((messages) => {\n\t\t\t\t\tfor (const m of messages) {\n\t\t\t\t\t\tpushEvent(options.path, m);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst stream = this.observe({ actor: options.actor, structured: false });\n\t\t\t\tstop = stream.subscribe((path, messages) => {\n\t\t\t\t\tfor (const m of messages) {\n\t\t\t\t\t\tpushEvent(path, m);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresult,\n\t\t\t\tdispose() {\n\t\t\t\t\tresult.dispose();\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst structuredObserveOptions = {\n\t\t\tactor: options.actor,\n\t\t\tstructured: true as const,\n\t\t\t...(options.timeline !== false ? { timeline: true as const } : {}),\n\t\t\t...(options.causal ? { causal: true as const } : {}),\n\t\t\t...(options.derived ? { derived: true as const } : {}),\n\t\t};\n\t\tconst result: ObserveResult =\n\t\t\toptions.path != null\n\t\t\t\t? this.observe(options.path, structuredObserveOptions)\n\t\t\t\t: this.observe(structuredObserveOptions);\n\n\t\tlet cursor = 0;\n\t\tconst flushNewEvents = () => {\n\t\t\tconst nextEvents = result.events.slice(cursor);\n\t\t\tcursor = result.events.length;\n\t\t\tfor (const event of nextEvents) {\n\t\t\t\tif (!shouldLog(event.type)) continue;\n\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t}\n\t\t};\n\n\t\tconst stream =\n\t\t\toptions.path != null\n\t\t\t\t? this.observe(options.path, { actor: options.actor, structured: false })\n\t\t\t\t: this.observe({ actor: options.actor, structured: false });\n\n\t\tconst stop =\n\t\t\toptions.path != null\n\t\t\t\t? (stream as GraphObserveOne).subscribe((messages) => {\n\t\t\t\t\t\tif (messages.length > 0) {\n\t\t\t\t\t\t\tflushNewEvents();\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t: (stream as GraphObserveAll).subscribe((_path, messages) => {\n\t\t\t\t\t\tif (messages.length > 0) {\n\t\t\t\t\t\t\tflushNewEvents();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\treturn {\n\t\t\tresult,\n\t\t\tdispose() {\n\t\t\t\tstop();\n\t\t\t\tflushNewEvents();\n\t\t\t\tresult.dispose();\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * CLI/debug-friendly graph dump built on {@link Graph.describe}.\n\t *\n\t * @param options - Optional actor/filter/format toggles.\n\t * @returns Rendered graph text.\n\t */\n\tdumpGraph(options: GraphDumpOptions = {}): string {\n\t\tconst described = this.describe({\n\t\t\tactor: options.actor,\n\t\t\tfilter: options.filter,\n\t\t});\n\t\tconst includeEdges = options.includeEdges ?? true;\n\t\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\t\tif (options.format === \"json\") {\n\t\t\tconst payload: GraphDescribeOutput = {\n\t\t\t\tname: described.name,\n\t\t\t\tnodes: described.nodes,\n\t\t\t\tedges: includeEdges ? described.edges : [],\n\t\t\t\tsubgraphs: includeSubgraphs ? described.subgraphs : [],\n\t\t\t};\n\t\t\tconst text = JSON.stringify(sortJsonValue(payload), null, options.indent ?? 2);\n\t\t\toptions.logger?.(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tconst lines: string[] = [];\n\t\tlines.push(`Graph ${described.name}`);\n\t\tlines.push(\"Nodes:\");\n\t\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\t\tconst n = described.nodes[path]!;\n\t\t\tlines.push(`- ${path} (${n.type}/${n.status}): ${describeData(n.value)}`);\n\t\t}\n\t\tif (includeEdges) {\n\t\t\tlines.push(\"Edges:\");\n\t\t\tfor (const edge of described.edges) {\n\t\t\t\tlines.push(`- ${edge.from} -> ${edge.to}`);\n\t\t\t}\n\t\t}\n\t\tif (includeSubgraphs) {\n\t\t\tlines.push(\"Subgraphs:\");\n\t\t\tfor (const sg of described.subgraphs) {\n\t\t\t\tlines.push(`- ${sg}`);\n\t\t\t}\n\t\t}\n\t\tconst text = lines.join(\"\\n\");\n\t\toptions.logger?.(text);\n\t\treturn text;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Lifecycle & persistence (§3.7–§3.8)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Sends `[[TEARDOWN]]` to all nodes, then clears registries on this graph and every\n\t * mounted subgraph (§3.7). The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\tthis.signal([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tfor (const dispose of [...this._autoCheckpointDisposers]) {\n\t\t\ttry {\n\t\t\t\tdispose();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t\tthis._autoCheckpointDisposers.clear();\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/** Clear structure after parent already signaled TEARDOWN through this subtree. */\n\tprivate _destroyClearOnly(): void {\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/**\n\t * Serializes structure and current values to JSON-shaped data (§3.8). Same information\n\t * as {@link Graph.describe} plus a `version` field for format evolution.\n\t *\n\t * @returns Persistable snapshot with sorted keys.\n\t */\n\tsnapshot(): GraphPersistSnapshot {\n\t\tconst d = this.describe();\n\t\t// Explicit key sorting for deterministic output — don't rely on\n\t\t// describe() iteration order (audit batch-3, §3.8).\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tsortedNodes[key] = d.nodes[key]!;\n\t\t}\n\t\tconst sortedSubgraphs = [...d.subgraphs].sort();\n\t\treturn { ...d, version: 1, nodes: sortedNodes, subgraphs: sortedSubgraphs };\n\t}\n\n\t/**\n\t * Apply persisted values onto an existing graph whose topology matches the snapshot\n\t * (§3.8). Only {@link DescribeNodeOutput.type} `state` and `producer` entries with a\n\t * `value` field are written; `derived` / `operator` / `effect` are skipped so deps\n\t * drive recomputation. Unknown paths are ignored.\n\t *\n\t * @param data - Snapshot envelope with matching `name` and node slices.\n\t * @throws If `data.name` does not equal {@link Graph.name}.\n\t */\n\trestore(data: GraphPersistSnapshot, options?: { only?: string | readonly string[] }): void {\n\t\tparseSnapshotEnvelope(data);\n\t\tif (data.name !== this.name) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": restore snapshot name \"${data.name}\" does not match this graph`,\n\t\t\t);\n\t\t}\n\t\tconst onlyPatterns =\n\t\t\toptions?.only == null\n\t\t\t\t? null\n\t\t\t\t: (Array.isArray(options.only) ? options.only : [options.only]).map((p) => globToRegex(p));\n\t\tfor (const path of Object.keys(data.nodes).sort()) {\n\t\t\tif (onlyPatterns !== null && !onlyPatterns.some((re) => re.test(path))) continue;\n\t\t\tconst slice = data.nodes[path];\n\t\t\tif (slice === undefined || slice.value === undefined) continue;\n\t\t\tif (slice.type === \"derived\" || slice.type === \"operator\" || slice.type === \"effect\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.set(path, slice.value);\n\t\t\t} catch {\n\t\t\t\t/* missing path or set not applicable */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a graph named from the snapshot, optionally runs `build` to register nodes\n\t * and mounts, then {@link Graph.restore} values (§3.8).\n\t *\n\t * @param data - Snapshot envelope (`version` checked).\n\t * @param build - Optional callback to construct topology before values are applied.\n\t * @returns Hydrated `Graph` instance.\n\t */\n\tstatic fromSnapshot(data: GraphPersistSnapshot, build?: (g: Graph) => void): Graph {\n\t\tparseSnapshotEnvelope(data);\n\t\tconst g = new Graph(data.name);\n\t\tif (build) {\n\t\t\tbuild(g);\n\t\t\tg.restore(data);\n\t\t\treturn g;\n\t\t}\n\t\t// Auto-create mount hierarchy from subgraphs.\n\t\tfor (const mount of [...data.subgraphs].sort((a, b) => {\n\t\t\tconst da = a.split(PATH_SEP).length;\n\t\t\tconst db = b.split(PATH_SEP).length;\n\t\t\tif (da !== db) return da - db;\n\t\t\tif (a < b) return -1;\n\t\t\tif (a > b) return 1;\n\t\t\treturn 0;\n\t\t})) {\n\t\t\tconst parts = mount.split(PATH_SEP);\n\t\t\tlet target: Graph = g;\n\t\t\tfor (const seg of parts) {\n\t\t\t\tif (!target._mounts.has(seg)) {\n\t\t\t\t\ttarget.mount(seg, new Graph(seg));\n\t\t\t\t}\n\t\t\t\ttarget = target._mounts.get(seg)!;\n\t\t\t}\n\t\t}\n\n\t\tconst primaryEntries = Object.entries(data.nodes)\n\t\t\t.filter(([path]) => !path.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`))\n\t\t\t.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst pending = new Map(primaryEntries);\n\t\tconst created = new Map<string, Node>();\n\n\t\tlet progressed = true;\n\t\twhile (pending.size > 0 && progressed) {\n\t\t\tprogressed = false;\n\t\t\tfor (const [path, slice] of [...pending.entries()]) {\n\t\t\t\tconst deps = slice?.deps ?? [];\n\t\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\t\t\t\tconst [owner, localName] = Graph._ownerForPath(g, path);\n\t\t\t\tconst meta: Record<string, unknown> = { ...(slice?.meta ?? {}) };\n\t\t\t\tconst factory = Graph._factoryForPath(path);\n\t\t\t\tlet node: Node;\n\t\t\t\tif (slice?.type === \"state\") {\n\t\t\t\t\tnode = stateNode(slice.value, { meta });\n\t\t\t\t} else {\n\t\t\t\t\tif (factory == null) continue;\n\t\t\t\t\tnode = factory(localName, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\ttype: slice.type,\n\t\t\t\t\t\tvalue: slice.value,\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tresolvedDeps: deps.map((dep) => created.get(dep)!),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\towner.add(localName, node);\n\t\t\t\tcreated.set(path, node);\n\t\t\t\tpending.delete(path);\n\t\t\t\tprogressed = true;\n\t\t\t}\n\t\t}\n\t\tif (pending.size > 0) {\n\t\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`Graph.fromSnapshot could not reconstruct nodes without build callback: ${unresolved}. ` +\n\t\t\t\t\t`Register matching factories with Graph.registerFactory(pattern, factory).`,\n\t\t\t);\n\t\t}\n\t\tfor (const edge of data.edges) {\n\t\t\ttry {\n\t\t\t\tg.connect(edge.from, edge.to);\n\t\t\t} catch {\n\t\t\t\t/* ignore malformed or non-reconstructable edge */\n\t\t\t}\n\t\t}\n\t\tg.restore(data);\n\t\treturn g;\n\t}\n\n\t/**\n\t * Plain snapshot with **recursively sorted object keys** for deterministic serialization (§3.8).\n\t *\n\t * @remarks\n\t * ECMAScript `JSON.stringify(graph)` invokes this method; it must return a plain object, not an\n\t * already-stringified JSON string (otherwise the graph would be double-encoded).\n\t * For a single UTF-8 string with a trailing newline (convenient for git), use {@link Graph.toJSONString}.\n\t *\n\t * @returns Same object as {@link Graph.snapshot}.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * Deterministic JSON **text**: `JSON.stringify` of {@link Graph.toJSON} plus a trailing newline (§3.8).\n\t *\n\t * @returns Stable string suitable for diffs.\n\t */\n\ttoJSONString(): string {\n\t\treturn stableJsonStringify(this.snapshot());\n\t}\n\n\t/**\n\t * Debounced persistence wired to graph-wide observe stream (spec §3.8 auto-checkpoint).\n\t *\n\t * Checkpoint trigger uses {@link messageTier}: only batches containing tier >= 2 messages\n\t * schedule a save (`DATA`/`RESOLVED`/terminal/destruction), never pure tier-0/1 control waves.\n\t */\n\tautoCheckpoint(\n\t\tadapter: AutoCheckpointAdapter,\n\t\toptions: GraphAutoCheckpointOptions = {},\n\t): GraphAutoCheckpointHandle {\n\t\tconst debounceMs = Math.max(0, options.debounceMs ?? 500);\n\t\tconst compactEvery = Math.max(1, options.compactEvery ?? 10);\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet seq = 0;\n\t\tlet pending = false;\n\t\tlet lastDescribe: GraphDescribeOutput | undefined;\n\n\t\tconst flush = () => {\n\t\t\ttimer = undefined;\n\t\t\tif (!pending) return;\n\t\t\tpending = false;\n\t\t\ttry {\n\t\t\t\tconst described = this.describe();\n\t\t\t\tconst snapshot = { ...described, version: SNAPSHOT_VERSION };\n\t\t\t\tseq += 1;\n\t\t\t\tconst shouldCompact = lastDescribe == null || seq % compactEvery === 0;\n\t\t\t\tif (shouldCompact) {\n\t\t\t\t\tadapter.save({ mode: \"full\", snapshot, seq } satisfies GraphCheckpointRecord);\n\t\t\t\t} else {\n\t\t\t\t\tconst previous = lastDescribe;\n\t\t\t\t\tif (previous == null) return;\n\t\t\t\t\tadapter.save({\n\t\t\t\t\t\tmode: \"diff\",\n\t\t\t\t\t\tdiff: Graph.diff(previous, described),\n\t\t\t\t\t\tsnapshot,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t} satisfies GraphCheckpointRecord);\n\t\t\t\t}\n\t\t\t\tlastDescribe = described;\n\t\t\t} catch (error) {\n\t\t\t\toptions.onError?.(error);\n\t\t\t}\n\t\t};\n\n\t\tconst schedule = () => {\n\t\t\tpending = true;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = setTimeout(flush, debounceMs);\n\t\t};\n\n\t\tconst off = this.observe().subscribe((path, messages) => {\n\t\t\tconst triggeredByTier = messages.some((m) => messageTier(m[0]) >= 2);\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst described = this.describe().nodes[path];\n\t\t\t\tif (described == null || !options.filter(path, described)) return;\n\t\t\t}\n\t\t\tschedule();\n\t\t});\n\n\t\tconst dispose = () => {\n\t\t\toff();\n\t\t\tif (timer !== undefined) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = undefined;\n\t\t\t}\n\t\t\tthis._autoCheckpointDisposers.delete(dispose);\n\t\t};\n\t\tthis._autoCheckpointDisposers.add(dispose);\n\t\treturn { dispose };\n\t}\n\n\t/**\n\t * Export the current graph topology as Mermaid flowchart text.\n\t *\n\t * Renders qualified node paths and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns Mermaid flowchart source.\n\t */\n\ttoMermaid(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`flowchart ${direction}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(` ${id}[\"${escapeMermaidLabel(path)}\"]`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(` ${fromId} --> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t/**\n\t * Export the current graph topology as D2 diagram text.\n\t *\n\t * Renders qualified node paths, constructor deps, and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns D2 source text.\n\t */\n\ttoD2(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`direction: ${d2DirectionFromGraphDirection(direction)}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(`${id}: \"${escapeD2Label(path)}\"`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(`${fromId} -> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Inspector (roadmap 3.3) — reasoning trace, overhead gating\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * When `false`, structured observation options (`causal`, `timeline`),\n\t * `annotate()`, and `traceLog()` are no-ops. Raw `observe()` always works.\n\t *\n\t * Default: `true` outside production (`process.env.NODE_ENV !== \"production\"`).\n\t */\n\tstatic inspectorEnabled = !(\n\t\ttypeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n\t);\n\n\tprivate _annotations = new Map<string, string>();\n\tprivate _traceRing = new RingBuffer<TraceEntry>(1000);\n\n\t/**\n\t * Attaches a reasoning annotation to a node — captures *why* an AI agent set a value.\n\t *\n\t * No-op when {@link Graph.inspectorEnabled} is `false`.\n\t *\n\t * @param path - Qualified node path.\n\t * @param reason - Free-text note stored in the trace ring buffer.\n\t */\n\tannotate(path: string, reason: string): void {\n\t\tif (!Graph.inspectorEnabled) return;\n\t\tthis.resolve(path); // validate path exists\n\t\tthis._annotations.set(path, reason);\n\t\tthis._traceRing.push({ path, reason, timestamp_ns: monotonicNs() });\n\t}\n\n\t/**\n\t * Returns a chronological log of all reasoning annotations (ring buffer).\n\t *\n\t * @returns `[]` when {@link Graph.inspectorEnabled} is `false`.\n\t */\n\ttraceLog(): readonly TraceEntry[] {\n\t\tif (!Graph.inspectorEnabled) return [];\n\t\treturn this._traceRing.toArray();\n\t}\n\n\t/**\n\t * Computes structural + value diff between two {@link Graph.describe} snapshots.\n\t *\n\t * @param a - Earlier describe output.\n\t * @param b - Later describe output.\n\t * @returns Added/removed nodes, changed fields, and edge deltas.\n\t */\n\tstatic diff(a: GraphDescribeOutput, b: GraphDescribeOutput): GraphDiffResult {\n\t\tconst aKeys = new Set(Object.keys(a.nodes));\n\t\tconst bKeys = new Set(Object.keys(b.nodes));\n\n\t\tconst nodesAdded = [...bKeys].filter((k) => !aKeys.has(k)).sort();\n\t\tconst nodesRemoved = [...aKeys].filter((k) => !bKeys.has(k)).sort();\n\t\tconst nodesChanged: GraphDiffChange[] = [];\n\n\t\tfor (const key of aKeys) {\n\t\t\tif (!bKeys.has(key)) continue;\n\t\t\tconst na = a.nodes[key];\n\t\t\tconst nb = b.nodes[key];\n\t\t\t// V0 optimization: skip value comparison when both nodes have matching versions.\n\t\t\tconst av = na.v;\n\t\t\tconst bv = nb.v;\n\t\t\tif (av != null && bv != null && av.id === bv.id && av.version === bv.version) {\n\t\t\t\t// Version unchanged — only check type/status (cheap string compare).\n\t\t\t\tfor (const field of [\"type\", \"status\"] as const) {\n\t\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\t\tif (va !== vb) {\n\t\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const field of [\"type\", \"status\", \"value\"] as const) {\n\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\tif (!Object.is(va, vb) && JSON.stringify(va) !== JSON.stringify(vb)) {\n\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst edgeKey = (e: { from: string; to: string }) => `${e.from}\\t${e.to}`;\n\t\tconst aEdges = new Set(a.edges.map(edgeKey));\n\t\tconst bEdges = new Set(b.edges.map(edgeKey));\n\n\t\tconst edgesAdded = b.edges.filter((e) => !aEdges.has(edgeKey(e)));\n\t\tconst edgesRemoved = a.edges.filter((e) => !bEdges.has(edgeKey(e)));\n\t\tconst aSubgraphs = new Set(a.subgraphs);\n\t\tconst bSubgraphs = new Set(b.subgraphs);\n\t\tconst subgraphsAdded = [...bSubgraphs].filter((s) => !aSubgraphs.has(s)).sort();\n\t\tconst subgraphsRemoved = [...aSubgraphs].filter((s) => !bSubgraphs.has(s)).sort();\n\n\t\treturn {\n\t\t\tnodesAdded,\n\t\t\tnodesRemoved,\n\t\t\tnodesChanged,\n\t\t\tedgesAdded,\n\t\t\tedgesRemoved,\n\t\t\tsubgraphsAdded,\n\t\t\tsubgraphsRemoved,\n\t\t};\n\t}\n}\n\n/** Entry in the reasoning trace ring buffer (roadmap 3.3). */\nexport type TraceEntry = {\n\tpath: string;\n\treason: string;\n\ttimestamp_ns: number;\n};\n\n/** Result of {@link Graph.diff}. */\nexport type GraphDiffResult = {\n\tnodesAdded: string[];\n\tnodesRemoved: string[];\n\tnodesChanged: GraphDiffChange[];\n\tedgesAdded: Array<{ from: string; to: string }>;\n\tedgesRemoved: Array<{ from: string; to: string }>;\n\tsubgraphsAdded: string[];\n\tsubgraphsRemoved: string[];\n};\n\n/** A single field change within a diff. */\nexport type GraphDiffChange = {\n\tpath: string;\n\tfield: string;\n\tfrom: unknown;\n\tto: unknown;\n};\n\n/** Direction for {@link reachable} graph traversal. */\nexport type ReachableDirection = \"upstream\" | \"downstream\";\n\n/** Options for {@link reachable}. */\nexport type ReachableOptions = {\n\t/** Maximum hop depth from `from` (0 returns `[]`). Omit for unbounded traversal. */\n\tmaxDepth?: number;\n};\n\n/**\n * Reachability query over a {@link Graph.describe} snapshot.\n *\n * Traversal combines dependency links (`deps`) and explicit graph edges (`edges`):\n * - `upstream`: follows `deps` plus incoming edges.\n * - `downstream`: follows reverse-`deps` plus outgoing edges.\n *\n * @param described - `graph.describe()` output to traverse.\n * @param from - Start path (qualified node path).\n * @param direction - Traversal direction.\n * @param options - Optional max depth bound.\n * @returns Sorted list of reachable paths (excluding `from`).\n *\n * @example\n * ```ts\n * import { Graph, reachable } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const a = g.register(\"a\");\n * const b = g.register(\"b\", [a]);\n * const described = g.describe();\n *\n * reachable(described, \"app.a\", \"downstream\"); // [\"app.b\"]\n * reachable(described, \"app.b\", \"upstream\"); // [\"app.a\"]\n * ```\n */\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions: ReachableOptions = {},\n): string[] {\n\tif (!from) return [];\n\tif (direction !== \"upstream\" && direction !== \"downstream\") {\n\t\tthrow new Error(`reachable: direction must be \"upstream\" or \"downstream\"`);\n\t}\n\tconst maxDepth = options.maxDepth;\n\tif (maxDepth != null && (!Number.isInteger(maxDepth) || maxDepth < 0)) {\n\t\tthrow new Error(`reachable: maxDepth must be an integer >= 0`);\n\t}\n\tif (maxDepth === 0) return [];\n\n\tconst depsByPath = new Map<string, string[]>();\n\tconst reverseDeps = new Map<string, Set<string>>();\n\tconst incomingEdges = new Map<string, Set<string>>();\n\tconst outgoingEdges = new Map<string, Set<string>>();\n\tconst universe = new Set<string>();\n\n\tconst nodesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"nodes\" in described &&\n\t\ttypeof (described as Record<string, unknown>).nodes === \"object\" &&\n\t\t(described as Record<string, unknown>).nodes !== null &&\n\t\t!Array.isArray((described as Record<string, unknown>).nodes)\n\t\t\t? ((described as Record<string, unknown>).nodes as Record<string, unknown>)\n\t\t\t: {};\n\tconst edgesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"edges\" in described &&\n\t\tArray.isArray((described as Record<string, unknown>).edges)\n\t\t\t? ((described as Record<string, unknown>).edges as unknown[])\n\t\t\t: [];\n\n\tfor (const [path, node] of Object.entries(nodesRaw)) {\n\t\tif (!path) continue;\n\t\tuniverse.add(path);\n\t\tconst deps =\n\t\t\tnode != null && typeof node === \"object\" && Array.isArray((node as { deps?: unknown[] }).deps)\n\t\t\t\t? (node as { deps: unknown[] }).deps\n\t\t\t\t: [];\n\t\tconst cleanDeps = deps.filter((d): d is string => typeof d === \"string\" && d.length > 0);\n\t\tdepsByPath.set(path, cleanDeps);\n\t\tfor (const dep of cleanDeps) {\n\t\t\tuniverse.add(dep);\n\t\t\tif (!reverseDeps.has(dep)) reverseDeps.set(dep, new Set());\n\t\t\treverseDeps.get(dep)!.add(path);\n\t\t}\n\t}\n\tfor (const edge of edgesRaw) {\n\t\tif (edge == null || typeof edge !== \"object\") continue;\n\t\tconst edgeFrom =\n\t\t\t\"from\" in edge && typeof (edge as { from?: unknown }).from === \"string\"\n\t\t\t\t? ((edge as { from: string }).from as string)\n\t\t\t\t: \"\";\n\t\tconst edgeTo =\n\t\t\t\"to\" in edge && typeof (edge as { to?: unknown }).to === \"string\"\n\t\t\t\t? ((edge as { to: string }).to as string)\n\t\t\t\t: \"\";\n\t\tif (!edgeFrom || !edgeTo) continue;\n\t\tuniverse.add(edgeFrom);\n\t\tuniverse.add(edgeTo);\n\t\tif (!outgoingEdges.has(edgeFrom)) outgoingEdges.set(edgeFrom, new Set());\n\t\toutgoingEdges.get(edgeFrom)!.add(edgeTo);\n\t\tif (!incomingEdges.has(edgeTo)) incomingEdges.set(edgeTo, new Set());\n\t\tincomingEdges.get(edgeTo)!.add(edgeFrom);\n\t}\n\n\tif (!universe.has(from)) return [];\n\n\tconst neighbors = (path: string): string[] => {\n\t\tif (direction === \"upstream\") {\n\t\t\tconst depNeighbors = depsByPath.get(path) ?? [];\n\t\t\tconst edgeNeighbors = [...(incomingEdges.get(path) ?? [])];\n\t\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t\t}\n\t\tconst depNeighbors = [...(reverseDeps.get(path) ?? [])];\n\t\tconst edgeNeighbors = [...(outgoingEdges.get(path) ?? [])];\n\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t};\n\n\tconst visited = new Set<string>([from]);\n\tconst out = new Set<string>();\n\tconst queue: Array<{ path: string; depth: number }> = [{ path: from, depth: 0 }];\n\twhile (queue.length > 0) {\n\t\tconst next = queue.shift()!;\n\t\tif (maxDepth != null && next.depth >= maxDepth) continue;\n\t\tfor (const nb of neighbors(next.path)) {\n\t\t\tif (!nb || visited.has(nb)) continue;\n\t\t\tvisited.add(nb);\n\t\t\tout.add(nb);\n\t\t\tqueue.push({ 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;;;ACgJO,IAAM,YAAwB;AAAA,EACpC,aAAa;AAAA,EACb,MAAM;AAAA,EAEN,OAAO,UAA4C;AAElD,UAAM,OAAO,KAAK,UAAU,QAAQ;AACpC,WAAO,IAAI,YAAY,EAAE,OAAO,IAAI;AAAA,EACrC;AAAA,EAEA,OAAO,QAA0C;AAChD,UAAM,OAAO,IAAI,YAAY,EAAE,OAAO,MAAM;AAC5C,WAAO,KAAK,MAAM,IAAI;AAAA,EACvB;AACD;AAmBO,SAAS,mBAAmB,SAGpB;AACd,SAAO;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,IACN,QAAQ,CAAC,aAAa,QAAQ,OAAO,QAAQ;AAAA,IAC7C,QAAQ,CAAC,WAAW,QAAQ,OAAO,MAAM;AAAA,EAC1C;AACD;AAeO,SAAS,uBACf,SAIA,MAIa;AACb,SAAO;AAAA,IACN,aAAa;AAAA,IACb,MAAM;AAAA,IACN,QAAQ,CAAC,aAAa,KAAK,aAAa,QAAQ,OAAO,QAAQ,CAAC;AAAA,IAChE,QAAQ,CAAC,WAAW,QAAQ,OAAO,KAAK,eAAe,MAAM,CAAC;AAAA,EAC/D;AACD;AAYO,SAAS,eACf,iBACA,oBACoB;AACpB,QAAM,YAAY,IAAI,IAAI,kBAAkB;AAC5C,aAAW,SAAS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