@graphrefly/graphrefly 0.18.0 → 0.19.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/dist/{chunk-TNKODJ6E.js → chunk-AHRKWMNI.js} +7 -3
- package/dist/{chunk-TNKODJ6E.js.map → chunk-AHRKWMNI.js.map} +1 -1
- package/dist/{chunk-76YPZQTW.js → chunk-BER7UYLM.js} +27 -26
- package/dist/chunk-BER7UYLM.js.map +1 -0
- package/dist/{chunk-F6ORUNO7.js → chunk-IRZAGZUB.js} +34 -2
- package/dist/{chunk-F6ORUNO7.js.map → chunk-IRZAGZUB.js.map} +1 -1
- package/dist/{chunk-LB3RYLSC.js → chunk-JC2SN46B.js} +197 -42
- package/dist/chunk-JC2SN46B.js.map +1 -0
- package/dist/{chunk-KJGUP35I.js → chunk-OO5QOAXI.js} +4 -4
- package/dist/{chunk-UVWEKTYC.js → chunk-UW77D7SP.js} +3 -3
- package/dist/{chunk-J7S54G7I.js → chunk-XUOY3YKN.js} +7 -2
- package/dist/chunk-XUOY3YKN.js.map +1 -0
- package/dist/chunk-YLR5JUJZ.js +111 -0
- package/dist/chunk-YLR5JUJZ.js.map +1 -0
- package/dist/{chunk-BV3TPSBK.js → chunk-YXR3WW3Q.js} +740 -755
- package/dist/chunk-YXR3WW3Q.js.map +1 -0
- package/dist/compat/nestjs/index.cjs +931 -784
- package/dist/compat/nestjs/index.cjs.map +1 -1
- package/dist/compat/nestjs/index.d.cts +4 -4
- package/dist/compat/nestjs/index.d.ts +4 -4
- package/dist/compat/nestjs/index.js +7 -7
- package/dist/core/index.cjs +651 -664
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +7 -3
- package/dist/extra/index.cjs +686 -672
- package/dist/extra/index.cjs.map +1 -1
- package/dist/extra/index.d.cts +4 -4
- package/dist/extra/index.d.ts +4 -4
- package/dist/extra/index.js +5 -5
- package/dist/graph/index.cjs +836 -808
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +3 -3
- package/dist/graph/index.d.ts +3 -3
- package/dist/graph/index.js +8 -8
- package/dist/{graph-gISB9n3n.d.ts → graph-KsTe57nI.d.cts} +82 -8
- package/dist/{graph-BYFlyNpX.d.cts → graph-mILUUqW8.d.ts} +82 -8
- package/dist/{index-CgKPpiu8.d.ts → index-8a605sg9.d.ts} +2 -2
- package/dist/{index-DKaB2x0T.d.ts → index-B2SvPEbc.d.ts} +6 -65
- package/dist/{index-B80mMeuf.d.ts → index-BBUYZfJ1.d.cts} +122 -76
- package/dist/{index-D_tUMcpz.d.cts → index-Bjh5C1Tp.d.cts} +37 -32
- package/dist/{index-B43mC7uY.d.cts → index-BjtlNirP.d.cts} +3 -3
- package/dist/{index-7WnwgjMu.d.ts → index-BnkMgNNa.d.ts} +37 -32
- package/dist/{index-CEDaJaYE.d.ts → index-CgSiUouz.d.ts} +3 -3
- package/dist/{index-EmzYk-TG.d.cts → index-CvKzv0AW.d.ts} +122 -76
- package/dist/{index-Ci_vPaVm.d.cts → index-UudxGnzc.d.cts} +6 -65
- package/dist/{index-BqOWSFhr.d.cts → index-VHA43cGP.d.cts} +2 -2
- package/dist/index.cjs +5920 -5572
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +595 -399
- package/dist/index.d.ts +595 -399
- package/dist/index.js +4357 -4063
- package/dist/index.js.map +1 -1
- package/dist/{meta-npl5b97j.d.cts → meta-BnG7XAaE.d.cts} +394 -236
- package/dist/{meta-npl5b97j.d.ts → meta-BnG7XAaE.d.ts} +394 -236
- package/dist/{observable-DFBCBELR.d.cts → observable-C8Kx_O6k.d.cts} +1 -1
- package/dist/{observable-oAGygKvc.d.ts → observable-DcBwQY7t.d.ts} +1 -1
- package/dist/patterns/reactive-layout/index.cjs +865 -718
- package/dist/patterns/reactive-layout/index.cjs.map +1 -1
- package/dist/patterns/reactive-layout/index.d.cts +3 -3
- package/dist/patterns/reactive-layout/index.d.ts +3 -3
- package/dist/patterns/reactive-layout/index.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-76YPZQTW.js.map +0 -1
- package/dist/chunk-BV3TPSBK.js.map +0 -1
- package/dist/chunk-FCLROC4Q.js +0 -231
- package/dist/chunk-FCLROC4Q.js.map +0 -1
- package/dist/chunk-J7S54G7I.js.map +0 -1
- package/dist/chunk-LB3RYLSC.js.map +0 -1
- /package/dist/{chunk-KJGUP35I.js.map → chunk-OO5QOAXI.js.map} +0 -0
- /package/dist/{chunk-UVWEKTYC.js.map → chunk-UW77D7SP.js.map} +0 -0
package/dist/core/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/index.ts","../../src/core/actor.ts","../../src/core/messages.ts","../../src/core/batch.ts","../../src/core/clock.ts","../../src/core/guard.ts","../../src/core/versioning.ts","../../src/core/node.ts","../../src/core/bridge.ts","../../src/core/dynamic-node.ts","../../src/core/meta.ts","../../src/core/sugar.ts","../../src/core/timer.ts"],"sourcesContent":["/**\n * Core layer: message protocol, node primitive, lifecycle (Phase 0).\n */\nexport * from \"./actor.js\";\nexport * from \"./batch.js\";\nexport { type BridgeOptions, bridge, DEFAULT_DOWN } from \"./bridge.js\";\nexport { monotonicNs, wallClockNs } from \"./clock.js\";\nexport * from \"./dynamic-node.js\";\nexport * from \"./guard.js\";\nexport * from \"./messages.js\";\nexport {\n\ttype DescribeDetail,\n\ttype DescribeField,\n\ttype DescribeNodeOutput,\n\tresolveDescribeFields,\n} from \"./meta.js\";\nexport {\n\tCLEANUP_RESULT,\n\ttype CleanupResult,\n\tcleanupResult,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeFn,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\tnode,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node.js\";\nexport * from \"./sugar.js\";\nexport { ResettableTimer } from \"./timer.js\";\nexport {\n\tadvanceVersion,\n\tcreateVersioning,\n\tdefaultHash,\n\ttype HashFn,\n\tisV1,\n\ttype NodeVersionInfo,\n\ttype V0,\n\ttype V1,\n\ttype VersioningLevel,\n\ttype VersioningOptions,\n} from \"./versioning.js\";\n","/**\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 * 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 `downWithBatch`, messages are partitioned by tier and delivered\n * in tier order. This ensures phase-2 values (DATA/RESOLVED) reach sinks before\n * terminal signals (COMPLETE/ERROR) mark the node as done, preventing the\n * \"COMPLETE-before-DATA\" class of bugs. Sources that emit in canonical order\n * naturally partition correctly with zero overhead.\n *\n * Unknown message types (forward-compat) are tier 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\tmessageTier,\n\tRESOLVED,\n} from \"./messages.js\";\n\n/**\n * §1.3.7 — Inside a batch, DIRTY propagates immediately; DATA and RESOLVED are\n * deferred until the outermost `batch()` callback returns. Terminal signals\n * (COMPLETE, ERROR) are delivered after phase-2 messages in the same batch\n * (see canonical ordering in `messages.ts`).\n */\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\nconst pendingPhase2: Array<() => void> = [];\nconst pendingPhase3: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * deferred phase-2 work is draining.\n *\n * Matching Python's `is_batching()` semantics: nested emissions during drain\n * are deferred until the current drain pass completes, preventing ordering\n * bugs when callbacks trigger further DATA/RESOLVED.\n *\n * @returns `true` while inside `batch()` or while the drain loop is running.\n *\n * @example\n * ```ts\n * import { batch, isBatching } from \"@graphrefly/graphrefly-ts\";\n *\n * batch(() => {\n * console.log(isBatching()); // true\n * });\n * ```\n *\n * @category core\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral queue.\n * If `fn` throws (including from a nested `batch`), deferred DATA/RESOLVED for\n * that **outer** `batch` frame are discarded — phase-2 is not flushed after an\n * error. While the drain loop is running (`flushInProgress`), a nested `batch`\n * that throws must **not** clear the global queue (cross-language decision A4).\n *\n * During the drain loop, `isBatching()` remains true so nested `downWithBatch`\n * calls still defer phase-2 messages. The drain loop runs until the queue is\n * quiescent (no pending work remains). Per-emission try/catch ensures one\n * throwing callback does not orphan remaining emissions; the first error is\n * re-thrown after all emissions drain. Callbacks that ran before the throw may\n * have applied phase-2 — partial graph state is intentional (decision C1).\n *\n * @param fn — Synchronous work that may call `downWithBatch` / `node.down()`.\n * @returns `void` — all side-effects happen through `downWithBatch` and the\n * phase-2 drain that runs after `fn` returns.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.batch(() => {\n * core.downWithBatch(sink, [[core.DATA, 1]]);\n * });\n * ```\n *\n * @category core\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\t// Do not wipe the outer drain's queue (decision A4).\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) {\n\t\tflushInProgress = true;\n\t}\n\tconst errors: unknown[] = [];\n\ttry {\n\t\tlet iterations = 0;\n\t\t// Drain phase-2 first, then phase-3. If phase-3 callbacks enqueue new\n\t\t// phase-2 work, the outer loop catches it and drains phase-2 again\n\t\t// before re-entering phase-3.\n\t\twhile (pendingPhase2.length > 0 || pendingPhase3.length > 0) {\n\t\t\t// Phase-2 (DATA/RESOLVED) — parent node values settle here.\n\t\t\twhile (pendingPhase2.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase2.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Phase-3 — meta companion emissions that must follow parent settlement.\n\t\t\tif (pendingPhase3.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase3.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) {\n\t\t\tflushInProgress = false;\n\t\t}\n\t}\n\tif (errors.length === 1) {\n\t\tthrow errors[0];\n\t}\n\tif (errors.length > 1) {\n\t\tthrow new AggregateError(errors, \"batch drain: multiple callbacks threw\");\n\t}\n}\n\n/**\n * Splits a message array into three groups by signal tier (see `messages.ts`):\n *\n * - **immediate** — tier 0–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 downstream through `sink`, applying batch semantics and\n * canonical tier-based ordering (see `messages.ts`):\n *\n * 1. **Immediate** (tier 0–1, 4): DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN,\n * unknown — delivered 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 delivered after phase-2 synchronously.\n *\n * This ordering prevents the \"COMPLETE-before-DATA\" class of bugs: terminal\n * signals never make a node terminal before phase-2 values reach sinks,\n * regardless of how the source assembled the message array.\n *\n * @param sink — Sink callback. May be called up to three times per invocation\n * (immediate, deferred, terminal) when not batching.\n * @param messages — Full `[[Type, Data?], ...]` array for one downstream delivery.\n * @param phase — Starting delivery phase (`2` = data, `3` = terminal). Default `2`.\n * @param options - Optional configuration.\n * @option strategy | `\"partition\"` or `\"sequential\"` | `\"partition\"` | `\"partition\"` groups by tier; `\"sequential\"` preserves message order within each tier using `messageTier()` classification.\n * @returns `void` — delivery is performed through `sink` callbacks, synchronously\n * or deferred into the active batch queue.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.downWithBatch((msgs) => console.log(msgs), [[core.DIRTY], [core.DATA, 42]]);\n * ```\n *\n * @category core\n */\n/** Delivery strategy for {@link downWithBatch}. Mirrors Python `DownStrategy`. */\nexport type DownStrategy = \"partition\" | \"sequential\";\n\nexport function downWithBatch(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n\toptions?: { strategy?: DownStrategy },\n): void {\n\tif (messages.length === 0) {\n\t\treturn;\n\t}\n\n\tif (options?.strategy === \"sequential\") {\n\t\t_downSequential(sink, messages, phase);\n\t\treturn;\n\t}\n\n\tconst queue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\n\t// Fast path: single-message batches (most common in graph-internal propagation)\n\t// skip partitionForBatch allocation entirely.\n\tif (messages.length === 1) {\n\t\tconst t = messages[0][0];\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else if (isTerminalMessage(t)) {\n\t\t\t// Terminal single message: defer when batching so any preceding\n\t\t\t// phase-2 in the queue flushes first.\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate: deliver synchronously.\n\t\t\tsink(messages);\n\t\t}\n\t\treturn;\n\t}\n\t// Multi-message: three-way partition by tier.\n\tconst { immediate, deferred, terminal } = partitionForBatch(messages);\n\n\t// 1. Immediate signals (tier 0–1, 4) — deliver synchronously now.\n\tif (immediate.length > 0) {\n\t\tsink(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(() => sink(deferred));\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tqueue.push(() => sink(terminal));\n\t\t}\n\t} else {\n\t\tif (deferred.length > 0) {\n\t\t\tsink(deferred);\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tsink(terminal);\n\t\t}\n\t}\n}\n\n/**\n * Sequential strategy: walk messages one at a time. Phase-2 (DATA/RESOLVED) and\n * terminal (COMPLETE/ERROR) messages are deferred while batching; immediate\n * messages deliver synchronously. Matches graphrefly-py `_down_sequential`.\n */\nfunction _downSequential(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n): void {\n\tconst dataQueue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\tfor (const msg of messages) {\n\t\tconst tier = messageTier(msg[0]);\n\t\tif (tier === 2) {\n\t\t\t// Phase-2 (DATA/RESOLVED): defer while batching.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tdataQueue.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else if (tier >= 3) {\n\t\t\t// Terminal (COMPLETE/ERROR/TEARDOWN): always route to phase-3\n\t\t\t// regardless of the caller's `phase` param — terminals must\n\t\t\t// drain after all phase-2 work to prevent premature termination.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tpendingPhase3.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate (DIRTY, INVALIDATE, PAUSE, RESUME): deliver synchronously.\n\t\t\tsink([msg]);\n\t\t}\n\t}\n}\n","/**\n * Centralised timestamp utilities.\n *\n * Convention: all graphrefly-ts timestamps use nanoseconds (`_ns` suffix).\n *\n * - {@link monotonicNs} — monotonic clock (ordering, durations, timeline events).\n * - {@link wallClockNs} — wall-clock (mutation attribution, cron emission).\n *\n * **Precision limits (JS platform):**\n *\n * - `monotonicNs`: effective ~microsecond precision. `performance.now()` returns\n * milliseconds with ~5µs resolution; the last 3 digits of the nanosecond value\n * are always zero. Python's `time.monotonic_ns()` gives true nanoseconds.\n *\n * - `wallClockNs`: ~256ns precision loss at current epoch. `Date.now() * 1e6`\n * produces values around 1.8×10¹⁸ which exceed IEEE 754's 2⁵³ safe integer\n * limit. Python's `time.time_ns()` (arbitrary-precision `int`) has no loss.\n * In practice this is irrelevant — JS is single-threaded, so sub-microsecond\n * timestamp collisions cannot occur.\n */\n\n/** Monotonic nanosecond timestamp via `performance.now()`. */\nexport function monotonicNs(): number {\n\treturn Math.trunc(performance.now() * 1_000_000);\n}\n\n/** Wall-clock nanosecond timestamp via `Date.now()`. */\nexport function wallClockNs(): number {\n\treturn Date.now() * 1_000_000;\n}\n","import type { Actor } from \"./actor.js\";\n\n/**\n * Actions checked by {@link NodeGuard}. `write` covers both {@link Node.down} and\n * {@link Node.up} today; finer-grained strings may be added later (e.g. `\"write.data\"`).\n */\nexport type GuardAction = \"write\" | \"signal\" | \"observe\" | (string & {});\n\nexport type NodeGuard = (actor: Actor, action: GuardAction) => boolean;\n\nexport type GuardDeniedDetails = {\n\tactor: Actor;\n\taction: GuardAction;\n\t/** Registry or options name when known */\n\tnodeName?: string;\n};\n\n/**\n * Thrown when a {@link NodeGuard} denies an action for a given actor.\n *\n * Carries the rejected `actor`, `action`, and optional `nodeName` for diagnostic\n * messages and middleware error handling.\n *\n * @example\n * ```ts\n * import { GuardDenied, policy } from \"@graphrefly/graphrefly-ts\";\n *\n * const guard = policy((allow) => { allow(\"observe\"); });\n * try {\n * if (!guard({ type: \"llm\", id: \"agent-1\" }, \"write\")) {\n * throw new GuardDenied(\n * { actor: { type: \"llm\", id: \"agent-1\" }, action: \"write\", nodeName: \"userInput\" },\n * );\n * }\n * } catch (e) {\n * if (e instanceof GuardDenied) console.error(e.action, e.actor.type); // \"write\" \"llm\"\n * }\n * ```\n */\nexport class GuardDenied extends Error {\n\treadonly actor: Actor;\n\treadonly action: GuardAction;\n\treadonly nodeName?: string;\n\n\t/**\n\t * @param details - Actor, action, and optional node name for the denial.\n\t * @param message - Optional override for the default error message.\n\t */\n\tconstructor(details: GuardDeniedDetails, message?: string) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\t`GuardDenied: action \"${String(details.action)}\" denied for actor type \"${String(details.actor.type)}\"`,\n\t\t);\n\t\tthis.name = \"GuardDenied\";\n\t\tthis.actor = details.actor;\n\t\tthis.action = details.action;\n\t\tthis.nodeName = details.nodeName;\n\t}\n\n\t/** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */\n\tget node(): string | undefined {\n\t\treturn this.nodeName;\n\t}\n}\n\ntype Where = (actor: Actor) => boolean;\n\ntype Rule = {\n\tkind: \"allow\" | \"deny\";\n\tactions: Set<GuardAction>;\n\twhere: Where;\n};\n\nfunction normalizeActions(action: GuardAction | readonly GuardAction[]): GuardAction[] {\n\tif (Array.isArray(action)) {\n\t\treturn [...action];\n\t}\n\treturn [action as GuardAction];\n}\n\nfunction matchesActions(set: Set<GuardAction>, action: GuardAction): boolean {\n\treturn set.has(action) || set.has(\"*\" as GuardAction);\n}\n\nexport type PolicyAllow = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyDeny = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyRuleData = {\n\teffect: \"allow\" | \"deny\";\n\taction: GuardAction | readonly GuardAction[];\n\tactorType?: string | readonly string[];\n\tactorId?: string | readonly string[];\n\tclaims?: Record<string, unknown>;\n};\n\n/**\n * Declarative guard builder. Precedence: any matching **deny** blocks even if an allow also matches.\n * If no rule matches, the guard returns `false` (deny-by-default). Aligned with graphrefly-py `policy()`.\n *\n * @param build - Callback that registers `allow(...)` / `deny(...)` rules in order.\n * @returns A `NodeGuard` for use as `node({ guard })`.\n *\n * @example\n * ```ts\n * const guard = policy((allow, deny) => {\n * allow(\"observe\");\n * deny(\"write\", { where: (a) => a.type === \"llm\" });\n * });\n * ```\n */\nexport function policy(build: (allow: PolicyAllow, deny: PolicyDeny) => void): NodeGuard {\n\tconst rules: Rule[] = [];\n\tconst allow: PolicyAllow = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"allow\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tconst deny: PolicyDeny = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"deny\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tbuild(allow, deny);\n\treturn (actor, action) => {\n\t\tlet denied = false;\n\t\tlet allowed = false;\n\t\tfor (const r of rules) {\n\t\t\tif (!matchesActions(r.actions, action)) continue;\n\t\t\tif (!r.where(actor)) continue;\n\t\t\tif (r.kind === \"deny\") {\n\t\t\t\tdenied = true;\n\t\t\t} else {\n\t\t\t\tallowed = true;\n\t\t\t}\n\t\t}\n\t\tif (denied) return false;\n\t\treturn allowed;\n\t};\n}\n\n/**\n * Rebuild a declarative guard from persisted policy data (snapshot-safe).\n *\n * Rules are deny-overrides, same semantics as {@link policy}.\n */\nexport function policyFromRules(rules: readonly PolicyRuleData[]): NodeGuard {\n\treturn policy((allow, deny) => {\n\t\tfor (const rule of rules) {\n\t\t\tconst actorTypes =\n\t\t\t\trule.actorType == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);\n\t\t\tconst actorIds =\n\t\t\t\trule.actorId == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);\n\t\t\tconst claimEntries = Object.entries(rule.claims ?? {});\n\t\t\tconst where: Where = (actor) => {\n\t\t\t\tif (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;\n\t\t\t\tif (actorIds !== null && !actorIds.has(String(actor.id ?? \"\"))) return false;\n\t\t\t\tfor (const [key, value] of claimEntries) {\n\t\t\t\t\tif ((actor as Record<string, unknown>)[key] !== value) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tif (rule.effect === \"deny\") {\n\t\t\t\tdeny(rule.action, { where });\n\t\t\t} else {\n\t\t\t\tallow(rule.action, { where });\n\t\t\t}\n\t\t}\n\t});\n}\n\nconst STANDARD_WRITE_TYPES = [\"human\", \"llm\", \"wallet\", \"system\"] as const;\n\n/**\n * Derives a best-effort `meta.access` hint string by probing `guard` with the\n * standard actor types `human`, `llm`, `wallet`, `system` for the `\"write\"` action\n * (roadmap 1.5). Aligned with graphrefly-py `access_hint_for_guard`.\n *\n * @param guard - Guard function to probe (typically from {@link policy}).\n * @returns `\"restricted\"` when no standard type is allowed; `\"both\"` when both\n * `human` and `llm` are allowed (plus optionally `system`); the single allowed\n * type name when only one passes; or a `\"+\"` joined list otherwise.\n *\n * @example\n * ```ts\n * import { policy, accessHintForGuard } from \"@graphrefly/graphrefly-ts\";\n *\n * const guardBoth = policy((allow) => { allow(\"write\"); });\n * accessHintForGuard(guardBoth); // \"both\"\n *\n * const guardHuman = policy((allow) => {\n * allow(\"write\", { where: (a) => a.type === \"human\" });\n * });\n * accessHintForGuard(guardHuman); // \"human\"\n * ```\n */\nexport function accessHintForGuard(guard: NodeGuard): string {\n\tconst allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: \"\" }, \"write\"));\n\tif (allowed.length === 0) return \"restricted\";\n\tif (\n\t\tallowed.includes(\"human\") &&\n\t\tallowed.includes(\"llm\") &&\n\t\tallowed.every((t) => t === \"human\" || t === \"llm\" || t === \"system\")\n\t) {\n\t\treturn \"both\";\n\t}\n\tif (allowed.length === 1) return allowed[0];\n\treturn allowed.join(\"+\");\n}\n","/**\n * 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 { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\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/**\n * Internal sentinel value: \"no cached value has been set or emitted.\"\n * Used instead of `undefined` so that `undefined` can be a valid emitted value.\n */\nexport const NO_VALUE: unique symbol = Symbol.for(\"graphrefly/NO_VALUE\");\n\n/**\n * Branded symbol that marks a {@link CleanupResult} wrapper.\n * Used internally by {@link cleanupResult} — prevents duck-type collisions\n * with domain objects that happen to have a `cleanup` property.\n */\nexport const CLEANUP_RESULT: unique symbol = Symbol.for(\"graphrefly/CLEANUP_RESULT\");\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\n/**\n * Explicit cleanup wrapper. When a node fn returns `{ cleanup, value? }`,\n * `cleanup` is registered as the teardown/recompute cleanup and `value`\n * (if present) is emitted as data. This avoids the ambiguity where returning\n * a plain function is silently consumed as cleanup instead of emitted as data.\n *\n * Use the {@link cleanupResult} factory to create instances — it stamps the\n * branded {@link CLEANUP_RESULT} symbol so that domain objects with a `cleanup`\n * property are never misinterpreted.\n *\n * Plain function returns are still treated as cleanup for backward compatibility.\n */\nexport type CleanupResult<T = unknown> = {\n\treadonly [CLEANUP_RESULT]: true;\n\tcleanup: () => void;\n\tvalue?: T;\n};\n\n/**\n * Create a branded {@link CleanupResult}.\n *\n * ```ts\n * node([dep], () => cleanupResult(() => release(), computedValue))\n * ```\n */\nexport function cleanupResult<T>(cleanup: () => void): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, value: T): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, ...args: [] | [T]): CleanupResult<T> {\n\tconst r: CleanupResult<T> = { [CLEANUP_RESULT]: true, cleanup };\n\tif (args.length > 0) r.value = args[0];\n\treturn r;\n}\n\nconst isCleanupResult = (value: unknown): value is CleanupResult =>\n\ttypeof value === \"object\" && value !== null && CLEANUP_RESULT in 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 | typeof NO_VALUE;\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_boundDownToSinks: (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 = \"initial\" in opts ? (opts.initial as T) : NO_VALUE;\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 === NO_VALUE ? undefined : this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\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._downAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tself._upInternal(messages);\n\t\t\t},\n\t\t};\n\n\t\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._boundDownToSinks = this._downToSinks.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(\n\t\t\tlevel,\n\t\t\tthis._cached === NO_VALUE ? undefined : this._cached,\n\t\t\t{\n\t\t\t\tid: opts?.id,\n\t\t\t\thash: this._hashFn,\n\t\t\t},\n\t\t);\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\tget(): T | undefined {\n\t\treturn this._cached === NO_VALUE ? undefined : this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._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\tdownWithBatch(this._boundDownToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tdownWithBatch(this._boundDownToSinks, sinkMessages);\n\t}\n\n\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._cached = NO_VALUE;\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_downToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others mid-iteration.\n\t\t// Iterating the live Set would skip not-yet-visited sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\t_handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (m.length < 2) {\n\t\t\t\t\t// GRAPHREFLY-SPEC §1.2: bare [DATA] without payload is a protocol violation.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\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 = NO_VALUE;\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 = NO_VALUE;\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_downAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\t// §2.5: equals() only compares two real values. NO_VALUE sentinel means\n\t\t// \"never emitted / cache cleared\" — first emission always treated as changed.\n\t\tlet unchanged: boolean;\n\t\ttry {\n\t\t\tunchanged = this._cached !== NO_VALUE && this._equals(this._cached, value);\n\t\t} catch (eqErr) {\n\t\t\tconst eqMsg = eqErr instanceof Error ? eqErr.message : String(eqErr);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": equals threw: ${eqMsg}`, { cause: eqErr });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\treturn;\n\t\t}\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\t// _handleLocalLifecycle (called by _downInternal) sets _cached from the DATA payload.\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\t// Explicit cleanup wrapper: { cleanup, value? }\n\t\t\tif (isCleanupResult(out)) {\n\t\t\t\tthis._cleanup = out.cleanup;\n\t\t\t\tif (this._manualEmitUsed) return;\n\t\t\t\tif (\"value\" in out) {\n\t\t\t\t\tthis._downAutoValue(out.value);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Legacy: plain function return → cleanup (backward compat)\n\t\t\tif (isCleanupFn(out)) {\n\t\t\t\tthis._cleanup = out;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this._manualEmitUsed) return;\n\t\t\tif (out === undefined) return;\n\t\t\tthis._downAutoValue(out);\n\t\t} catch (err) {\n\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, { cause: err });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t}\n\t}\n\n\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\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\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 * **`equals` and mutable values:** The default `Object.is` identity check is\n * correct for the common immutable-value case. If your node produces mutable\n * objects (e.g. arrays or maps mutated in place), provide a custom `equals`\n * function — otherwise `Object.is` will always return `true` for the same\n * reference and the node will emit `RESOLVED` instead of `DATA`.\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 * bridge — graph-visible message forwarding between two nodes.\n *\n * Replaces ad-hoc `subscribe()` bridges that bypass graph topology.\n * The returned node is an effect that intercepts messages from `from`\n * and forwards them to `to.down()`. Register it with `graph.add()` to\n * make the bridge visible in `describe()` and `snapshot()`.\n *\n * **Upstream path:** The bridge node has `from` as its dep, so anything\n * downstream of the bridge that calls `up()` naturally reaches `from`.\n * If `to` is used as a dep by other nodes and those nodes send `up()`,\n * the messages reach `to`'s deps (not `from`). For full upstream relay\n * across the bridge boundary, wire the bridge as a dep of `to`'s\n * consumers or use `graph.connect()`.\n *\n * **ABAC / guards:** `to.down()` is called without `NodeTransportOptions`,\n * so any ABAC guard on `to` receives `actor = undefined`. Upstream (`up()`)\n * messages propagate through the dep chain the same way — no actor is\n * injected on either path. Both paths are intentionally unguarded; if `to`\n * requires a specific actor, provide a guarded wrapper node and bridge to\n * that instead.\n *\n * **Default forwarding:** All standard message types are forwarded by\n * default, including TEARDOWN, PAUSE, RESUME, and INVALIDATE. Use the\n * `down` option to restrict which types are forwarded. Callers that need\n * to exclude TEARDOWN (e.g. inter-stage wiring in `funnel()`) pass an\n * explicit `down` array without TEARDOWN.\n *\n * @module\n */\n\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport { type Node, type NodeActions, node, type OnMessageHandler } from \"./node.js\";\n\n/** Options for {@link bridge}. */\nexport type BridgeOptions = {\n\t/** Node name (for graph registration / describe). */\n\tname?: string;\n\t/**\n\t * Standard message types to forward downstream. Default: all standard\n\t * types. Unknown (non-standard) types always forward per spec §1.3.6\n\t * regardless of this option.\n\t */\n\tdown?: readonly symbol[];\n};\n\n/** All standard types forwarded by default. Export for callers that\n * need to customize (e.g. exclude TEARDOWN). */\nexport const DEFAULT_DOWN: readonly symbol[] = [\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tCOMPLETE,\n\tERROR,\n\tTEARDOWN,\n\tPAUSE,\n\tRESUME,\n\tINVALIDATE,\n];\n\n/**\n * All standard message types the bridge understands. Types outside this set\n * are \"unknown\" and must always be forwarded (spec §1.3.6).\n */\nconst STANDARD_TYPES = new Set<symbol>([\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tCOMPLETE,\n\tERROR,\n\tTEARDOWN,\n\tPAUSE,\n\tRESUME,\n\tINVALIDATE,\n]);\n\n/**\n * Create a graph-visible bridge node that forwards messages from `from` to `to`.\n *\n * The bridge is a real node (effect) — it shows up in `describe()`, participates\n * in two-phase push, and cleans up on TEARDOWN. Register it via `graph.add()`\n * to make it part of the graph topology.\n *\n * **Unknown message types** (custom domain signals not in the standard protocol\n * set) are always forwarded to `to`, regardless of the `down` option. This\n * satisfies spec §1.3.6 (\"unknown types forward unchanged\").\n *\n * **COMPLETE / ERROR**: when forwarded, the bridge also transitions to terminal\n * state so graph-wide completion detection works correctly.\n *\n * @param from - Source node to observe.\n * @param to - Target node to forward messages to via `to.down()`.\n * @param opts - Optional configuration.\n * @returns A bridge effect node. Add it to a graph with `graph.add(name, bridge(...))`.\n *\n * @example\n * ```ts\n * import { bridge, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(0);\n * const b = state(0);\n * const br = bridge(a, b, { name: \"__bridge_a_b\" });\n * graph.add(\"__bridge_a_b\", br);\n * // Now a's messages flow to b, visible in describe()\n * ```\n *\n * @category core\n */\nexport function bridge<T = unknown>(from: Node<T>, to: Node, opts?: BridgeOptions): Node<unknown> {\n\tconst allowedDown = new Set(opts?.down ?? DEFAULT_DOWN);\n\n\tconst onMessage: OnMessageHandler = (\n\t\tmsg: Message,\n\t\t_depIndex: number,\n\t\t_actions: NodeActions,\n\t): boolean => {\n\t\tconst type = msg[0];\n\n\t\t// Unknown types (custom domain signals) always forward — spec §1.3.6.\n\t\tif (!STANDARD_TYPES.has(type)) {\n\t\t\tto.down([msg]);\n\t\t\treturn true;\n\t\t}\n\n\t\t// Terminal types: always transition the bridge to terminal state\n\t\t// (return false → default dispatch). Only forward to `to` if allowed.\n\t\tif (type === COMPLETE || type === ERROR) {\n\t\t\tif (allowedDown.has(type)) {\n\t\t\t\tto.down([msg]);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Known type, not in allowedDown — consume without forwarding.\n\t\tif (!allowedDown.has(type)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Forward the message to the target.\n\t\tto.down([msg]);\n\t\treturn true;\n\t};\n\n\treturn node([from as Node], undefined, {\n\t\tname: opts?.name,\n\t\tdescribeKind: \"effect\",\n\t\tonMessage,\n\t\tmeta: { _internal: true },\n\t});\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 { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport {\n\tnode as createNode,\n\tNO_VALUE,\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 _boundDownToSinks: (messages: Messages) => void;\n\n\t// Mutable state\n\tprivate _cached: T | typeof NO_VALUE = NO_VALUE;\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._downAutoValue(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._boundDownToSinks = this._downToSinks.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 === NO_VALUE ? undefined : this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._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\tdownWithBatch(this._boundDownToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tdownWithBatch(this._boundDownToSinks, sinkMessages);\n\t}\n\n\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._cached = NO_VALUE;\n\t\t\tthis._status = \"disconnected\";\n\t\t\tthis._onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\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 _downToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\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 = NO_VALUE;\n\t\t\t\tthis._status = \"dirty\";\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tthis._status = \"settled\";\n\t\t\t} else if (t === RESOLVED) {\n\t\t\t\tthis._status = \"resolved\";\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 = NO_VALUE;\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 _downAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tlet unchanged: boolean;\n\t\ttry {\n\t\t\tunchanged = this._cached !== NO_VALUE && this._equals(this._cached, value);\n\t\t} catch (eqErr) {\n\t\t\tconst eqMsg = eqErr instanceof Error ? eqErr.message : String(eqErr);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": equals threw: ${eqMsg}`, { cause: eqErr });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\treturn;\n\t\t}\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._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._downAutoValue(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\tdownWithBatch(this._boundDownToSinks, [[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\tdownWithBatch(this._boundDownToSinks, [[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 type { Actor } from \"./actor.js\";\nimport { 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\t/** Guard info (full detail). */\n\tguard?: string;\n\t/** Last mutation attribution (full detail). */\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n};\n\n/**\n * Detail level for `describe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — type + deps only (default). LLM-friendly.\n * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`).\n * - `\"full\"` — standard + guard, lastMutation.\n */\nexport type DescribeDetail = \"minimal\" | \"standard\" | \"full\";\n\n/**\n * Valid field names for `describe({ fields: [...] })` (Phase 3.3b).\n * Dotted paths like `\"meta.label\"` select specific meta keys.\n */\nexport type DescribeField =\n\t| \"type\"\n\t| \"status\"\n\t| \"value\"\n\t| \"deps\"\n\t| \"meta\"\n\t| \"v\"\n\t| \"guard\"\n\t| \"lastMutation\"\n\t| `meta.${string}`;\n\n/** Resolve which fields to include based on detail level or explicit field list. */\nexport function resolveDescribeFields(\n\tdetail?: DescribeDetail,\n\tfields?: readonly DescribeField[],\n): Set<string> | null {\n\t// Explicit fields override detail level\n\tif (fields != null && fields.length > 0) return new Set(fields);\n\tswitch (detail) {\n\t\tcase \"standard\":\n\t\t\treturn new Set([\"type\", \"status\", \"value\", \"deps\", \"meta\", \"v\"]);\n\t\tcase \"full\":\n\t\t\treturn null; // null = include everything\n\t\tdefault:\n\t\t\treturn new Set([\"type\", \"deps\"]);\n\t}\n}\n\nfunction inferDescribeType(n: NodeImpl): DescribeNodeOutput[\"type\"] {\n\tif (n._describeKind != null) return n._describeKind;\n\tif (!n._hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\tif (n._fn == null) return \"derived\";\n\tif (n._manualEmitUsed) return \"operator\";\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON (GRAPHREFLY-SPEC §2.3, §3.6).\n *\n * @remarks\n * Values come from {@link Node.get}, which returns the **last settled** cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status` when\n * freshness matters. Avoid calling mid-batch for the same reason.\n *\n * Meta nodes are **not** terminated when their parent receives COMPLETE or\n * ERROR — they remain writable so callers can record post-mortem metadata\n * (e.g. `meta.error`). They *are* torn down when the parent receives TEARDOWN.\n *\n * @param node - The node whose meta fields to snapshot.\n * @returns Plain object of `{ key: value }` pairs (empty if no meta defined).\n * Keys whose companion node's {@link Node.get} throws are omitted.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = core.node({ initial: 0, meta: { tag: \"a\" } });\n * core.metaSnapshot(n); // { tag: \"a\" }\n * ```\n */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.get();\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta` snapshot).\n * Parity with graphrefly-py `describe_node`.\n *\n * `type` is inferred from factory configuration, optional `describeKind` in node options,\n * and the last `manualEmitUsed` hint (operator vs derived). {@link effect} sets\n * `describeKind: \"effect\"`. Nodes not created by {@link node} fall back to `type: \"state\"` and empty `deps`.\n *\n * @param node - Any `Node` to introspect.\n * @returns `DescribeNodeOutput` suitable for merging into graph describe maps.\n *\n * @example\n * ```ts\n * import { describeNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * describeNode(state(0));\n * ```\n */\n/**\n * Builds a single-node slice for `Graph.describe()`.\n *\n * @param node - Node to introspect.\n * @param includeFields - Set of fields to include, or `null` for all. When omitted, all fields are included (legacy behavior).\n */\nexport function describeNode(node: Node, includeFields?: Set<string> | null): DescribeNodeOutput {\n\tconst all = includeFields == null; // null or undefined → include everything\n\n\t// Specific meta keys requested via dotted paths (e.g. \"meta.label\")\n\tconst metaKeys: string[] | null =\n\t\t!all && includeFields != null\n\t\t\t? [...includeFields].filter((f) => f.startsWith(\"meta.\")).map((f) => f.slice(5))\n\t\t\t: null;\n\tconst wantsMeta = all || includeFields!.has(\"meta\") || (metaKeys != null && metaKeys.length > 0);\n\n\tlet type: DescribeNodeOutput[\"type\"] = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.name ?? \"\");\n\t} else if (node instanceof DynamicNodeImpl) {\n\t\ttype = node._describeKind ?? \"derived\";\n\t\tdeps = [];\n\t}\n\n\tconst out: DescribeNodeOutput = { type, deps };\n\n\t// status\n\tif (all || includeFields!.has(\"status\")) {\n\t\tout.status = node.status;\n\t}\n\n\t// Resolve guard once — used by both meta.access hint and standalone guard field\n\tconst guard =\n\t\t(node instanceof NodeImpl && node._guard) ||\n\t\t(node instanceof DynamicNodeImpl && node._guard) ||\n\t\tundefined;\n\n\t// meta\n\tif (wantsMeta) {\n\t\tconst rawMeta: Record<string, unknown> = { ...metaSnapshot(node) };\n\t\tif (guard != null && rawMeta.access === undefined) {\n\t\t\trawMeta.access = accessHintForGuard(guard);\n\t\t}\n\n\t\tif (metaKeys != null && metaKeys.length > 0 && !includeFields!.has(\"meta\")) {\n\t\t\t// Only specific meta keys\n\t\t\tconst filtered: Record<string, unknown> = {};\n\t\t\tfor (const k of metaKeys) {\n\t\t\t\tif (k in rawMeta) filtered[k] = rawMeta[k];\n\t\t\t}\n\t\t\tout.meta = filtered;\n\t\t} else {\n\t\t\tout.meta = rawMeta;\n\t\t}\n\t}\n\n\t// name (always include when present — it's identity, not detail)\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\t// value\n\tif (all || includeFields!.has(\"value\")) {\n\t\ttry {\n\t\t\tout.value = node.get();\n\t\t} catch {\n\t\t\t/* omit value */\n\t\t}\n\t}\n\n\t// Versioning (GRAPHREFLY-SPEC §7)\n\tif ((all || includeFields!.has(\"v\")) && node.v != null) {\n\t\tconst vInfo: DescribeNodeOutput[\"v\"] = { id: node.v.id, version: node.v.version };\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo!.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo!.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\t// Guard info (full detail)\n\tif (all || includeFields!.has(\"guard\")) {\n\t\tif (guard != null) {\n\t\t\tout.guard = accessHintForGuard(guard);\n\t\t}\n\t}\n\n\t// Last mutation attribution (full detail)\n\tif (all || includeFields!.has(\"lastMutation\")) {\n\t\tif (node.lastMutation != null) {\n\t\t\tout.lastMutation = node.lastMutation;\n\t\t}\n\t}\n\n\treturn out;\n}\n","import { type Node, type NodeFn, type NodeOptions, node } from \"./node.js\";\n\n/**\n * Creates a manual source with no upstream deps. Emit values with {@link Node.down}.\n *\n * Spec: `state(initial, opts?)` is `node([], { initial, ...opts })` (GRAPHREFLY-SPEC §2.7).\n *\n * @param initial - Initial cached value. Because `initial` is provided, `equals` is\n * called on the first {@link Node.down | down()} emission — if the value matches\n * `initial`, the node emits `RESOLVED` instead of `DATA` (spec §2.5).\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n * @returns `Node<T>` - Stateful node you drive imperatively.\n *\n * @example\n * ```ts\n * import { DATA, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(0);\n * n.down([[DATA, 1]]);\n * ```\n *\n * @category core\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n/**\n * Creates a producer node with no deps; `fn` runs when the first subscriber connects.\n *\n * @param fn - Receives deps (empty) and {@link NodeActions}; use `emit` / `down` to push.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Producer node.\n *\n * @example\n * ```ts\n * import { producer } from \"@graphrefly/graphrefly-ts\";\n *\n * const tick = producer((_d, a) => {\n * a.emit(1);\n * });\n * ```\n *\n * @category core\n */\nexport function producer<T = unknown>(fn: NodeFn<T>, opts?: NodeOptions): Node<T> {\n\treturn node<T>(fn, { describeKind: \"producer\", ...opts });\n}\n\n/**\n * Creates a derived node from dependencies and a compute function (same primitive as operators).\n *\n * @param deps - Upstream nodes.\n * @param fn - Compute function; return value is emitted, or use `actions` explicitly.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Derived node.\n *\n * @example\n * ```ts\n * import { derived, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n *\n * @category core\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: NodeFn<T>,\n\topts?: NodeOptions,\n): Node<T> {\n\treturn node<T>(deps, fn, { describeKind: \"derived\", ...opts });\n}\n\n/**\n * Runs a side-effect when deps settle; return value is not auto-emitted.\n *\n * @param deps - Nodes to watch.\n * @param fn - Side-effect body.\n * @returns `Node<unknown>` - Effect node.\n *\n * @example\n * ```ts\n * import { effect, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(1);\n * effect([n], ([v]) => {\n * console.log(v);\n * });\n * ```\n *\n * @category core\n */\nexport function effect(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","/**\n * Creates a resettable deadline timer for internal timeout, retry, and rate-limiting use.\n *\n * @remarks **Centralised primitive:** wraps `setTimeout`/`clearTimeout` with a generation guard\n * so that stale callbacks never fire after `cancel()` or a new `start()`.\n *\n * @remarks **Spec §5.10 exception:** resilience operators (`timeout`, `retry`, `rateLimiter`)\n * need raw timers — `fromTimer` creates a new Node per reset, which is too heavy here.\n *\n * @example\n * ```ts\n * import { ResettableTimer } from \"@graphrefly/graphrefly-ts\";\n *\n * const timer = new ResettableTimer();\n * timer.start(1000, () => console.log(\"fired\"));\n * timer.cancel(); // cancels before firing\n * timer.start(500, () => console.log(\"new deadline\"));\n * console.log(timer.pending); // true\n * ```\n *\n * @category core\n */\nexport class ResettableTimer {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _gen = 0;\n\n\t/** Schedule callback after delayMs. Cancels any pending timer. */\n\tstart(delayMs: number, callback: () => void): void {\n\t\tthis.cancel();\n\t\tthis._gen += 1;\n\t\tconst gen = this._gen;\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tif (gen !== this._gen) return;\n\t\t\tcallback();\n\t\t}, delayMs);\n\t}\n\n\t/** Cancel the pending timer (if any). */\n\tcancel(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\t/** Whether a timer is currently pending. */\n\tget pending(): boolean {\n\t\treturn this._timer !== undefined;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAM,SAAiB,UAA4B;AAClD,SAAK,OAAO;AACZ,SAAK,QAAQ;AACb,UAAM,MAAM,KAAK;AACjB,SAAK,SAAS,WAAW,MAAM;AAC9B,WAAK,SAAS;AACd,UAAI,QAAQ,KAAK,KAAM;AACvB,eAAS;AAAA,IACV,GAAG,OAAO;AAAA,EACX;AAAA;AAAA,EAGA,SAAe;AACd,QAAI,KAAK,WAAW,QAAW;AAC9B,mBAAa,KAAK,MAAM;AACxB,WAAK,SAAS;AAAA,IACf;AAAA,EACD;AAAA;AAAA,EAGA,IAAI,UAAmB;AACtB,WAAO,KAAK,WAAW;AAAA,EACxB;AACD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/index.ts","../../src/core/actor.ts","../../src/core/messages.ts","../../src/core/batch.ts","../../src/core/guard.ts","../../src/core/clock.ts","../../src/core/versioning.ts","../../src/core/node-base.ts","../../src/core/node.ts","../../src/core/bridge.ts","../../src/core/dynamic-node.ts","../../src/core/meta.ts","../../src/core/sugar.ts","../../src/core/timer.ts"],"sourcesContent":["/**\n * Core layer: message protocol, node primitive, lifecycle (Phase 0).\n */\nexport * from \"./actor.js\";\nexport * from \"./batch.js\";\nexport { type BridgeOptions, bridge, DEFAULT_DOWN } from \"./bridge.js\";\nexport { monotonicNs, wallClockNs } from \"./clock.js\";\nexport * from \"./dynamic-node.js\";\nexport * from \"./guard.js\";\nexport * from \"./messages.js\";\nexport {\n\ttype DescribeDetail,\n\ttype DescribeField,\n\ttype DescribeNodeOutput,\n\tresolveDescribeFields,\n} from \"./meta.js\";\nexport {\n\tCLEANUP_RESULT,\n\ttype CleanupResult,\n\tcleanupResult,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeFn,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\tnode,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node.js\";\nexport * from \"./sugar.js\";\nexport { ResettableTimer } from \"./timer.js\";\nexport {\n\tadvanceVersion,\n\tcreateVersioning,\n\tdefaultHash,\n\ttype HashFn,\n\tisV1,\n\ttype NodeVersionInfo,\n\ttype V0,\n\ttype V1,\n\ttype VersioningLevel,\n\ttype VersioningOptions,\n} from \"./versioning.js\";\n","/**\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 * GraphReFly message protocol — §1 `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n * Emissions are always `[[Type, Data?], ...]` (no single-tuple shorthand).\n *\n * ## Canonical message ordering (within a composite batch)\n *\n * When multiple message types appear in a single `down()` call, the canonical\n * delivery order is determined by **signal tier**:\n *\n * | Tier | Signals | Role | Batch behavior |\n * |------|------------------------|-------------------|-------------------------------------|\n * | 0 | START | Subscribe handshake | Immediate (never deferred) |\n * | 1 | DIRTY, INVALIDATE | Notification | Immediate (never deferred) |\n * | 2 | PAUSE, RESUME | Flow control | Immediate (never deferred) |\n * | 3 | DATA, RESOLVED | Value settlement | Deferred inside `batch()` |\n * | 4 | COMPLETE, ERROR | Terminal lifecycle | Deferred to after phase-2 |\n * | 5 | TEARDOWN | Destruction | Immediate (usually sent alone) |\n *\n * **Rule:** Within `downWithBatch`, messages are partitioned by tier and delivered\n * in tier order. This ensures phase-2 values (DATA/RESOLVED) reach sinks before\n * terminal signals (COMPLETE/ERROR) mark the node as done, preventing the\n * \"COMPLETE-before-DATA\" class of bugs. Sources that emit in canonical order\n * naturally partition correctly with zero overhead.\n *\n * Unknown message types (forward-compat) are tier 1 (immediate).\n *\n * ## Meta node bypass rules (centralized — GRAPHREFLY-SPEC §2.3)\n *\n * - **INVALIDATE** via `graph.signal()` — no-op on meta nodes (cached values preserved).\n * - **COMPLETE / ERROR** — not propagated from parent to meta (meta outlives terminal\n * state for post-mortem writes like setting `meta.error` after ERROR).\n * - **TEARDOWN** — propagated from parent to meta, releasing meta resources.\n */\n\n/**\n * Subscribe-time handshake (`START`). Delivered to each new sink at the top of\n * `subscribe()` — `[[START]]` for a SENTINEL (no cached value) node or\n * `[[START], [DATA, cached]]` for a node with a cached value.\n *\n * Semantics: \"upstream connected and ready to flow.\" A new sink receiving\n * `[[START]]` alone knows the upstream is alive but has no current value; a\n * sink receiving `[[START], [DATA, v]]` knows the upstream is ready\n * with value `v`. Absence of `START` before any other message means the\n * subscription was either never established or the node is terminal.\n *\n * Tier 0 — immediate, delivered before any DIRTY/DATA in the same batch.\n * Not forwarded through nodes — each node emits its own `START` to its own\n * new sinks.\n */\nexport const START = Symbol.for(\"graphrefly/START\");\n/** Value delivery (`DATA`, value). Tier 3 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 1 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 3 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 1 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 2 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 2 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 5 — immediate (usually sent alone). */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 4 — delivered after phase-2 in the same batch. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 4 — delivered after phase-2 in the same batch. */\nexport const ERROR = Symbol.for(\"graphrefly/ERROR\");\n\n/** Known protocol type symbols (open set — other symbols are valid and forward). */\nexport const knownMessageTypes: readonly symbol[] = [\n\tSTART,\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tINVALIDATE,\n\tPAUSE,\n\tRESUME,\n\tTEARDOWN,\n\tCOMPLETE,\n\tERROR,\n];\n\n/** O(1) lookup for {@link isKnownMessageType} and {@link isLocalOnly}. */\nconst knownMessageSet: ReadonlySet<symbol> = new Set(knownMessageTypes);\n\n/** One protocol tuple: `[Type, optional payload]`. */\nexport type Message = readonly [symbol, unknown?];\n\n/**\n * A batch of tuples — the wire shape for `node.down()` / `node.up()`.\n */\nexport type Messages = readonly Message[];\n\n/**\n * Whether `t` is one of the built-in protocol symbols in this module.\n *\n * @param t — Message type symbol (unknown types are still valid; they must forward).\n * @returns `true` for `DATA`, `DIRTY`, `RESOLVED`, etc.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, isKnownMessageType } from \"@graphrefly/graphrefly-ts\";\n *\n * isKnownMessageType(DATA); // true\n * isKnownMessageType(Symbol(\"custom\")); // false\n * ```\n */\nexport function isKnownMessageType(t: symbol): boolean {\n\treturn knownMessageSet.has(t);\n}\n\n/**\n * Returns the signal tier for a message type (see module-level ordering table).\n *\n * - 0: subscribe handshake (START) — immediate, first in canonical order\n * - 1: notification (DIRTY, INVALIDATE) — immediate\n * - 2: flow control (PAUSE, RESUME) — immediate\n * - 3: value (DATA, RESOLVED) — deferred inside `batch()`\n * - 4: terminal (COMPLETE, ERROR) — delivered after phase-3\n * - 5: destruction (TEARDOWN) — immediate, usually alone\n * - 1 for unknown types (forward-compat: immediate)\n *\n * @param t — Message type symbol.\n * @returns Tier number (0–5).\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, TEARDOWN, messageTier, START } from \"@graphrefly/graphrefly-ts\";\n *\n * messageTier(START); // 0\n * messageTier(DIRTY); // 1\n * messageTier(DATA); // 3\n * messageTier(COMPLETE); // 4\n * messageTier(TEARDOWN); // 5\n * ```\n */\nexport function messageTier(t: symbol): number {\n\tif (t === START) return 0;\n\tif (t === DIRTY || t === INVALIDATE) return 1;\n\tif (t === PAUSE || t === RESUME) return 2;\n\tif (t === DATA || t === RESOLVED) return 3;\n\tif (t === COMPLETE || t === ERROR) return 4;\n\tif (t === TEARDOWN) return 5;\n\treturn 1; // unknown → immediate (after START)\n}\n\n/**\n * Returns whether this tuple is deferred by `batch()` (phase 2: `DATA` or `RESOLVED`).\n *\n * @param msg — Single message tuple.\n * @returns `true` if `msg` is `DATA` or `RESOLVED`.\n *\n * @example\n * ```ts\n * import { DATA, RESOLVED, DIRTY, isPhase2Message } from \"@graphrefly/graphrefly-ts\";\n *\n * isPhase2Message([DATA, 42]); // true\n * isPhase2Message([RESOLVED]); // true\n * isPhase2Message([DIRTY]); // false\n * ```\n */\nexport function isPhase2Message(msg: Message): boolean {\n\tconst t = msg[0];\n\treturn t === DATA || t === RESOLVED;\n}\n\n/**\n * Returns whether this message type is terminal (COMPLETE or ERROR).\n * Terminal messages are delivered after phase-2 in the same batch to prevent\n * the node from becoming terminal before value messages reach sinks.\n *\n * @param t — Message type symbol.\n * @returns `true` for `COMPLETE` or `ERROR`.\n *\n * @example\n * ```ts\n * import { COMPLETE, ERROR, DATA, isTerminalMessage } from \"@graphrefly/graphrefly-ts\";\n *\n * isTerminalMessage(COMPLETE); // true\n * isTerminalMessage(ERROR); // true\n * isTerminalMessage(DATA); // false\n * ```\n */\nexport function isTerminalMessage(t: symbol): boolean {\n\treturn t === COMPLETE || t === ERROR;\n}\n\n/**\n * Whether `t` is a graph-local signal that should NOT cross a wire/transport\n * boundary (SSE, WebSocket, worker bridge, persistence sinks).\n *\n * Local-only signals (tier 0–2): START, DIRTY, INVALIDATE, PAUSE, RESUME.\n * These are internal to the reactive graph — subscribe handshakes,\n * notification phases, and flow control have no semantics for remote consumers.\n *\n * Wire-crossing signals (tier 3+): DATA, RESOLVED, COMPLETE, ERROR, TEARDOWN.\n * Unknown message types (spec §1.3.6 forward-compat) also cross the wire.\n *\n * Individual adapters may further opt-in to local signals for observability\n * (e.g. SSE `includeDirty`, `includeResolved` options). Storage/persistence\n * adapters that need INVALIDATE for remote cache-clear should explicitly\n * forward it despite `isLocalOnly(INVALIDATE) === true`. The default is to\n * skip all local-only signals at the boundary.\n *\n * @param t — Message type symbol.\n * @returns `true` if the message should be kept local (not sent over wire).\n *\n * @example\n * ```ts\n * import { START, DIRTY, DATA, COMPLETE, isLocalOnly } from \"@graphrefly/graphrefly-ts\";\n *\n * isLocalOnly(START); // true — subscribe handshake\n * isLocalOnly(DIRTY); // true — notification phase\n * isLocalOnly(RESOLVED); // false — value settlement crosses wire\n * isLocalOnly(DATA); // false — value crosses wire\n * isLocalOnly(COMPLETE); // false — terminal crosses wire\n * ```\n *\n * @category core\n */\nexport function isLocalOnly(t: symbol): boolean {\n\t// Unknown types always cross the wire (spec §1.3.6 forward-compat).\n\t// messageTier returns 1 for unknowns, but unknowns are NOT local-only.\n\tif (!knownMessageSet.has(t)) return false;\n\treturn messageTier(t) < 3;\n}\n\n/**\n * Whether `t` should be propagated from a parent node to its companion meta nodes.\n * Only TEARDOWN propagates; COMPLETE/ERROR/INVALIDATE do not (meta outlives parent\n * terminal state for post-mortem writes).\n *\n * @param t — Message type symbol.\n * @returns `true` if the signal should reach meta nodes.\n *\n * @example\n * ```ts\n * import { TEARDOWN, COMPLETE, ERROR, propagatesToMeta } from \"@graphrefly/graphrefly-ts\";\n *\n * propagatesToMeta(TEARDOWN); // true\n * propagatesToMeta(COMPLETE); // false\n * propagatesToMeta(ERROR); // false\n * ```\n */\nexport function propagatesToMeta(t: symbol): boolean {\n\treturn t === TEARDOWN;\n}\n","import {\n\tDATA,\n\tisPhase2Message,\n\tisTerminalMessage,\n\ttype Message,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n} from \"./messages.js\";\n\n/**\n * §1.3.7 — Inside a batch, DIRTY propagates immediately; DATA and RESOLVED are\n * deferred until the outermost `batch()` callback returns. Terminal signals\n * (COMPLETE, ERROR) are delivered after phase-2 messages in the same batch\n * (see canonical ordering in `messages.ts`).\n */\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\nconst pendingPhase2: Array<() => void> = [];\nconst pendingPhase3: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * deferred phase-2 work is draining.\n *\n * Matching Python's `is_batching()` semantics: nested emissions during drain\n * are deferred until the current drain pass completes, preventing ordering\n * bugs when callbacks trigger further DATA/RESOLVED.\n *\n * @returns `true` while inside `batch()` or while the drain loop is running.\n *\n * @example\n * ```ts\n * import { batch, isBatching } from \"@graphrefly/graphrefly-ts\";\n *\n * batch(() => {\n * console.log(isBatching()); // true\n * });\n * ```\n *\n * @category core\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral queue.\n * If `fn` throws (including from a nested `batch`), deferred DATA/RESOLVED for\n * that **outer** `batch` frame are discarded — phase-2 is not flushed after an\n * error. While the drain loop is running (`flushInProgress`), a nested `batch`\n * that throws must **not** clear the global queue (cross-language decision A4).\n *\n * During the drain loop, `isBatching()` remains true so nested `downWithBatch`\n * calls still defer phase-2 messages. The drain loop runs until the queue is\n * quiescent (no pending work remains). Per-emission try/catch ensures one\n * throwing callback does not orphan remaining emissions; the first error is\n * re-thrown after all emissions drain. Callbacks that ran before the throw may\n * have applied phase-2 — partial graph state is intentional (decision C1).\n *\n * @param fn — Synchronous work that may call `downWithBatch` / `node.down()`.\n * @returns `void` — all side-effects happen through `downWithBatch` and the\n * phase-2 drain that runs after `fn` returns.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.batch(() => {\n * core.downWithBatch(sink, [[core.DATA, 1]]);\n * });\n * ```\n *\n * @category core\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\t// Do not wipe the outer drain's queue (decision A4).\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) {\n\t\tflushInProgress = true;\n\t}\n\tconst errors: unknown[] = [];\n\ttry {\n\t\tlet iterations = 0;\n\t\t// Drain phase-2 first, then phase-3. If phase-3 callbacks enqueue new\n\t\t// phase-2 work, the outer loop catches it and drains phase-2 again\n\t\t// before re-entering phase-3.\n\t\twhile (pendingPhase2.length > 0 || pendingPhase3.length > 0) {\n\t\t\t// Phase-2 (DATA/RESOLVED) — parent node values settle here.\n\t\t\twhile (pendingPhase2.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase2.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Phase-3 — meta companion emissions that must follow parent settlement.\n\t\t\tif (pendingPhase3.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase3.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) {\n\t\t\tflushInProgress = false;\n\t\t}\n\t}\n\tif (errors.length === 1) {\n\t\tthrow errors[0];\n\t}\n\tif (errors.length > 1) {\n\t\tthrow new AggregateError(errors, \"batch drain: multiple callbacks threw\");\n\t}\n}\n\n/**\n * Splits a message array into three groups by signal tier (see `messages.ts`):\n *\n * - **immediate** — tier 0–2, 5: START, DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN, unknown\n * - **deferred** — tier 3: DATA, RESOLVED (phase-2, deferred inside `batch()`)\n * - **terminal** — tier 4: COMPLETE, ERROR (delivered after phase-2)\n *\n * Order within each group is preserved.\n *\n * @param messages — One `down()` payload.\n * @returns Three groups in canonical delivery order.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, partitionForBatch } from \"@graphrefly/graphrefly-ts\";\n *\n * partitionForBatch([[DIRTY], [DATA, 1], [COMPLETE]]);\n * // { immediate: [[DIRTY]], deferred: [[DATA, 1]], terminal: [[COMPLETE]] }\n * ```\n *\n * @category core\n */\nexport function partitionForBatch(messages: Messages): {\n\timmediate: Messages;\n\tdeferred: Messages;\n\tterminal: Messages;\n} {\n\tconst immediate: Message[] = [];\n\tconst deferred: Message[] = [];\n\tconst terminal: Message[] = [];\n\tfor (const m of messages) {\n\t\tif (isPhase2Message(m)) {\n\t\t\tdeferred.push(m);\n\t\t} else if (isTerminalMessage(m[0])) {\n\t\t\tterminal.push(m);\n\t\t} else {\n\t\t\timmediate.push(m);\n\t\t}\n\t}\n\treturn { immediate, deferred, terminal };\n}\n\n/**\n * Delivers messages downstream through `sink`, applying batch semantics and\n * canonical tier-based ordering (see `messages.ts`):\n *\n * 1. **Immediate** (tier 0–2, 5): START, DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN,\n * unknown — delivered synchronously.\n * 2. **Phase-2** (tier 3): DATA, RESOLVED — deferred while `isBatching()`.\n * 3. **Terminal** (tier 4): COMPLETE, ERROR — always delivered after phase-2.\n * When batching, terminal is queued after deferred phase-2 in the pending list.\n * When not batching, terminal is delivered after phase-2 synchronously.\n *\n * This ordering prevents the \"COMPLETE-before-DATA\" class of bugs: terminal\n * signals never make a node terminal before phase-2 values reach sinks,\n * regardless of how the source assembled the message array.\n *\n * @param sink — Sink callback. May be called up to three times per invocation\n * (immediate, deferred, terminal) when not batching.\n * @param messages — Full `[[Type, Data?], ...]` array for one downstream delivery.\n * @param phase — Starting delivery phase (`2` = data, `3` = terminal). Default `2`.\n * @param options - Optional configuration.\n * @option strategy | `\"partition\"` or `\"sequential\"` | `\"partition\"` | `\"partition\"` groups by tier; `\"sequential\"` preserves message order within each tier using `messageTier()` classification.\n * @returns `void` — delivery is performed through `sink` callbacks, synchronously\n * or deferred into the active batch queue.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.downWithBatch((msgs) => console.log(msgs), [[core.DIRTY], [core.DATA, 42]]);\n * ```\n *\n * @category core\n */\n/** Delivery strategy for {@link downWithBatch}. Mirrors Python `DownStrategy`. */\nexport type DownStrategy = \"partition\" | \"sequential\";\n\nexport function downWithBatch(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n\toptions?: { strategy?: DownStrategy },\n): void {\n\tif (messages.length === 0) {\n\t\treturn;\n\t}\n\n\tif (options?.strategy === \"sequential\") {\n\t\t_downSequential(sink, messages, phase);\n\t\treturn;\n\t}\n\n\tconst queue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\n\t// Fast path: single-message batches (most common in graph-internal propagation)\n\t// skip partitionForBatch allocation entirely.\n\tif (messages.length === 1) {\n\t\tconst t = messages[0][0];\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else if (isTerminalMessage(t)) {\n\t\t\t// Terminal single message: defer when batching so any preceding\n\t\t\t// phase-2 in the queue flushes first.\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate: deliver synchronously.\n\t\t\tsink(messages);\n\t\t}\n\t\treturn;\n\t}\n\t// Multi-message: three-way partition by tier.\n\tconst { immediate, deferred, terminal } = partitionForBatch(messages);\n\n\t// 1. Immediate signals (tier 0–2, 5) — deliver synchronously now.\n\tif (immediate.length > 0) {\n\t\tsink(immediate);\n\t}\n\n\t// 2. Deferred (tier 3) + Terminal (tier 4) — canonical order preserved.\n\tif (isBatching()) {\n\t\tif (deferred.length > 0) {\n\t\t\tqueue.push(() => sink(deferred));\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tqueue.push(() => sink(terminal));\n\t\t}\n\t} else {\n\t\tif (deferred.length > 0) {\n\t\t\tsink(deferred);\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tsink(terminal);\n\t\t}\n\t}\n}\n\n/**\n * Sequential strategy: walk messages one at a time. Phase-2 (DATA/RESOLVED) and\n * terminal (COMPLETE/ERROR) messages are deferred while batching; immediate\n * messages deliver synchronously. Matches graphrefly-py `_down_sequential`.\n *\n * Tier legend (after START introduction):\n * 0 = START — immediate, delivered before other tiers\n * 1 = DIRTY, INVALIDATE — immediate\n * 2 = PAUSE, RESUME — immediate\n * 3 = DATA, RESOLVED — deferred inside batch\n * 4 = COMPLETE, ERROR — deferred to phase-3 queue (drains after data)\n * 5 = TEARDOWN — deferred to phase-3 queue (drains after data)\n */\nfunction _downSequential(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n): void {\n\tconst dataQueue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\tfor (const msg of messages) {\n\t\tconst tier = messageTier(msg[0]);\n\t\tif (tier === 3) {\n\t\t\t// Phase-2 (DATA/RESOLVED): defer while batching.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tdataQueue.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else if (tier >= 4) {\n\t\t\t// Terminal + destruction (COMPLETE/ERROR/TEARDOWN): always route to\n\t\t\t// phase-3 queue — terminals and teardown must drain after all phase-2\n\t\t\t// work to prevent premature termination or early resource release.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tpendingPhase3.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate (START, DIRTY, INVALIDATE, PAUSE, RESUME):\n\t\t\t// deliver synchronously.\n\t\t\tsink([msg]);\n\t\t}\n\t}\n}\n","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 * 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","/**\n * Node versioning — GRAPHREFLY-SPEC §7.\n *\n * Progressive, optional versioning for node identity and change tracking.\n *\n * - **V0**: `id` + `version` — identity & change detection (~16 bytes overhead)\n * - **V1**: + `cid` + `prev` — content addressing & linked history (~60 bytes overhead)\n *\n * **Lifecycle notes:**\n * - Version advances only on DATA (not RESOLVED, INVALIDATE, or TEARDOWN).\n * - `resetOnTeardown` clears the cached value but does NOT reset versioning state.\n * After teardown, `v.cid` still reflects the last DATA value, not the cleared cache.\n * The invariant `hash(node.get()) === v.cid` only holds in `settled`/`resolved` status.\n * - Resubscribable nodes preserve versioning across subscription lifetimes (monotonic counter).\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** V0: identity + monotonic version counter. */\nexport type V0 = {\n\treadonly id: string;\n\tversion: number;\n};\n\n/** V1: V0 + content-addressed identifier + previous cid link. */\nexport type V1 = V0 & {\n\tcid: string;\n\tprev: string | null;\n};\n\n/** Union of all versioning info shapes. */\nexport type NodeVersionInfo = V0 | V1;\n\n/** Supported versioning levels (extensible to 2, 3 later). */\nexport type VersioningLevel = 0 | 1;\n\n/** Function that hashes a value to a hex string (for V1 cid). */\nexport type HashFn = (value: unknown) => string;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface VersioningOptions {\n\t/** Override auto-generated id. */\n\tid?: string;\n\t/** Custom hash function for V1 cid (default: SHA-256 truncated to 16 hex chars). */\n\thash?: HashFn;\n}\n\n// ---------------------------------------------------------------------------\n// Default hash\n// ---------------------------------------------------------------------------\n\n/**\n * Canonicalize a value for deterministic cross-language hashing.\n *\n * - Integer-valued floats normalize to integer strings (`1.0` → `1`).\n * - `NaN`, `Infinity`, `-Infinity` are rejected (no JSON equivalent).\n * - `undefined` normalizes to `null`.\n * - Object keys are sorted lexicographically.\n *\n * This ensures TS `JSON.stringify` and Python `json.dumps(sort_keys=True)`\n * produce identical output for the same logical value.\n */\nexport function canonicalizeForHash(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow new TypeError(`Cannot hash non-finite number: ${value}`);\n\t\t}\n\t\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. ` +\n\t\t\t\t\t\"Cross-language cid parity is not guaranteed for unsafe integers.\",\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\" || typeof value === \"boolean\" || value === null) {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalizeForHash);\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst sorted: Record<string, unknown> = {};\n\t\tfor (const k of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tsorted[k] = canonicalizeForHash((value as Record<string, unknown>)[k]);\n\t\t}\n\t\treturn sorted;\n\t}\n\t// Fallback: coerce to null (bigint, symbol, function)\n\treturn null;\n}\n\n/**\n * Default content hash: SHA-256 of deterministic JSON, truncated to 16 hex chars (~64-bit).\n * Uses {@link canonicalizeForHash} for cross-language parity with Python `default_hash`.\n */\nexport function defaultHash(value: unknown): string {\n\tconst canonical = canonicalizeForHash(value ?? null);\n\tconst json = JSON.stringify(canonical);\n\treturn createHash(\"sha256\").update(json).digest(\"hex\").slice(0, 16);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create initial versioning state for a node.\n *\n * @param level - 0 for V0, 1 for V1.\n * @param initialValue - The node's initial cached value (used for V1 cid).\n * @param opts - Optional overrides (id, hash).\n */\nexport function createVersioning(\n\tlevel: VersioningLevel,\n\tinitialValue: unknown,\n\topts?: VersioningOptions,\n): NodeVersionInfo {\n\tconst id = opts?.id ?? randomUUID();\n\tif (level === 0) {\n\t\treturn { id, version: 0 } satisfies V0;\n\t}\n\tconst hash = opts?.hash ?? defaultHash;\n\tconst cid = hash(initialValue);\n\treturn { id, version: 0, cid, prev: null } satisfies V1;\n}\n\n// ---------------------------------------------------------------------------\n// Advance\n// ---------------------------------------------------------------------------\n\n/**\n * Advance versioning state after a DATA emission (value changed).\n *\n * Mutates `info` in place for performance (called on every DATA).\n * Only call when the cached value has actually changed (not on RESOLVED).\n *\n * @param info - The node's current versioning state.\n * @param newValue - The new cached value.\n * @param hashFn - Hash function (only used for V1).\n */\nexport function advanceVersion(info: NodeVersionInfo, newValue: unknown, hashFn: HashFn): void {\n\tinfo.version += 1;\n\tif (\"cid\" in info) {\n\t\t(info as V1).prev = (info as V1).cid;\n\t\t(info as V1).cid = hashFn(newValue);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this V1 versioning info? */\nexport function isV1(info: NodeVersionInfo): info is V1 {\n\treturn \"cid\" in info;\n}\n","/**\n * `NodeBase` — abstract class implementing the {@link Node} protocol with\n * lifecycle machinery shared between {@link NodeImpl} (static deps) and\n * {@link DynamicNodeImpl} (runtime-tracked deps).\n *\n * **Responsibilities (shared):**\n * - Identity (name, describeKind, meta, guard, versioning)\n * - Cache + status lifecycle (`_cached`, `_status`, `_terminal`)\n * - Sink storage (null / single / Set fast paths)\n * - `subscribe()` with START handshake + first-subscriber activation\n * - `_downInternal` → `_downToSinks` delivery pipeline (via `downWithBatch`)\n * - `_downAutoValue` (value → protocol framing with equals)\n * - `_handleLocalLifecycle` (cached/status/terminal updates + meta propagation)\n *\n * **Subclass hooks (abstract):**\n * - `_onActivate()` — called when sinkCount transitions 0 → 1\n * - `_doDeactivate()` — cleanup on deactivation (at-most-once, guarded by `_onDeactivate`)\n * - `up()` / `unsubscribe()` / `_upInternal()` — dep-iteration specifics\n * - `_createMetaNode()` — meta companion factory (avoids circular imports)\n *\n * See GRAPHREFLY-SPEC §2 and COMPOSITION-GUIDE §1 for protocol contracts.\n */\n\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, NodeVersionInfo, VersioningLevel } from \"./versioning.js\";\nimport { advanceVersion, createVersioning, defaultHash } from \"./versioning.js\";\n\n// ---------------------------------------------------------------------------\n// Symbols\n// ---------------------------------------------------------------------------\n\n/**\n * Internal sentinel value: \"no cached value has been set or emitted.\"\n * Used instead of `undefined` so that `undefined` can be a valid emitted value.\n */\nexport const NO_VALUE: unique symbol = Symbol.for(\"graphrefly/NO_VALUE\");\n\n/**\n * Branded symbol that marks a {@link CleanupResult} wrapper — prevents\n * duck-type collisions with domain objects that happen to have a `cleanup`\n * property.\n */\nexport const CLEANUP_RESULT: unique symbol = Symbol.for(\"graphrefly/CLEANUP_RESULT\");\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Lifecycle status of a node (GRAPHREFLY-SPEC §2.2). */\nexport type NodeStatus =\n\t| \"disconnected\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\n/** Callback that receives downstream message batches. */\nexport type NodeSink = (messages: Messages) => void;\n\n/** Imperative actions available inside a node's compute function. */\nexport interface NodeActions {\n\t/** Emit raw messages downstream. */\n\tdown(messages: Messages): void;\n\t/** Emit a single value (auto-wraps in DIRTY/DATA or DIRTY/RESOLVED). */\n\temit(value: unknown): void;\n\t/** Send messages upstream toward sources. */\n\tup(messages: Messages): void;\n}\n\n/**\n * Callback for intercepting messages before the default dispatch (§2.6).\n *\n * Called for every message from every dep. Return `true` to consume\n * (skip default handling), or `false` to let default dispatch run.\n */\nexport type OnMessageHandler = (msg: Message, depIndex: number, actions: NodeActions) => boolean;\n\n/**\n * Internal inspector hook (opt-in): emits dependency message and run events\n * for graph-level observability features (`observe(..., { causal|derived })`).\n */\nexport type NodeInspectorHookEvent =\n\t| { kind: \"dep_message\"; depIndex: number; message: Message }\n\t| { kind: \"run\"; depValues: readonly unknown[] };\n\nexport type NodeInspectorHook = (event: NodeInspectorHookEvent) => void;\n\n/** Explicit describe `type` for {@link Graph.describe} (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\n/** Options accepted by every node constructor. */\nexport interface NodeOptions {\n\tname?: string;\n\t/**\n\t * Overrides inferred `type` in describe output. Sugar constructors set this;\n\t * omit to infer from deps / fn / manual emit usage.\n\t */\n\tdescribeKind?: NodeDescribeKind;\n\t/** Equality check for RESOLVED detection. Defaults to `Object.is`. */\n\tequals?: (a: unknown, b: unknown) => boolean;\n\tinitial?: unknown;\n\t/**\n\t * Each key becomes an independently subscribable companion node.\n\t * Meta nodes outlive the parent's subscription lifecycle: when all sinks\n\t * unsubscribe the parent deactivates but meta nodes stay alive.\n\t * Send `[[TEARDOWN]]` to the parent to release meta node resources.\n\t */\n\tmeta?: Record<string, unknown>;\n\t/** Allow fresh subscriptions after COMPLETE/ERROR. */\n\tresubscribable?: boolean;\n\t/**\n\t * Invoked when a new {@link Node.subscribe} clears a terminal state on a\n\t * resubscribable node — reset operator-local counters/accumulators here.\n\t */\n\tonResubscribe?: () => void;\n\t/** Clear cached value on TEARDOWN. */\n\tresetOnTeardown?: boolean;\n\t/**\n\t * When `true` (default), auto-emit `[[COMPLETE]]` when all deps complete\n\t * (spec §1.3.5). Set `false` for derived/operator nodes that should not\n\t * auto-complete.\n\t */\n\tcompleteWhenDepsComplete?: boolean;\n\t/**\n\t * Intercept messages before the default dispatch (spec §2.6).\n\t *\n\t * Return `true` to consume the message (skip default handling),\n\t * or `false` to let the default dispatch run.\n\t */\n\tonMessage?: OnMessageHandler;\n\t/**\n\t * ABAC: `(actor, action) => boolean`. `write` applies to both {@link Node.down} and {@link Node.up}.\n\t * Companion {@link NodeOptions.meta | meta} nodes inherit this guard from the primary.\n\t */\n\tguard?: NodeGuard;\n\t/** Opt-in versioning level (GRAPHREFLY-SPEC §7). */\n\tversioning?: VersioningLevel;\n\t/** Override auto-generated versioning id. */\n\tversioningId?: string;\n\t/** Custom hash function for V1 cid computation. */\n\tversioningHash?: HashFn;\n}\n\n/** Actor/delivery context for {@link Node.down} and {@link Node.up}. */\nexport type NodeTransportOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips guard checks (reactive internals, graph lifecycle TEARDOWN, etc.).\n\t * Not for untrusted call sites.\n\t */\n\tinternal?: boolean;\n\t/**\n\t * `signal` for {@link Graph.signal} deliveries; default `write` for {@link Graph.set}\n\t * and direct `down`.\n\t */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/** Optional hints passed to {@link Node.subscribe}. */\nexport interface SubscribeHints {\n\t/**\n\t * Subscriber has exactly one dep with `fn` — the source may skip DIRTY\n\t * dispatch when this is the sole subscriber. The subscriber synthesizes\n\t * dirty state locally.\n\t */\n\tsingleDep?: boolean;\n\t/**\n\t * Actor to check against the node's `observe` guard. When set,\n\t * `subscribe()` throws {@link GuardDenied} if the actor is not permitted\n\t * to observe this node.\n\t */\n\tactor?: Actor;\n}\n\n/** A reactive node in the GraphReFly protocol. */\nexport interface Node<T = unknown> {\n\treadonly name?: string;\n\treadonly status: NodeStatus;\n\treadonly meta: Record<string, Node>;\n\t/** Returns the current cached value. */\n\tget(): T | undefined;\n\t/** Push messages downstream. */\n\tdown(messages: Messages, options?: NodeTransportOptions): void;\n\t/**\n\t * Registers a sink to receive downstream messages.\n\t *\n\t * @param sink - Callback receiving message batches.\n\t * @param hints - Optional optimization hints (e.g. `{ singleDep: true }`).\n\t * @returns An unsubscribe function (idempotent).\n\t */\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void;\n\t/** Send messages upstream (present on nodes with deps). */\n\tup?: (messages: Messages, options?: NodeTransportOptions) => void;\n\t/** Disconnect from upstream deps (present on nodes with deps). */\n\tunsubscribe?: () => void;\n\t/** Last successful guarded `down` / `up` (not set for `internal` deliveries). */\n\treadonly lastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/** Whether `actor` may {@link Graph.observe} this node. */\n\tallowsObserve(actor: Actor): boolean;\n\t/** Whether a {@link NodeOptions.guard | guard} is installed. */\n\thasGuard(): boolean;\n\t/** Versioning info (GRAPHREFLY-SPEC §7). `undefined` when versioning is not enabled. */\n\treadonly v: Readonly<NodeVersionInfo> | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Cleanup result wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Explicit cleanup wrapper. When a node fn returns `{ cleanup, value? }`,\n * `cleanup` is registered as the teardown/recompute cleanup and `value`\n * (if present) is emitted as data. This avoids the ambiguity where returning\n * a plain function is silently consumed as cleanup instead of emitted as data.\n */\nexport type CleanupResult<T = unknown> = {\n\treadonly [CLEANUP_RESULT]: true;\n\tcleanup: () => void;\n\tvalue?: T;\n};\n\n/** Create a branded {@link CleanupResult}. */\nexport function cleanupResult<T>(cleanup: () => void): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, value: T): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, ...args: [] | [T]): CleanupResult<T> {\n\tconst r: CleanupResult<T> = { [CLEANUP_RESULT]: true, cleanup };\n\tif (args.length > 0) r.value = args[0];\n\treturn r;\n}\n\nexport const isCleanupResult = (value: unknown): value is CleanupResult =>\n\ttypeof value === \"object\" && value !== null && CLEANUP_RESULT in value;\n\nexport const isCleanupFn = (value: unknown): value is () => void => typeof value === \"function\";\n\n// ---------------------------------------------------------------------------\n// Status transitions\n// ---------------------------------------------------------------------------\n\n/**\n * Returns the post-message status for `status` after processing `msg`.\n * START is informational and does not transition status.\n */\nexport function statusAfterMessage(status: NodeStatus, msg: Message): NodeStatus {\n\tconst t = msg[0];\n\tif (t === DIRTY) return \"dirty\";\n\tif (t === DATA) return \"settled\";\n\tif (t === RESOLVED) return \"resolved\";\n\tif (t === COMPLETE) return \"completed\";\n\tif (t === ERROR) return \"errored\";\n\tif (t === INVALIDATE) return \"dirty\";\n\tif (t === TEARDOWN) return \"disconnected\";\n\treturn status;\n}\n\n// ---------------------------------------------------------------------------\n// BitSet — dep mask helper (int fast path for ≤31 deps, array for more)\n// ---------------------------------------------------------------------------\n\n/**\n * Dep settlement tracker. IMPORTANT: `covers()` requires both operands to be\n * the same concrete type (both IntBitSet or both ArrayBitSet). Within a node,\n * all masks share the same `createBitSet(deps.length)` factory, so this is\n * always satisfied.\n */\nexport interface BitSet {\n\tset(index: number): void;\n\tclear(index: number): void;\n\thas(index: number): boolean;\n\t/** True when all bits in `other` are also set in `this`. */\n\tcovers(other: BitSet): boolean;\n\t/** True when at least one bit is set. */\n\tany(): boolean;\n\treset(): void;\n\t/** Set all bits in [0, size) — used for the pre-set-dirty wave trick. */\n\tsetAll(): void;\n}\n\nfunction createIntBitSet(size: number): BitSet {\n\tconst fullMask = size >= 32 ? -1 : ~(-1 << size);\n\tlet bits = 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\tbits |= 1 << i;\n\t\t},\n\t\tclear(i: number) {\n\t\t\tbits &= ~(1 << i);\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (bits & (1 << i)) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst otherBits = (other as unknown as { _bits(): number })._bits();\n\t\t\treturn (bits & otherBits) === otherBits;\n\t\t},\n\t\tany() {\n\t\t\treturn bits !== 0;\n\t\t},\n\t\treset() {\n\t\t\tbits = 0;\n\t\t},\n\t\tsetAll() {\n\t\t\tbits = fullMask;\n\t\t},\n\t\t_bits() {\n\t\t\treturn bits;\n\t\t},\n\t} as BitSet & { _bits(): number };\n}\n\nfunction createArrayBitSet(size: number): BitSet {\n\tconst words = new Uint32Array(Math.ceil(size / 32));\n\tconst lastBits = size % 32;\n\tconst lastWordMask = lastBits === 0 ? 0xffffffff : ((1 << lastBits) - 1) >>> 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\twords[i >>> 5] |= 1 << (i & 31);\n\t\t},\n\t\tclear(i: number) {\n\t\t\twords[i >>> 5] &= ~(1 << (i & 31));\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (words[i >>> 5] & (1 << (i & 31))) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst ow = (other as unknown as { _words: Uint32Array })._words;\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif ((words[w] & ow[w]) >>> 0 !== ow[w]) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\t\tany() {\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif (words[w] !== 0) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\treset() {\n\t\t\twords.fill(0);\n\t\t},\n\t\tsetAll() {\n\t\t\tfor (let w = 0; w < words.length - 1; w++) words[w] = 0xffffffff;\n\t\t\tif (words.length > 0) words[words.length - 1] = lastWordMask;\n\t\t},\n\t\t_words: words,\n\t} as unknown as BitSet;\n}\n\n/** Create a BitSet sized for `size` bits (≤31 uses fast int path). */\nexport function createBitSet(size: number): BitSet {\n\treturn size <= 31 ? createIntBitSet(size) : createArrayBitSet(size);\n}\n\n// ---------------------------------------------------------------------------\n// NodeBase\n// ---------------------------------------------------------------------------\n\n/**\n * Abstract base class for every node in the graph. Both {@link NodeImpl}\n * (static deps) and {@link DynamicNodeImpl} (runtime-tracked deps) extend\n * this to share subscribe/sink/lifecycle machinery.\n *\n * Invariants (see GRAPHREFLY-SPEC §2.2):\n * - `_sinkCount` always reflects the size of `_sinks`.\n * - `_cached === NO_VALUE` iff the node has never produced a value (SENTINEL).\n * - `_terminal` is set exactly once (per subscription cycle for resubscribable).\n * - `_onActivate` runs exactly once per activation cycle; `_doDeactivate`\n * runs at most once per deactivation (guarded by `_active` flag).\n *\n * ROM/RAM rule (GRAPHREFLY-SPEC §2.2): state nodes (no fn) preserve `_cached`\n * across disconnect — intrinsic, non-volatile. Compute nodes (derived,\n * producer, dynamic) clear `_cached` on disconnect in their subclass\n * `_doDeactivate` — their value is a function of live subscriptions.\n */\nexport abstract class NodeBase<T = unknown> implements Node<T> {\n\t// --- Identity (set once) ---\n\tprotected readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\t/** @internal Read by `describeNode` before inference. */\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\n\t// --- Options ---\n\tprotected readonly _equals: (a: unknown, b: unknown) => boolean;\n\tprotected readonly _resubscribable: boolean;\n\tprotected readonly _resetOnTeardown: boolean;\n\tprotected readonly _onResubscribe: (() => void) | undefined;\n\tprotected readonly _onMessage: OnMessageHandler | undefined;\n\t/** @internal Read by `describeNode` for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\t/** @internal Subclasses update this through {@link _recordMutation}. */\n\tprotected _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\n\t// --- Versioning ---\n\tprotected _hashFn: HashFn;\n\tprivate _versioning: NodeVersionInfo | undefined;\n\n\t// --- Lifecycle state ---\n\t/** @internal Read by `describeNode` and `graph.ts`. */\n\t_cached: T | typeof NO_VALUE;\n\t/** @internal Read externally via `get status()`. */\n\t_status: NodeStatus;\n\tprotected _terminal = false;\n\tprivate _active = false;\n\n\t// --- Sink storage ---\n\t/** @internal Read by `graph/profile.ts` for subscriber counts. */\n\t_sinkCount = 0;\n\tprotected _singleDepSinkCount = 0;\n\tprotected _singleDepSinks = new WeakSet<NodeSink>();\n\tprotected _sinks: NodeSink | Set<NodeSink> | null = null;\n\n\t// --- Actions + bound helpers ---\n\tprotected readonly _actions: NodeActions;\n\tprotected readonly _boundDownToSinks: (messages: Messages) => void;\n\n\t// --- Inspector hook (Graph observability) ---\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\n\tconstructor(opts: NodeOptions) {\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._resubscribable = opts.resubscribable ?? false;\n\t\tthis._resetOnTeardown = opts.resetOnTeardown ?? false;\n\t\tthis._onResubscribe = opts.onResubscribe;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._guard = opts.guard;\n\n\t\t// Cache pre-populated from `initial`, or SENTINEL.\n\t\tthis._cached = \"initial\" in opts ? (opts.initial as T) : NO_VALUE;\n\t\t// Initial status: state with value starts settled, otherwise disconnected.\n\t\tthis._status = \"disconnected\";\n\n\t\t// Versioning (GRAPHREFLY-SPEC §7)\n\t\tthis._hashFn = opts.versioningHash ?? defaultHash;\n\t\tthis._versioning =\n\t\t\topts.versioning != null\n\t\t\t\t? createVersioning(opts.versioning, this._cached === NO_VALUE ? undefined : this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\t// Build companion meta nodes — dispatched to subclass to avoid\n\t\t// circular imports (node-base → node → node-base).\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = this._createMetaNode(k, v, opts);\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions captured once — references `this` via an arrow/closure so\n\t\t// subclass hooks (e.g. `_onManualEmit`) fire on the right instance.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._onManualEmit();\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._onManualEmit();\n\t\t\t\tself._downAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tself._upInternal(messages);\n\t\t\t},\n\t\t};\n\n\t\tthis._boundDownToSinks = this._downToSinks.bind(this);\n\t}\n\n\t/**\n\t * Subclass hook invoked by `actions.down` / `actions.emit`. Default no-op;\n\t * {@link NodeImpl} overrides to set `_manualEmitUsed`.\n\t */\n\tprotected _onManualEmit(): void {\n\t\t/* no-op */\n\t}\n\n\t/**\n\t * Create a companion meta node. Called from the base constructor; must\n\t * not touch subclass fields that haven't been initialized yet (safe to\n\t * read from `opts`).\n\t */\n\tprotected abstract _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node;\n\n\t// --- Identity getters ---\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/** @internal Assigned by `Graph.add` when registered without an options `name`. */\n\t_assignRegistryName(localName: string): void {\n\t\tif (this._optsName !== undefined || this._registryName !== undefined) return;\n\t\tthis._registryName = localName;\n\t}\n\n\t/**\n\t * @internal Attach/remove inspector hook for graph-level observability.\n\t * Returns a disposer that restores the previous hook.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tconst prev = this._inspectorHook;\n\t\tthis._inspectorHook = hook;\n\t\treturn () => {\n\t\t\tif (this._inspectorHook === hook) {\n\t\t\t\tthis._inspectorHook = prev;\n\t\t\t}\n\t\t};\n\t}\n\n\t/** @internal Used by subclasses to surface inspector events. */\n\tprotected _emitInspectorHook(event: NodeInspectorHookEvent): void {\n\t\tthis._inspectorHook?.(event);\n\t}\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\tget v(): Readonly<NodeVersionInfo> | undefined {\n\t\treturn this._versioning;\n\t}\n\n\t/** @internal Used by `Graph.setVersioning` to retroactively apply versioning. */\n\t_applyVersioning(level: VersioningLevel, opts?: { id?: string; hash?: HashFn }): void {\n\t\tif (this._versioning != null) return;\n\t\tthis._hashFn = opts?.hash ?? this._hashFn;\n\t\tthis._versioning = createVersioning(\n\t\t\tlevel,\n\t\t\tthis._cached === NO_VALUE ? undefined : this._cached,\n\t\t\t{\n\t\t\t\tid: opts?.id,\n\t\t\t\thash: this._hashFn,\n\t\t\t},\n\t\t);\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\t// --- Public transport ---\n\n\tget(): T | undefined {\n\t\treturn this._cached === NO_VALUE ? undefined : this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\t/** @internal Record a successful guarded mutation (called by `down` and subclass `up`). */\n\tprotected _recordMutation(actor: Actor): void {\n\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t}\n\n\t/** Abstract — subclasses forward messages to dependencies (or no-op for sources). */\n\tabstract up(messages: Messages, options?: NodeTransportOptions): void;\n\n\t/** Abstract — subclasses release upstream subscriptions (or no-op for sources). */\n\tabstract unsubscribe(): void;\n\n\t/** Internal upstream-send used by `actions.up`. */\n\tprotected abstract _upInternal(messages: Messages): void;\n\n\t/** Called when `_sinkCount` transitions 0 → 1. */\n\tprotected abstract _onActivate(): void;\n\n\t/**\n\t * At-most-once deactivation guard. Both TEARDOWN (eager) and\n\t * unsubscribe-body (lazy) call this. The `_active` flag ensures\n\t * `_doDeactivate` runs exactly once per activation cycle.\n\t */\n\tprotected _onDeactivate(): void {\n\t\tif (!this._active) return;\n\t\tthis._active = false;\n\t\tthis._doDeactivate();\n\t}\n\n\t/** Subclass hook: cleanup on deactivation (called at most once). */\n\tprotected abstract _doDeactivate(): void;\n\n\t// --- Subscribe (uniform across node shapes) ---\n\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void {\n\t\tif (hints?.actor != null && this._guard != null) {\n\t\t\tconst actor = normalizeActor(hints.actor);\n\t\t\tif (!this._guard(actor, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\t// Resubscribable terminal reset — clear terminal + cache, fire hook.\n\t\tif (this._terminal && this._resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._status = \"disconnected\";\n\t\t\tthis._onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\t// §2.2 START handshake — delivered BEFORE registering sink in\n\t\t// `_sinks` so that re-entrant `_downToSinks` calls during\n\t\t// activation cannot reach the new sink before it receives START\n\t\t// (spec §1.3.8: START precedes any other message on a subscription).\n\t\t//\n\t\t// Wire shape:\n\t\t// SENTINEL cache → [[START]]\n\t\t// cached value → [[START], [DATA, cached]]\n\t\t//\n\t\t// DIRTY is intentionally NOT part of the handshake: nothing is\n\t\t// transitioning here, we're simply delivering the current state.\n\t\t// Downstream derived nodes mark both dirty+settled on DATA-without-\n\t\t// prior-DIRTY (spec §1.3.1 compat path), so wave tracking still\n\t\t// works without polluting observers with a spurious DIRTY.\n\t\t// §2.2 handshake: START (+ cached DATA if available). Terminal nodes\n\t\t// skip entirely — absence of START tells the subscriber the stream is\n\t\t// over (spec §2.2: \"absence of START means the subscription was never\n\t\t// established or the node is terminal\"). This is intentional: terminal\n\t\t// nodes release resources; replaying COMPLETE/ERROR to late subscribers\n\t\t// would require retaining the terminal cause indefinitely.\n\t\tif (!this._terminal) {\n\t\t\tconst startMessages: Messages =\n\t\t\t\tthis._cached === NO_VALUE ? [[START]] : [[START], [DATA, this._cached]];\n\t\t\tdownWithBatch(sink, startMessages);\n\t\t}\n\n\t\t// Register sink in the singleton / set storage — AFTER START so\n\t\t// re-entrant `_downToSinks` during `_onActivate` can reach it.\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\t// First subscriber triggers activation. May cause fn to run and emit\n\t\t// via `_downInternal` → `_downToSinks` to the new sink.\n\t\tif (this._sinkCount === 1 && !this._terminal) {\n\t\t\tthis._active = true;\n\t\t\tthis._onActivate();\n\t\t}\n\n\t\t// If activation did not produce a value (compute node blocked on\n\t\t// SENTINEL deps, or a source with no initial), surface \"pending\".\n\t\tif (!this._terminal && this._status === \"disconnected\" && this._cached === NO_VALUE) {\n\t\t\tthis._status = \"pending\";\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tif (this._singleDepSinks.has(sink)) {\n\t\t\t\tthis._singleDepSinkCount -= 1;\n\t\t\t\tthis._singleDepSinks.delete(sink);\n\t\t\t}\n\t\t\tif (this._sinks == null) return;\n\t\t\tif (typeof this._sinks === \"function\") {\n\t\t\t\tif (this._sinks === sink) this._sinks = null;\n\t\t\t} else {\n\t\t\t\tthis._sinks.delete(sink);\n\t\t\t\tif (this._sinks.size === 1) {\n\t\t\t\t\tconst [only] = this._sinks;\n\t\t\t\t\tthis._sinks = only;\n\t\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\t\tthis._sinks = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._sinks == null) {\n\t\t\t\tthis._onDeactivate();\n\t\t\t}\n\t\t};\n\t}\n\n\t// --- Down pipeline ---\n\n\t/**\n\t * Core outgoing dispatch. Applies terminal filter + local lifecycle\n\t * update, then hands messages to `downWithBatch` for tier-aware delivery.\n\t */\n\tprotected _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._resubscribable) {\n\t\t\t// After terminal, only TEARDOWN / INVALIDATE still propagate\n\t\t\t// (so graph teardown and cache-clear still work).\n\t\t\tconst pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (pass.length === 0) return;\n\t\t\tsinkMessages = pass as Messages;\n\t\t}\n\t\tthis._handleLocalLifecycle(sinkMessages);\n\t\t// Single-dep DIRTY-skip optimization: when this node's only sink is\n\t\t// single-dep AND the batch contains a phase-2 message (DATA/RESOLVED),\n\t\t// strip DIRTY from the outgoing batch. The downstream learns of the\n\t\t// value via the phase-2 message directly.\n\t\tif (this._canSkipDirty()) {\n\t\t\tlet hasPhase2 = false;\n\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\tconst t = sinkMessages[i][0];\n\t\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\t\thasPhase2 = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPhase2) {\n\t\t\t\tconst filtered: Message[] = [];\n\t\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\t\tif (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);\n\t\t\t\t}\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tdownWithBatch(this._boundDownToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tdownWithBatch(this._boundDownToSinks, sinkMessages);\n\t}\n\n\tprotected _canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\tprotected _downToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others mid-iteration.\n\t\t// Iterating the live Set would skip not-yet-visited sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\t/**\n\t * Update `_cached`, `_status`, `_terminal` from message batch before\n\t * delivery. Subclass hooks `_onInvalidate` / `_onTeardown` let\n\t * {@link NodeImpl} clear `_lastDepValues` and invoke cleanup fns.\n\t */\n\tprotected _handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (m.length < 2) {\n\t\t\t\t\t// §1.2: bare [DATA] without payload is a protocol violation.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\tthis._onInvalidate();\n\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t}\n\t\t\tthis._status = statusAfterMessage(this._status, m);\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._resetOnTeardown) {\n\t\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t\t}\n\t\t\t\tthis._onTeardown();\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\t// Force upstream disconnect immediately — don't wait for\n\t\t\t\t\t// downstream to unsubscribe. _onDeactivate's _active\n\t\t\t\t\t// guard ensures _doDeactivate runs at most once.\n\t\t\t\t\tthis._onDeactivate();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t !== TEARDOWN && propagatesToMeta(t)) {\n\t\t\t\tthis._propagateToMeta(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Subclass hook: invoked when INVALIDATE arrives (before `_cached` is\n\t * cleared). {@link NodeImpl} uses this to run the fn cleanup fn and\n\t * drop `_lastDepValues` so the next wave re-runs fn.\n\t */\n\tprotected _onInvalidate(): void {\n\t\t/* no-op default */\n\t}\n\n\t/**\n\t * Subclass hook: invoked when TEARDOWN arrives, before `_onDeactivate`.\n\t * {@link NodeImpl} uses this to run any pending cleanup fn.\n\t */\n\tprotected _onTeardown(): void {\n\t\t/* no-op default */\n\t}\n\n\t/** Forward a signal to all companion meta nodes (best-effort). */\n\tprotected _propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\t// Direct access through NodeBase — meta nodes are always NodeBase instances.\n\t\t\t\t(metaNode as NodeBase)._downInternal([[t]]);\n\t\t\t} catch {\n\t\t\t\t/* best-effort — other meta nodes still receive the signal */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Frame a computed value into the right protocol messages and dispatch\n\t * via `_downInternal`. Used by `_runFn` and `actions.emit`.\n\t */\n\tprotected _downAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tlet unchanged: boolean;\n\t\ttry {\n\t\t\tunchanged = this._cached !== NO_VALUE && this._equals(this._cached, value);\n\t\t} catch (eqErr) {\n\t\t\tconst eqMsg = eqErr instanceof Error ? eqErr.message : String(eqErr);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": equals threw: ${eqMsg}`, {\n\t\t\t\tcause: eqErr,\n\t\t\t});\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\treturn;\n\t\t}\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n}\n","/**\n * `NodeImpl` — the canonical node primitive for static (compile-time known)\n * dependency graphs. Covers state, producer, derived, effect, operator, and\n * passthrough shapes from a single class.\n *\n * Lifecycle machinery (subscribe + START handshake + `_downInternal` pipeline)\n * lives in {@link NodeBase}. This file only adds:\n * - Dep-wave tracking via pre-set dirty masks (first run and subsequent waves\n * share the same code path — see `_connectUpstream` + `_handleDepMessages`)\n * - `_runFn` with identity-skip optimization on `_lastDepValues`\n * - Producer start/stop tied to sink count\n * - ROM/RAM cache semantics: compute nodes clear `_cached` on disconnect,\n * state sources preserve it (see `_onDeactivate`).\n *\n * See GRAPHREFLY-SPEC §§2.1–2.8 and COMPOSITION-GUIDE §§1, 9.\n */\n\nimport { normalizeActor } from \"./actor.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport {\n\ttype BitSet,\n\tcreateBitSet,\n\tisCleanupFn,\n\tisCleanupResult,\n\tNO_VALUE,\n\ttype Node,\n\ttype NodeActions,\n\tNodeBase,\n\ttype NodeOptions,\n\ttype NodeTransportOptions,\n\ttype SubscribeHints,\n} from \"./node-base.js\";\n\n// Re-exports so downstream files keep importing from \"./node.js\".\nexport {\n\tCLEANUP_RESULT,\n\ttype CleanupResult,\n\tcleanupResult,\n\tNO_VALUE,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeInspectorHook,\n\ttype NodeInspectorHookEvent,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node-base.js\";\n\n/**\n * Compute function passed to `node(deps, fn, opts?)`.\n *\n * @returns A value to emit, `undefined` to skip emission, or a cleanup\n * function invoked before the next run or on teardown.\n */\nexport type NodeFn<T = unknown> = (\n\tdeps: readonly unknown[],\n\tactions: NodeActions,\n) => T | undefined | (() => void);\n\n// ---------------------------------------------------------------------------\n// NodeImpl\n// ---------------------------------------------------------------------------\n\n/**\n * Class-based implementation of the {@link Node} interface for static deps.\n *\n * All internal state is exposed as package-visible fields so introspection\n * (e.g. `describeNode`) can read them via `instanceof NodeImpl`.\n */\nexport class NodeImpl<T = unknown> extends NodeBase<T> {\n\t// --- Dep configuration (set once) ---\n\t_deps: readonly Node[];\n\t_fn: NodeFn<T> | undefined;\n\t_opts: NodeOptions;\n\t_hasDeps: boolean;\n\t_isSingleDep: boolean;\n\t_autoComplete: boolean;\n\n\t// --- Wave tracking masks ---\n\tprivate _depDirtyMask: BitSet;\n\tprivate _depSettledMask: BitSet;\n\tprivate _depCompleteMask: BitSet;\n\tprivate _allDepsCompleteMask: BitSet;\n\n\t// --- Identity-skip optimization ---\n\tprivate _lastDepValues: readonly unknown[] | undefined;\n\tprivate _cleanup: (() => void) | undefined;\n\n\t// --- Upstream bookkeeping ---\n\tprivate _upstreamUnsubs: Array<() => void> = [];\n\n\t// --- Fn behavior flag ---\n\t/** @internal Read by `describeNode` to infer `\"operator\"` label. */\n\t_manualEmitUsed = false;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn<T> | undefined, opts: NodeOptions) {\n\t\tsuper(opts);\n\t\tthis._deps = deps;\n\t\tthis._fn = fn;\n\t\tthis._opts = opts;\n\t\tthis._hasDeps = deps.length > 0;\n\t\tthis._isSingleDep = deps.length === 1 && fn != null;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\n\t\t// State-with-initial-value starts `settled`; everything else starts\n\t\t// `disconnected` and flips to `pending` at first subscribe if fn\n\t\t// hasn't produced a value yet.\n\t\tif (!this._hasDeps && fn == null && this._cached !== NO_VALUE) {\n\t\t\tthis._status = \"settled\";\n\t\t}\n\n\t\tthis._depDirtyMask = createBitSet(deps.length);\n\t\tthis._depSettledMask = createBitSet(deps.length);\n\t\tthis._depCompleteMask = createBitSet(deps.length);\n\t\tthis._allDepsCompleteMask = createBitSet(deps.length);\n\t\tfor (let i = 0; i < deps.length; i++) this._allDepsCompleteMask.set(i);\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\t// --- Meta node factory (called from base constructor) ---\n\n\tprotected _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node {\n\t\treturn node({\n\t\t\tinitial: initialValue,\n\t\t\tname: `${opts.name ?? \"node\"}:meta:${key}`,\n\t\t\tdescribeKind: \"state\",\n\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t});\n\t}\n\n\t// --- Manual emit tracker (set by actions.down / actions.emit) ---\n\n\tprotected override _onManualEmit(): void {\n\t\tthis._manualEmitUsed = true;\n\t}\n\n\t// --- Up / unsubscribe ---\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tif (options === undefined) {\n\t\t\t\tdep.up?.(messages);\n\t\t\t} else {\n\t\t\t\tdep.up?.(messages, options);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected _upInternal(messages: Messages): void {\n\t\tif (!this._hasDeps) return;\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tif (!this._hasDeps) return;\n\t\tthis._disconnectUpstream();\n\t}\n\n\t// --- Activation (first-subscriber / last-subscriber hooks) ---\n\n\tprotected _onActivate(): void {\n\t\tif (this._hasDeps) {\n\t\t\tthis._connectUpstream();\n\t\t\treturn;\n\t\t}\n\t\tif (this._fn) {\n\t\t\tthis._runFn();\n\t\t\treturn;\n\t\t}\n\t\t// Pure state node: no-op. Cached value (if any) is already delivered\n\t\t// through the subscribe-time START handshake.\n\t}\n\n\tprotected _doDeactivate(): void {\n\t\t// Release upstream subscriptions (for compute nodes with deps).\n\t\tthis._disconnectUpstream();\n\t\t// Flush pending cleanup fn (producers + derived both use `_cleanup`).\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\n\t\t// ROM/RAM rule (GRAPHREFLY-SPEC §2.2): compute nodes (anything with\n\t\t// `fn`) clear their cache on disconnect because their value is a\n\t\t// function of live subscriptions. State nodes (no fn) preserve\n\t\t// `_cached` — runtime writes survive across disconnect.\n\t\tif (this._fn != null) {\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._lastDepValues = undefined;\n\t\t}\n\n\t\t// Status: only transition to \"disconnected\" for compute nodes.\n\t\t// Pure state nodes remain in whatever status they were (usually\n\t\t// \"settled\" if they hold a value).\n\t\tif (this._hasDeps || this._fn != null) {\n\t\t\tthis._status = \"disconnected\";\n\t\t}\n\t}\n\n\t// --- INVALIDATE / TEARDOWN hooks (clear fn state) ---\n\n\tprotected override _onInvalidate(): void {\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\t\tthis._lastDepValues = undefined;\n\t}\n\n\tprotected override _onTeardown(): void {\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\t}\n\n\t// --- Upstream connect / disconnect ---\n\n\tprivate _connectUpstream(): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (this._upstreamUnsubs.length > 0) return; // already connected\n\n\t\t// Pre-set dirty mask to all-ones — wave completes when every dep\n\t\t// has settled at least once (spec §2.7, first-run gating).\n\t\tthis._depDirtyMask.setAll();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\t// Stay in \"disconnected\" until fn runs and updates status via\n\t\t// `_handleLocalLifecycle`. `subscribe()` will flip to \"pending\"\n\t\t// if fn did not run before returning.\n\n\t\tconst depValuesBefore = this._lastDepValues;\n\t\tconst subHints: SubscribeHints | undefined = this._isSingleDep\n\t\t\t? { singleDep: true }\n\t\t\t: undefined;\n\t\tfor (let i = 0; i < this._deps.length; i += 1) {\n\t\t\tconst dep = this._deps[i];\n\t\t\tthis._upstreamUnsubs.push(\n\t\t\t\tdep.subscribe((msgs) => this._handleDepMessages(i, msgs), subHints),\n\t\t\t);\n\t\t}\n\t\t// Fallback for `onMessage`-driven operators: if the subscribe loop\n\t\t// did not drive a wave completion (e.g. `concatMap`, `sample` —\n\t\t// operators whose `onMessage` consumes every dep message without\n\t\t// letting the mask-based wave progress), still run fn once so the\n\t\t// operator can initialize side-effect state (inner subscriptions,\n\t\t// cleanup fns, etc.). The fn-is-identity-check guards against\n\t\t// double runs when the normal wave path already fired.\n\t\tif (this._fn && this._onMessage && !this._terminal && this._lastDepValues === depValuesBefore) {\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\tprivate _disconnectUpstream(): void {\n\t\tif (this._upstreamUnsubs.length === 0) return;\n\t\tfor (const unsub of this._upstreamUnsubs.splice(0)) {\n\t\t\tunsub();\n\t\t}\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t}\n\n\t// --- Wave handling ---\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\tfor (const msg of messages) {\n\t\t\tthis._emitInspectorHook({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\t\t\t// User-defined message handler gets first look (spec §2.6).\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tconst consumed = this._onMessage(msg, index, this._actions);\n\t\t\t\t\tif (consumed) {\n\t\t\t\t\t\t// If the operator consumes this dep's subscribe\n\t\t\t\t\t\t// handshake (START), treat the dep as fully\n\t\t\t\t\t\t// user-managed: clear its pre-set dirty bit so the\n\t\t\t\t\t\t// first-run wave gate doesn't block on it.\n\t\t\t\t\t\t// Notifier deps in operators like `takeUntil` rely\n\t\t\t\t\t\t// on this — they're signaling deps, not data deps.\n\t\t\t\t\t\tif (t === START) {\n\t\t\t\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\t\t\t\tthis._runFn();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Tier-0 (START) from a dep is informational — it's the dep's\n\t\t\t// subscribe handshake. It carries no wave-state implication: the\n\t\t\t// paired DATA (if present) is handled by the DATA branch.\n\t\t\tif (messageTier(t) < 1) continue;\n\n\t\t\tif (!this._fn) {\n\t\t\t\t// Passthrough: forward everything except COMPLETE when multi-dep\n\t\t\t\t// (multi-dep passthrough waits for all deps to complete, §1.3.5).\n\t\t\t\tif (t === COMPLETE && this._deps.length > 1) {\n\t\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._onDepDirty(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._onDepSettled(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\tthis._depSettledMask.clear(index);\n\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t} else if (!this._depDirtyMask.any() && this._status === \"dirty\") {\n\t\t\t\t\t// D2: dep went DIRTY→COMPLETE without DATA — the node is\n\t\t\t\t\t// stuck in \"dirty\" with no pending wave to resolve it.\n\t\t\t\t\t// Recompute so downstream sees RESOLVED (unchanged) or\n\t\t\t\t\t// DATA (changed).\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Forward unknown message types.\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\tprivate _onDepDirty(index: number): void {\n\t\t// Track wave transition: propagate DIRTY to our downstream ONLY on\n\t\t// the first dirty of a wave. During the initial wave, the dirty mask\n\t\t// is pre-set to all-ones by `_connectUpstream` so this branch never\n\t\t// fires — our own `_downAutoValue` emits `[[DIRTY],[DATA,v]]` to\n\t\t// downstream when fn completes.\n\t\tconst wasDirty = this._depDirtyMask.has(index);\n\t\tthis._depDirtyMask.set(index);\n\t\tthis._depSettledMask.clear(index);\n\t\tif (!wasDirty) {\n\t\t\tthis._downInternal([[DIRTY]]);\n\t\t}\n\t}\n\n\tprivate _onDepSettled(index: number): void {\n\t\t// Ensure dep is marked dirty. If the dep settled without a prior\n\t\t// DIRTY (spec §1.3.1 compat path for raw external sources), route\n\t\t// through `_onDepDirty` so that our own downstream sees DIRTY\n\t\t// before the resulting DATA/RESOLVED — preserving the two-phase\n\t\t// invariant from our node's perspective.\n\t\tif (!this._depDirtyMask.has(index)) {\n\t\t\tthis._onDepDirty(index);\n\t\t}\n\t\tthis._depSettledMask.set(index);\n\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\tthis._depDirtyMask.reset();\n\t\t\tthis._depSettledMask.reset();\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\tprivate _maybeCompleteFromDeps(): void {\n\t\tif (\n\t\t\tthis._autoComplete &&\n\t\t\tthis._deps.length > 0 &&\n\t\t\tthis._depCompleteMask.covers(this._allDepsCompleteMask)\n\t\t) {\n\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t}\n\t}\n\n\t// --- Fn execution ---\n\n\tprivate _runFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._terminal && !this._resubscribable) return;\n\n\t\ttry {\n\t\t\tconst n = this._deps.length;\n\t\t\tconst depValues = new Array(n);\n\t\t\tfor (let i = 0; i < n; i++) depValues[i] = this._deps[i].get();\n\n\t\t\t// Identity skip BEFORE cleanup: if all dep values are unchanged,\n\t\t\t// skip cleanup+fn so effect nodes don't teardown/restart on no-op.\n\t\t\tconst prev = this._lastDepValues;\n\t\t\tif (n > 0 && prev != null && prev.length === n) {\n\t\t\t\tlet allSame = true;\n\t\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\t\tif (!Object.is(depValues[i], prev[i])) {\n\t\t\t\t\t\tallSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (allSame) {\n\t\t\t\t\tif (this._status === \"dirty\") {\n\t\t\t\t\t\tthis._downInternal([[RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prevCleanup = this._cleanup;\n\t\t\tthis._cleanup = undefined;\n\t\t\tprevCleanup?.();\n\n\t\t\tthis._manualEmitUsed = false;\n\t\t\tthis._lastDepValues = depValues;\n\t\t\tthis._emitInspectorHook({ kind: \"run\", depValues });\n\n\t\t\tconst out = this._fn(depValues, this._actions);\n\n\t\t\t// Explicit cleanup wrapper: { cleanup, value? }\n\t\t\tif (isCleanupResult(out)) {\n\t\t\t\tthis._cleanup = out.cleanup;\n\t\t\t\tif (this._manualEmitUsed) return;\n\t\t\t\tif (\"value\" in out) {\n\t\t\t\t\tthis._downAutoValue(out.value);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Legacy: plain function return → cleanup.\n\t\t\tif (isCleanupFn(out)) {\n\t\t\t\tthis._cleanup = out;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this._manualEmitUsed) return;\n\t\t\tif (out === undefined) return;\n\t\t\tthis._downAutoValue(out);\n\t\t} catch (err) {\n\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, { cause: err });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nconst isNodeArray = (value: unknown): value is readonly Node[] => Array.isArray(value);\n\nconst isNodeOptions = (value: unknown): value is NodeOptions =>\n\ttypeof value === \"object\" && value != null && !Array.isArray(value);\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (§2).\n *\n * Typical shapes: `node([])` / `node([], opts)` for a manual source;\n * `node(producerFn, opts)` for a producer; `node(deps, computeFn, opts)` for\n * derived nodes and operators.\n *\n * @param depsOrFn - Dependency nodes, a {@link NodeFn} (producer), or {@link NodeOptions} alone.\n * @param fnOrOpts - With deps: compute function or options. Omitted for producer-only form.\n * @param optsArg - Options when both `deps` and `fn` are provided.\n * @returns `Node<T>` — lazy until subscribed.\n *\n * @remarks\n * **Protocol:** START handshake, DIRTY / DATA / RESOLVED ordering, completion,\n * and batch deferral follow `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n *\n * **`equals` and mutable values:** The default `Object.is` identity check is\n * correct for the common immutable-value case. If your node produces mutable\n * objects, provide a custom `equals` — otherwise `Object.is` always returns\n * `true` for the same reference and the node emits `RESOLVED` instead of `DATA`.\n *\n * **ROM/RAM (§2.2):** State nodes (no fn) preserve their cache across\n * disconnect — runtime writes survive. Compute nodes (derived, producer)\n * clear their cache on disconnect; reconnect re-runs fn.\n *\n * @example\n * ```ts\n * import { node, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = node([a], ([x]) => (x as number) + 1);\n * ```\n *\n * @category core\n */\nexport function node<T = unknown>(\n\tdepsOrFn?: readonly Node[] | NodeFn<T> | NodeOptions,\n\tfnOrOpts?: NodeFn<T> | NodeOptions,\n\toptsArg?: NodeOptions,\n): Node<T> {\n\tconst deps: readonly Node[] = isNodeArray(depsOrFn) ? depsOrFn : [];\n\tconst fn: NodeFn<T> | undefined =\n\t\ttypeof depsOrFn === \"function\"\n\t\t\t? depsOrFn\n\t\t\t: typeof fnOrOpts === \"function\"\n\t\t\t\t? fnOrOpts\n\t\t\t\t: undefined;\n\tlet opts: NodeOptions = {};\n\tif (isNodeArray(depsOrFn)) {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t} else if (isNodeOptions(depsOrFn)) {\n\t\topts = depsOrFn;\n\t} else {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t}\n\n\treturn new NodeImpl<T>(deps, fn, opts);\n}\n","/**\n * bridge — graph-visible message forwarding between two nodes.\n *\n * Replaces ad-hoc `subscribe()` bridges that bypass graph topology.\n * The returned node is an effect that intercepts messages from `from`\n * and forwards them to `to.down()`. Register it with `graph.add()` to\n * make the bridge visible in `describe()` and `snapshot()`.\n *\n * **Upstream path:** The bridge node has `from` as its dep, so anything\n * downstream of the bridge that calls `up()` naturally reaches `from`.\n * If `to` is used as a dep by other nodes and those nodes send `up()`,\n * the messages reach `to`'s deps (not `from`). For full upstream relay\n * across the bridge boundary, wire the bridge as a dep of `to`'s\n * consumers or use `graph.connect()`.\n *\n * **ABAC / guards:** `to.down()` is called without `NodeTransportOptions`,\n * so any ABAC guard on `to` receives `actor = undefined`. Upstream (`up()`)\n * messages propagate through the dep chain the same way — no actor is\n * injected on either path. Both paths are intentionally unguarded; if `to`\n * requires a specific actor, provide a guarded wrapper node and bridge to\n * that instead.\n *\n * **Default forwarding:** All standard message types are forwarded by\n * default, including TEARDOWN, PAUSE, RESUME, and INVALIDATE. Use the\n * `down` option to restrict which types are forwarded. Callers that need\n * to exclude TEARDOWN (e.g. inter-stage wiring in `funnel()`) pass an\n * explicit `down` array without TEARDOWN.\n *\n * @module\n */\n\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport { type Node, type NodeActions, node, type OnMessageHandler } from \"./node.js\";\n\n/** Options for {@link bridge}. */\nexport type BridgeOptions = {\n\t/** Node name (for graph registration / describe). */\n\tname?: string;\n\t/**\n\t * Standard message types to forward downstream. Default: all standard\n\t * types. Unknown (non-standard) types always forward per spec §1.3.6\n\t * regardless of this option.\n\t */\n\tdown?: readonly symbol[];\n};\n\n/** All standard types forwarded by default. Export for callers that\n * need to customize (e.g. exclude TEARDOWN). */\nexport const DEFAULT_DOWN: readonly symbol[] = [\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tCOMPLETE,\n\tERROR,\n\tTEARDOWN,\n\tPAUSE,\n\tRESUME,\n\tINVALIDATE,\n];\n\n/**\n * All standard message types the bridge understands. Types outside this set\n * are \"unknown\" and must always be forwarded (spec §1.3.6).\n */\nconst STANDARD_TYPES = new Set<symbol>([\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tCOMPLETE,\n\tERROR,\n\tTEARDOWN,\n\tPAUSE,\n\tRESUME,\n\tINVALIDATE,\n]);\n\n/**\n * Create a graph-visible bridge node that forwards messages from `from` to `to`.\n *\n * The bridge is a real node (effect) — it shows up in `describe()`, participates\n * in two-phase push, and cleans up on TEARDOWN. Register it via `graph.add()`\n * to make it part of the graph topology.\n *\n * **Unknown message types** (custom domain signals not in the standard protocol\n * set) are always forwarded to `to`, regardless of the `down` option. This\n * satisfies spec §1.3.6 (\"unknown types forward unchanged\").\n *\n * **COMPLETE / ERROR**: when forwarded, the bridge also transitions to terminal\n * state so graph-wide completion detection works correctly.\n *\n * @param from - Source node to observe.\n * @param to - Target node to forward messages to via `to.down()`.\n * @param opts - Optional configuration.\n * @returns A bridge effect node. Add it to a graph with `graph.add(name, bridge(...))`.\n *\n * @example\n * ```ts\n * import { bridge, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(0);\n * const b = state(0);\n * const br = bridge(a, b, { name: \"__bridge_a_b\" });\n * graph.add(\"__bridge_a_b\", br);\n * // Now a's messages flow to b, visible in describe()\n * ```\n *\n * @category core\n */\nexport function bridge<T = unknown>(from: Node<T>, to: Node, opts?: BridgeOptions): Node<unknown> {\n\tconst allowedDown = new Set(opts?.down ?? DEFAULT_DOWN);\n\n\tconst onMessage: OnMessageHandler = (\n\t\tmsg: Message,\n\t\t_depIndex: number,\n\t\t_actions: NodeActions,\n\t): boolean => {\n\t\tconst type = msg[0];\n\n\t\t// Unknown types (custom domain signals) always forward — spec §1.3.6.\n\t\tif (!STANDARD_TYPES.has(type)) {\n\t\t\tto.down([msg]);\n\t\t\treturn true;\n\t\t}\n\n\t\t// Terminal types: always transition the bridge to terminal state\n\t\t// (return false → default dispatch). Only forward to `to` if allowed.\n\t\tif (type === COMPLETE || type === ERROR) {\n\t\t\tif (allowedDown.has(type)) {\n\t\t\t\tto.down([msg]);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Known type, not in allowedDown — consume without forwarding.\n\t\tif (!allowedDown.has(type)) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Forward the message to the target.\n\t\tto.down([msg]);\n\t\treturn true;\n\t};\n\n\treturn node([from as Node], undefined, {\n\t\tname: opts?.name,\n\t\tdescribeKind: \"effect\",\n\t\tonMessage,\n\t\tmeta: { _internal: true },\n\t});\n}\n","/**\n * `dynamicNode` — runtime dep tracking with diamond resolution (Phase 0.3b).\n *\n * Unlike `node()` where deps are fixed at construction, `dynamicNode`\n * discovers deps at runtime via a tracking `get()` proxy. After each\n * recompute, deps are diffed: new deps are connected, removed deps are\n * disconnected, and bitmasks are rebuilt.\n *\n * Shares subscribe / sink / lifecycle machinery with {@link NodeImpl} via\n * {@link NodeBase}. The only things that diverge from static nodes:\n * - deps are discovered inside `_runFn` via a tracking `get` proxy\n * - `_rewire` installs subscriptions lazily during `_runFn`\n * - during rewire, new dep messages are **buffered** (option C from the\n * Apr-2026 refactor); after rewire we scan the buffer for DATA values\n * that differ from what fn tracked, and re-run fn if any found\n * (bounded by `MAX_RERUN`)\n */\n\nimport { normalizeActor } from \"./actor.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport { node as createNode } from \"./node.js\";\nimport {\n\tNO_VALUE,\n\ttype Node,\n\tNodeBase,\n\ttype NodeOptions,\n\ttype NodeTransportOptions,\n} from \"./node-base.js\";\n\n/**\n * The tracking `get` function passed to `dynamicNode`'s compute function.\n * Each call to `get(dep)` reads the dep's current value and records it as a dependency.\n */\nexport type DynGet = <V>(dep: Node<V>) => V | undefined;\n\n/**\n * Compute function for `dynamicNode`. Receives a tracking `get` proxy.\n * Deps are discovered by which nodes are passed to `get()` during execution.\n */\nexport type DynamicNodeFn<T> = (get: DynGet) => T;\n\n/** Options for `dynamicNode`. */\nexport type DynamicNodeOptions = Pick<\n\tNodeOptions,\n\t| \"name\"\n\t| \"equals\"\n\t| \"meta\"\n\t| \"resubscribable\"\n\t| \"resetOnTeardown\"\n\t| \"guard\"\n\t| \"onMessage\"\n\t| \"onResubscribe\"\n\t| \"completeWhenDepsComplete\"\n\t| \"describeKind\"\n>;\n\n/** Bounded rerun cap for dynamic fn activation loop (lazy-dep stabilization). */\nconst MAX_RERUN = 16;\n\n/**\n * Creates a node with runtime dep tracking. Deps are discovered each time the\n * compute function runs by tracking which nodes are passed to the `get()` proxy.\n *\n * After each recompute:\n * - New deps (not in previous set) are subscribed\n * - Removed deps (not in current set) are unsubscribed\n * - Kept deps retain their existing subscriptions\n *\n * The node participates in diamond resolution via the pre-set dirty mask\n * (shared with {@link NodeImpl}).\n *\n * **Lazy-dep composition:** when a tracked dep is itself a lazy compute node\n * whose first subscribe causes a fresh value to arrive, the rewire buffer\n * detects the discrepancy and re-runs fn once so it observes the real value.\n * Capped at {@link MAX_RERUN} iterations.\n *\n * @param fn - Compute function receiving a tracking `get` proxy.\n * @param opts - Optional configuration.\n * @returns `Node<T>` with dynamic dep tracking.\n *\n * @example\n * ```ts\n * import { dynamicNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const cond = state(true);\n * const a = state(1);\n * const b = state(2);\n *\n * const d = dynamicNode((get) => {\n * const useA = get(cond);\n * return useA ? get(a) : get(b);\n * });\n * ```\n *\n * @category core\n */\nexport function dynamicNode<T = unknown>(fn: DynamicNodeFn<T>, opts?: DynamicNodeOptions): Node<T> {\n\treturn new DynamicNodeImpl<T>(fn, opts ?? {});\n}\n\n/** Pending buffer entry during `_rewire`. */\ntype PendingEntry = { index: number; msgs: Messages };\n\n/** @internal — exported for {@link describeNode} `instanceof` check. */\nexport class DynamicNodeImpl<T = unknown> extends NodeBase<T> {\n\tprivate readonly _fn: DynamicNodeFn<T>;\n\tprivate readonly _autoComplete: boolean;\n\n\t// Dynamic deps tracking\n\t/** @internal Read by `describeNode`. */\n\t_deps: Node[] = [];\n\tprivate _depUnsubs: Array<() => void> = [];\n\tprivate _depIndexMap = new Map<Node, number>();\n\tprivate _depDirtyBits = new Set<number>();\n\tprivate _depSettledBits = new Set<number>();\n\tprivate _depCompleteBits = new Set<number>();\n\n\t// Execution state\n\tprivate _running = false;\n\tprivate _rewiring = false;\n\tprivate _bufferedDepMessages: PendingEntry[] = [];\n\tprivate _trackedValues: Map<Node, unknown> = new Map();\n\tprivate _rerunCount = 0;\n\n\tconstructor(fn: DynamicNodeFn<T>, opts: DynamicNodeOptions) {\n\t\tsuper(opts);\n\t\tthis._fn = fn;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\tprotected _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node {\n\t\treturn createNode({\n\t\t\tinitial: initialValue,\n\t\t\tname: `${opts.name ?? \"dynamicNode\"}:meta:${key}`,\n\t\t\tdescribeKind: \"state\",\n\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t});\n\t}\n\n\t/** Versioning not supported on DynamicNodeImpl (override base). */\n\toverride get v(): undefined {\n\t\treturn undefined;\n\t}\n\n\t// --- Up / unsubscribe ---\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, options);\n\t\t}\n\t}\n\n\tprotected _upInternal(messages: Messages): void {\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tthis._disconnect();\n\t}\n\n\t// --- Activation hooks ---\n\n\tprotected _onActivate(): void {\n\t\tthis._runFn();\n\t}\n\n\tprotected _doDeactivate(): void {\n\t\tthis._disconnect();\n\t}\n\n\tprivate _disconnect(): void {\n\t\tfor (const unsub of this._depUnsubs) unsub();\n\t\tthis._depUnsubs = [];\n\t\tthis._deps = [];\n\t\tthis._depIndexMap.clear();\n\t\tthis._depDirtyBits.clear();\n\t\tthis._depSettledBits.clear();\n\t\tthis._depCompleteBits.clear();\n\n\t\t// ROM/RAM rule (GRAPHREFLY-SPEC §2.2): compute node clears cache on\n\t\t// disconnect — dynamic nodes are always compute nodes.\n\t\tthis._cached = NO_VALUE;\n\t\tthis._status = \"disconnected\";\n\t}\n\n\t// --- Fn execution with rewire buffer ---\n\n\tprivate _runFn(): void {\n\t\tif (this._terminal && !this._resubscribable) return;\n\t\tif (this._running) return;\n\n\t\tthis._running = true;\n\t\tthis._rerunCount = 0;\n\t\tlet result: T | undefined;\n\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\t// --- Phase 1: execute fn with tracking `get`. ---\n\t\t\t\tconst trackedDeps: Node[] = [];\n\t\t\t\tconst trackedValuesMap = new Map<Node, unknown>();\n\t\t\t\tconst trackedSet = new Set<Node>();\n\n\t\t\t\tconst get: DynGet = <V>(dep: Node<V>): V | undefined => {\n\t\t\t\t\tif (!trackedSet.has(dep)) {\n\t\t\t\t\t\ttrackedSet.add(dep);\n\t\t\t\t\t\ttrackedDeps.push(dep);\n\t\t\t\t\t\t// Spec §2.2: `get()` never triggers computation. If the\n\t\t\t\t\t\t// dep is a disconnected lazy node, this returns\n\t\t\t\t\t\t// undefined — the rewire buffer will detect the\n\t\t\t\t\t\t// discrepancy once the lazy dep's real value arrives\n\t\t\t\t\t\t// via subscribe-time push.\n\t\t\t\t\t\ttrackedValuesMap.set(dep, dep.get());\n\t\t\t\t\t}\n\t\t\t\t\treturn dep.get() as V | undefined;\n\t\t\t\t};\n\n\t\t\t\tthis._trackedValues = trackedValuesMap;\n\n\t\t\t\t// Collect dep values for inspector hook\n\t\t\t\tconst depValues: unknown[] = [];\n\t\t\t\tfor (const dep of this._deps) depValues.push(dep.get());\n\t\t\t\tthis._emitInspectorHook({ kind: \"run\", depValues });\n\n\t\t\t\ttry {\n\t\t\t\t\tresult = this._fn(get);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 2: rewire. ---\n\t\t\t\tthis._rewiring = true;\n\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\ttry {\n\t\t\t\t\tthis._rewire(trackedDeps);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._rewiring = false;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 3: scan buffer for discrepancies that require re-run. ---\n\t\t\t\tlet needsRerun = false;\n\t\t\t\tfor (const entry of this._bufferedDepMessages) {\n\t\t\t\t\tfor (const msg of entry.msgs) {\n\t\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\t\tconst dep = this._deps[entry.index];\n\t\t\t\t\t\t\tconst trackedValue = dep != null ? this._trackedValues.get(dep) : undefined;\n\t\t\t\t\t\t\tconst actualValue = msg[1];\n\t\t\t\t\t\t\tif (!this._equals(trackedValue, actualValue)) {\n\t\t\t\t\t\t\t\tneedsRerun = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (needsRerun) break;\n\t\t\t\t}\n\n\t\t\t\tif (needsRerun) {\n\t\t\t\t\tthis._rerunCount += 1;\n\t\t\t\t\tif (this._rerunCount > MAX_RERUN) {\n\t\t\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\t\t\tthis._downInternal([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\tERROR,\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t`dynamicNode \"${this.name ?? \"anonymous\"}\": rewire did not stabilize within ${MAX_RERUN} iterations`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Discard this iteration's buffer and loop.\n\t\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 4: drain buffer — update masks only, no _runFn. ---\n\t\t\t\t//\n\t\t\t\t// Buffered activation-cascade messages are already reflected\n\t\t\t\t// in `_trackedValues` (fn saw the same values). We update\n\t\t\t\t// the wave masks so subsequent dep updates start from a\n\t\t\t\t// consistent state, then clear both masks so the node\n\t\t\t\t// enters post-rewire with clean wave tracking.\n\t\t\t\tconst drain = this._bufferedDepMessages;\n\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\tfor (const entry of drain) {\n\t\t\t\t\tfor (const msg of entry.msgs) {\n\t\t\t\t\t\tthis._updateMasksForMessage(entry.index, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Clear wave masks — the activation cascade is fully\n\t\t\t\t// consumed; subsequent dep updates should start fresh.\n\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._running = false;\n\t\t}\n\n\t\tthis._downAutoValue(result);\n\t}\n\n\tprivate _rewire(newDeps: Node[]): void {\n\t\tconst oldMap = this._depIndexMap;\n\t\tconst newMap = new Map<Node, number>();\n\t\tconst newUnsubs: Array<() => void> = [];\n\n\t\t// Subscribe to new deps (or reuse existing subscriptions).\n\t\tfor (let i = 0; i < newDeps.length; i++) {\n\t\t\tconst dep = newDeps[i];\n\t\t\tnewMap.set(dep, i);\n\t\t\tconst oldIdx = oldMap.get(dep);\n\t\t\tif (oldIdx !== undefined) {\n\t\t\t\t// Kept dep — reuse subscription.\n\t\t\t\tnewUnsubs.push(this._depUnsubs[oldIdx]);\n\t\t\t\tthis._depUnsubs[oldIdx] = () => {};\n\t\t\t} else {\n\t\t\t\t// New dep — subscribe. Its subscribe-time handshake +\n\t\t\t\t// activation cascade will land in `_handleDepMessages`,\n\t\t\t\t// which routes to the buffer while `_rewiring` is true.\n\t\t\t\tconst idx = i;\n\t\t\t\tconst unsub = dep.subscribe((msgs) => this._handleDepMessages(idx, msgs));\n\t\t\t\tnewUnsubs.push(unsub);\n\t\t\t}\n\t\t}\n\n\t\t// Disconnect removed deps.\n\t\tfor (const [dep, oldIdx] of oldMap) {\n\t\t\tif (!newMap.has(dep)) {\n\t\t\t\tthis._depUnsubs[oldIdx]();\n\t\t\t}\n\t\t}\n\n\t\tthis._deps = newDeps;\n\t\tthis._depUnsubs = newUnsubs;\n\t\tthis._depIndexMap = newMap;\n\t\tthis._depDirtyBits.clear();\n\t\tthis._depSettledBits.clear();\n\n\t\t// Preserve complete bits for deps that are still present (re-indexed).\n\t\tconst newCompleteBits = new Set<number>();\n\t\tfor (const oldIdx of this._depCompleteBits) {\n\t\t\tfor (const [dep, idx] of oldMap) {\n\t\t\t\tif (idx === oldIdx && newMap.has(dep)) {\n\t\t\t\t\tnewCompleteBits.add(newMap.get(dep)!);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis._depCompleteBits = newCompleteBits;\n\t}\n\n\t// --- Dep message handling ---\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\t// During rewire, buffer messages for post-rewire scan.\n\t\tif (this._rewiring) {\n\t\t\tthis._bufferedDepMessages.push({ index, msgs: messages });\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const msg of messages) {\n\t\t\tthis._emitInspectorHook({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\n\t\t\t// Note: unlike NodeImpl, we do NOT clear dirty bits when onMessage\n\t\t\t// consumes START. NodeImpl pre-sets all dirty bits in _connectUpstream\n\t\t\t// and must clear them for consumed-START deps (notifier pattern).\n\t\t\t// DynamicNodeImpl never pre-sets dirty bits — deps are discovered\n\t\t\t// lazily during _runFn — so there are no bits to clear.\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Tier-0 (START) from a dep is informational — see NodeImpl for rationale.\n\t\t\tif (messageTier(t) < 1) continue;\n\n\t\t\tif (t === DIRTY) {\n\t\t\t\tconst wasEmpty = this._depDirtyBits.size === 0;\n\t\t\t\tthis._depDirtyBits.add(index);\n\t\t\t\tthis._depSettledBits.delete(index);\n\t\t\t\tif (wasEmpty) {\n\t\t\t\t\tthis._downInternal([[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tif (!this._depDirtyBits.has(index)) {\n\t\t\t\t\t// DATA-without-prior-DIRTY — propagate DIRTY for the two-phase\n\t\t\t\t\t// invariant (§1.3.1 compat path).\n\t\t\t\t\tconst wasEmpty = this._depDirtyBits.size === 0;\n\t\t\t\t\tthis._depDirtyBits.add(index);\n\t\t\t\t\tif (wasEmpty) {\n\t\t\t\t\t\tthis._downInternal([[DIRTY]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._depSettledBits.add(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\t\tif (!this._running) {\n\t\t\t\t\t\t// Identity check against the values fn already saw — if\n\t\t\t\t\t\t// nothing has actually changed, skip the run. This\n\t\t\t\t\t\t// guards against deferred handshake DATA (arriving\n\t\t\t\t\t\t// after `_rewire` finishes inside an open batch)\n\t\t\t\t\t\t// from triggering a redundant re-run.\n\t\t\t\t\t\tif (this._depValuesDifferFromTracked()) {\n\t\t\t\t\t\t\tthis._runFn();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteBits.add(index);\n\t\t\t\tthis._depDirtyBits.delete(index);\n\t\t\t\tthis._depSettledBits.delete(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\t\tif (!this._running) this._runFn();\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tthis._autoComplete &&\n\t\t\t\t\tthis._depCompleteBits.size >= this._deps.length &&\n\t\t\t\t\tthis._deps.length > 0\n\t\t\t\t) {\n\t\t\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\t/**\n\t * Update dep masks for a message without triggering `_runFn` — used\n\t * during post-rewire drain so the wave state is consistent with the\n\t * buffered activation cascade without recursing.\n\t */\n\tprivate _updateMasksForMessage(index: number, msg: Messages[number]): void {\n\t\tconst t = msg[0];\n\t\tif (t === DIRTY) {\n\t\t\tthis._depDirtyBits.add(index);\n\t\t\tthis._depSettledBits.delete(index);\n\t\t} else if (t === DATA || t === RESOLVED) {\n\t\t\tthis._depDirtyBits.add(index);\n\t\t\tthis._depSettledBits.add(index);\n\t\t} else if (t === COMPLETE) {\n\t\t\tthis._depCompleteBits.add(index);\n\t\t\tthis._depDirtyBits.delete(index);\n\t\t\tthis._depSettledBits.delete(index);\n\t\t}\n\t}\n\n\tprivate _allDirtySettled(): boolean {\n\t\tif (this._depDirtyBits.size === 0) return false;\n\t\tfor (const idx of this._depDirtyBits) {\n\t\t\tif (!this._depSettledBits.has(idx)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * True if any current dep value differs from what the last `_runFn`\n\t * saw via `get()`. Used to suppress redundant re-runs when deferred\n\t * handshake messages arrive after `_rewire` for a dep whose value\n\t * already matches `_trackedValues`.\n\t */\n\tprivate _depValuesDifferFromTracked(): boolean {\n\t\tfor (const dep of this._deps) {\n\t\t\tconst current = dep.get();\n\t\t\tconst tracked = this._trackedValues.get(dep);\n\t\t\tif (!this._equals(current, tracked)) return true;\n\t\t}\n\t\treturn false;\n\t}\n}\n","import type { Actor } from \"./actor.js\";\nimport { DynamicNodeImpl } from \"./dynamic-node.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { NO_VALUE, type Node, NodeImpl } from \"./node.js\";\n\n/** JSON-shaped slice of a node for Phase 1 `Graph.describe()` (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type DescribeNodeOutput = {\n\ttype: \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\tstatus?: Node[\"status\"];\n\tdeps: string[];\n\tmeta?: Record<string, unknown>;\n\tname?: string;\n\tvalue?: unknown;\n\t/** True when the node has never received or been initialized with a value (cache holds SENTINEL). */\n\tsentinel?: boolean;\n\t/** Node versioning info (GRAPHREFLY-SPEC §7). Present only when versioning is enabled. */\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\n\t/** Guard info (full detail). */\n\tguard?: string;\n\t/** Last mutation attribution (full detail). */\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n};\n\n/**\n * Detail level for `describe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — type + deps only (default). LLM-friendly.\n * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`).\n * - `\"full\"` — standard + guard, lastMutation.\n */\nexport type DescribeDetail = \"minimal\" | \"standard\" | \"full\";\n\n/**\n * Valid field names for `describe({ fields: [...] })` (Phase 3.3b).\n * Dotted paths like `\"meta.label\"` select specific meta keys.\n */\nexport type DescribeField =\n\t| \"type\"\n\t| \"status\"\n\t| \"value\"\n\t| \"deps\"\n\t| \"meta\"\n\t| \"v\"\n\t| \"guard\"\n\t| \"lastMutation\"\n\t| `meta.${string}`;\n\n/** Resolve which fields to include based on detail level or explicit field list. */\nexport function resolveDescribeFields(\n\tdetail?: DescribeDetail,\n\tfields?: readonly DescribeField[],\n): Set<string> | null {\n\t// Explicit fields override detail level\n\tif (fields != null && fields.length > 0) return new Set(fields);\n\tswitch (detail) {\n\t\tcase \"standard\":\n\t\t\treturn new Set([\"type\", \"status\", \"value\", \"deps\", \"meta\", \"v\"]);\n\t\tcase \"full\":\n\t\t\treturn null; // null = include everything\n\t\tdefault:\n\t\t\treturn new Set([\"type\", \"deps\"]);\n\t}\n}\n\nfunction inferDescribeType(n: NodeImpl): DescribeNodeOutput[\"type\"] {\n\tif (n._describeKind != null) return n._describeKind;\n\tif (!n._hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\tif (n._fn == null) return \"derived\";\n\tif (n._manualEmitUsed) return \"operator\";\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON (GRAPHREFLY-SPEC §2.3, §3.6).\n *\n * @remarks\n * Values come from {@link Node.get}, which returns the **last settled** cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status` when\n * freshness matters. Avoid calling mid-batch for the same reason.\n *\n * Meta nodes are **not** terminated when their parent receives COMPLETE or\n * ERROR — they remain writable so callers can record post-mortem metadata\n * (e.g. `meta.error`). They *are* torn down when the parent receives TEARDOWN.\n *\n * @param node - The node whose meta fields to snapshot.\n * @returns Plain object of `{ key: value }` pairs (empty if no meta defined).\n * Keys whose companion node's {@link Node.get} throws are omitted.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = core.node({ initial: 0, meta: { tag: \"a\" } });\n * core.metaSnapshot(n); // { tag: \"a\" }\n * ```\n */\n/** @internal Used by {@link describeNode} — not part of the public API. */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.get();\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta` snapshot).\n * Parity with graphrefly-py `describe_node`.\n *\n * `type` is inferred from factory configuration, optional `describeKind` in node options,\n * and the last `manualEmitUsed` hint (operator vs derived). {@link effect} sets\n * `describeKind: \"effect\"`. Nodes not created by {@link node} fall back to `type: \"state\"` and empty `deps`.\n *\n * @param node - Any `Node` to introspect.\n * @returns `DescribeNodeOutput` suitable for merging into graph describe maps.\n *\n * @example\n * ```ts\n * import { describeNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * describeNode(state(0));\n * ```\n */\n/**\n * Builds a single-node slice for `Graph.describe()`.\n *\n * @param node - Node to introspect.\n * @param includeFields - Set of fields to include, or `null` for all. When omitted, all fields are included (legacy behavior).\n */\n/** @internal Used by {@link Graph.describe} — not part of the public API. */\nexport function describeNode(node: Node, includeFields?: Set<string> | null): DescribeNodeOutput {\n\tconst all = includeFields == null; // null or undefined → include everything\n\n\t// Specific meta keys requested via dotted paths (e.g. \"meta.label\")\n\tconst metaKeys: string[] | null =\n\t\t!all && includeFields != null\n\t\t\t? [...includeFields].filter((f) => f.startsWith(\"meta.\")).map((f) => f.slice(5))\n\t\t\t: null;\n\tconst wantsMeta = all || includeFields!.has(\"meta\") || (metaKeys != null && metaKeys.length > 0);\n\n\tlet type: DescribeNodeOutput[\"type\"] = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.name ?? \"\");\n\t} else if (node instanceof DynamicNodeImpl) {\n\t\ttype = node._describeKind ?? \"derived\";\n\t\tdeps = [];\n\t}\n\n\tconst out: DescribeNodeOutput = { type, deps };\n\n\t// status\n\tif (all || includeFields!.has(\"status\")) {\n\t\tout.status = node.status;\n\t}\n\n\t// Resolve guard once — used by both meta.access hint and standalone guard field\n\tconst guard =\n\t\t(node instanceof NodeImpl && node._guard) ||\n\t\t(node instanceof DynamicNodeImpl && node._guard) ||\n\t\tundefined;\n\n\t// meta\n\tif (wantsMeta) {\n\t\tconst rawMeta: Record<string, unknown> = { ...metaSnapshot(node) };\n\t\tif (guard != null && rawMeta.access === undefined) {\n\t\t\trawMeta.access = accessHintForGuard(guard);\n\t\t}\n\n\t\tif (metaKeys != null && metaKeys.length > 0 && !includeFields!.has(\"meta\")) {\n\t\t\t// Only specific meta keys\n\t\t\tconst filtered: Record<string, unknown> = {};\n\t\t\tfor (const k of metaKeys) {\n\t\t\t\tif (k in rawMeta) filtered[k] = rawMeta[k];\n\t\t\t}\n\t\t\tout.meta = filtered;\n\t\t} else {\n\t\t\tout.meta = rawMeta;\n\t\t}\n\t}\n\n\t// name (always include when present — it's identity, not detail)\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\t// value + sentinel indicator\n\tif (all || includeFields!.has(\"value\")) {\n\t\tconst isSentinel =\n\t\t\t(node instanceof NodeImpl && node._cached === NO_VALUE) ||\n\t\t\t(node instanceof DynamicNodeImpl && node._cached === NO_VALUE);\n\t\tif (isSentinel) {\n\t\t\tout.sentinel = true;\n\t\t}\n\t\ttry {\n\t\t\tout.value = node.get();\n\t\t} catch {\n\t\t\t/* omit value */\n\t\t}\n\t}\n\n\t// Versioning (GRAPHREFLY-SPEC §7)\n\tif ((all || includeFields!.has(\"v\")) && node.v != null) {\n\t\tconst vInfo: DescribeNodeOutput[\"v\"] = { id: node.v.id, version: node.v.version };\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo!.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo!.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\t// Guard info (full detail)\n\tif (all || includeFields!.has(\"guard\")) {\n\t\tif (guard != null) {\n\t\t\tout.guard = accessHintForGuard(guard);\n\t\t}\n\t}\n\n\t// Last mutation attribution (full detail)\n\tif (all || includeFields!.has(\"lastMutation\")) {\n\t\tif (node.lastMutation != null) {\n\t\t\tout.lastMutation = node.lastMutation;\n\t\t}\n\t}\n\n\treturn out;\n}\n","import { type Node, type NodeFn, type NodeOptions, node } from \"./node.js\";\n\n/**\n * Creates a manual source with no upstream deps. Emit values with {@link Node.down}.\n *\n * Spec: `state(initial, opts?)` is `node([], { initial, ...opts })` (GRAPHREFLY-SPEC §2.7).\n *\n * @param initial - Initial cached value. Because `initial` is provided, `equals` is\n * called on the first {@link Node.down | down()} emission — if the value matches\n * `initial`, the node emits `RESOLVED` instead of `DATA` (spec §2.5).\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n * @returns `Node<T>` - Stateful node you drive imperatively.\n *\n * @example\n * ```ts\n * import { DATA, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(0);\n * n.down([[DATA, 1]]);\n * ```\n *\n * @category core\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n/**\n * Creates a producer node with no deps; `fn` runs when the first subscriber connects.\n *\n * @param fn - Receives deps (empty) and {@link NodeActions}; use `emit` / `down` to push.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Producer node.\n *\n * @example\n * ```ts\n * import { producer } from \"@graphrefly/graphrefly-ts\";\n *\n * const tick = producer((_d, a) => {\n * a.emit(1);\n * });\n * ```\n *\n * @category core\n */\nexport function producer<T = unknown>(fn: NodeFn<T>, opts?: NodeOptions): Node<T> {\n\treturn node<T>(fn, { describeKind: \"producer\", ...opts });\n}\n\n/**\n * Creates a derived node from dependencies and a compute function (same primitive as operators).\n *\n * @param deps - Upstream nodes.\n * @param fn - Compute function; return value is emitted, or use `actions` explicitly.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Derived node.\n *\n * @example\n * ```ts\n * import { derived, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n *\n * @category core\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: NodeFn<T>,\n\topts?: NodeOptions,\n): Node<T> {\n\treturn node<T>(deps, fn, { describeKind: \"derived\", ...opts });\n}\n\n/**\n * Runs a side-effect when deps settle; return value is not auto-emitted.\n *\n * @param deps - Nodes to watch.\n * @param fn - Side-effect body.\n * @returns `Node<unknown>` - Effect node.\n *\n * @example\n * ```ts\n * import { effect, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(1);\n * effect([n], ([v]) => {\n * console.log(v);\n * });\n * ```\n *\n * @category core\n */\nexport function effect(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","/**\n * Creates a resettable deadline timer for internal timeout, retry, and rate-limiting use.\n *\n * @remarks **Centralised primitive:** wraps `setTimeout`/`clearTimeout` with a generation guard\n * so that stale callbacks never fire after `cancel()` or a new `start()`.\n *\n * @remarks **Spec §5.10 exception:** resilience operators (`timeout`, `retry`, `rateLimiter`)\n * need raw timers — `fromTimer` creates a new Node per reset, which is too heavy here.\n *\n * @example\n * ```ts\n * import { ResettableTimer } from \"@graphrefly/graphrefly-ts\";\n *\n * const timer = new ResettableTimer();\n * timer.start(1000, () => console.log(\"fired\"));\n * timer.cancel(); // cancels before firing\n * timer.start(500, () => console.log(\"new deadline\"));\n * console.log(timer.pending); // true\n * ```\n *\n * @category core\n */\nexport class ResettableTimer {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _gen = 0;\n\n\t/** Schedule callback after delayMs. Cancels any pending timer. */\n\tstart(delayMs: number, callback: () => void): void {\n\t\tthis.cancel();\n\t\tthis._gen += 1;\n\t\tconst gen = this._gen;\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tif (gen !== this._gen) return;\n\t\t\tcallback();\n\t\t}, delayMs);\n\t}\n\n\t/** Cancel the pending timer (if any). */\n\tcancel(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\t/** Whether a timer is currently pending. */\n\tget pending(): boolean {\n\t\treturn this._timer !== undefined;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACWO,IAAM,gBAAuB,EAAE,MAAM,UAAU,IAAI,GAAG;AAetD,SAAS,eAAe,OAAsB;AACpD,MAAI,SAAS,KAAM,QAAO;AAC1B,QAAM,EAAE,MAAM,IAAI,GAAG,KAAK,IAAI;AAC9B,SAAO;AAAA,IACN,MAAM,QAAQ;AAAA,IACd,IAAI,MAAM;AAAA,IACV,GAAG;AAAA,EACJ;AACD;;;ACeO,IAAM,QAAQ,uBAAO,IAAI,kBAAkB;AAE3C,IAAM,OAAO,uBAAO,IAAI,iBAAiB;AAEzC,IAAM,QAAQ,uBAAO,IAAI,kBAAkB;AAE3C,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAEjD,IAAM,aAAa,uBAAO,IAAI,uBAAuB;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