@graphrefly/graphrefly 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +234 -0
- package/dist/chunk-5X3LAO3B.js +1571 -0
- package/dist/chunk-5X3LAO3B.js.map +1 -0
- package/dist/chunk-6W5SGIGB.js +1793 -0
- package/dist/chunk-6W5SGIGB.js.map +1 -0
- package/dist/chunk-CP6MNKAA.js +97 -0
- package/dist/chunk-CP6MNKAA.js.map +1 -0
- package/dist/chunk-HP7OKEOE.js +107 -0
- package/dist/chunk-HP7OKEOE.js.map +1 -0
- package/dist/chunk-KWXPDASV.js +781 -0
- package/dist/chunk-KWXPDASV.js.map +1 -0
- package/dist/chunk-O3PI7W45.js +68 -0
- package/dist/chunk-O3PI7W45.js.map +1 -0
- package/dist/chunk-QW7H3ICI.js +1372 -0
- package/dist/chunk-QW7H3ICI.js.map +1 -0
- package/dist/chunk-VPS7L64N.js +4785 -0
- package/dist/chunk-VPS7L64N.js.map +1 -0
- package/dist/chunk-Z4Y4FMQN.js +1097 -0
- package/dist/chunk-Z4Y4FMQN.js.map +1 -0
- package/dist/compat/nestjs/index.cjs +4883 -0
- package/dist/compat/nestjs/index.cjs.map +1 -0
- package/dist/compat/nestjs/index.d.cts +7 -0
- package/dist/compat/nestjs/index.d.ts +7 -0
- package/dist/compat/nestjs/index.js +84 -0
- package/dist/compat/nestjs/index.js.map +1 -0
- package/dist/core/index.cjs +1632 -0
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.cts +2 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +90 -0
- package/dist/core/index.js.map +1 -0
- package/dist/extra/index.cjs +6885 -0
- package/dist/extra/index.cjs.map +1 -0
- package/dist/extra/index.d.cts +5 -0
- package/dist/extra/index.d.ts +5 -0
- package/dist/extra/index.js +290 -0
- package/dist/extra/index.js.map +1 -0
- package/dist/graph/index.cjs +3225 -0
- package/dist/graph/index.cjs.map +1 -0
- package/dist/graph/index.d.cts +3 -0
- package/dist/graph/index.d.ts +3 -0
- package/dist/graph/index.js +25 -0
- package/dist/graph/index.js.map +1 -0
- package/dist/graph-CL_ZDAj9.d.cts +605 -0
- package/dist/graph-D18qmsNm.d.ts +605 -0
- package/dist/index-B6SsZs2h.d.cts +3463 -0
- package/dist/index-B7eOdgEx.d.ts +449 -0
- package/dist/index-BHUvlQ3v.d.ts +3463 -0
- package/dist/index-BtK55IE2.d.ts +231 -0
- package/dist/index-BvhgZRHK.d.cts +231 -0
- package/dist/index-Bvy_6CaN.d.ts +452 -0
- package/dist/index-C3BMRmmp.d.cts +449 -0
- package/dist/index-C5mqLhMX.d.cts +452 -0
- package/dist/index-CP_QvbWu.d.ts +940 -0
- package/dist/index-D_geH2Bm.d.cts +940 -0
- package/dist/index.cjs +14843 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1517 -0
- package/dist/index.d.ts +1517 -0
- package/dist/index.js +3649 -0
- package/dist/index.js.map +1 -0
- package/dist/meta-BsF6Sag9.d.cts +607 -0
- package/dist/meta-BsF6Sag9.d.ts +607 -0
- package/dist/patterns/reactive-layout/index.cjs +4143 -0
- package/dist/patterns/reactive-layout/index.cjs.map +1 -0
- package/dist/patterns/reactive-layout/index.d.cts +3 -0
- package/dist/patterns/reactive-layout/index.d.ts +3 -0
- package/dist/patterns/reactive-layout/index.js +38 -0
- package/dist/patterns/reactive-layout/index.js.map +1 -0
- package/dist/reactive-log-BfvfNWQh.d.cts +137 -0
- package/dist/reactive-log-ohLmTXoZ.d.ts +137 -0
- package/package.json +256 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/compat/index.ts","../src/compat/jotai/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/dynamic-node.ts","../src/core/sugar.ts","../src/compat/nanostores/index.ts","../src/compat/nestjs/index.ts","../src/extra/observable.ts","../src/compat/nestjs/decorators.ts","../src/compat/nestjs/tokens.ts","../src/extra/sources.ts","../src/extra/cron.ts","../src/compat/nestjs/explorer.ts","../src/extra/backpressure.ts","../src/compat/nestjs/gateway.ts","../src/compat/nestjs/guard.ts","../src/compat/nestjs/module.ts","../src/core/meta.ts","../src/graph/graph.ts","../src/patterns/cqrs.ts","../src/core/index.ts","../src/extra/reactive-base.ts","../src/extra/reactive-log.ts","../src/graph/index.ts","../src/graph/codec.ts","../src/compat/react/index.ts","../src/compat/signals/index.ts","../src/compat/solid/index.ts","../src/compat/svelte/index.ts","../src/compat/vue/index.ts","../src/compat/zustand/index.ts","../src/extra/index.ts","../src/extra/backoff.ts","../src/extra/resilience.ts","../src/extra/adapters.ts","../src/extra/checkpoint.ts","../src/extra/operators.ts","../src/extra/reactive-map.ts","../src/extra/composite.ts","../src/extra/pubsub.ts","../src/extra/reactive-index.ts","../src/extra/reactive-list.ts","../src/extra/worker/protocol.ts","../src/extra/worker/transport.ts","../src/extra/worker/bridge.ts","../src/extra/worker/self.ts","../src/patterns/index.ts","../src/patterns/ai.ts","../src/patterns/memory.ts","../src/patterns/messaging.ts","../src/patterns/orchestration.ts","../src/patterns/reactive-layout/index.ts","../src/patterns/reactive-layout/measurement-adapters.ts","../src/patterns/reactive-layout/reactive-layout.ts","../src/patterns/reactive-layout/reactive-block-layout.ts"],"sourcesContent":["/**\n * GraphRefly — public API surface.\n */\nexport const version = \"0.0.0\";\n\nexport * from \"./compat/index.js\";\nexport * as compat from \"./compat/index.js\";\n// Named re-exports enable finer-grained tree-shaking for consumers.\nexport * from \"./core/index.js\";\n// Keep namespace exports for ergonomic grouped imports.\nexport * as core from \"./core/index.js\";\nexport * from \"./extra/index.js\";\nexport * as extra from \"./extra/index.js\";\nexport * from \"./graph/index.js\";\nexport * as graph from \"./graph/index.js\";\nexport * from \"./patterns/index.js\";\nexport * as patterns from \"./patterns/index.js\";\n","/**\n * Compat layer: compatibility wrappers for other state management libraries (Phase 5.1b).\n *\n * Framework adapters are optional peers. Install only what you use:\n * - `@graphrefly/graphrefly-ts/compat/react` -> `react`, `react-dom`\n * - `@graphrefly/graphrefly-ts/compat/vue` -> `vue`\n * - `@graphrefly/graphrefly-ts/compat/svelte` -> `svelte`\n * - `@graphrefly/graphrefly-ts/compat/solid` -> `solid-js`\n */\nexport * as jotai from \"./jotai/index.js\";\nexport * as nanostores from \"./nanostores/index.js\";\nexport * as nestjs from \"./nestjs/index.js\";\nexport * as react from \"./react/index.js\";\nexport * as signals from \"./signals/index.js\";\nexport * as solid from \"./solid/index.js\";\nexport * as svelte from \"./svelte/index.js\";\nexport * as vue from \"./vue/index.js\";\nexport * as zustand from \"./zustand/index.js\";\n","import { dynamicNode } from \"../../core/dynamic-node.js\";\nimport { DATA, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { state } from \"../../core/sugar.js\";\n\n/**\n * Options for creating an atom.\n *\n * @category compat\n */\nexport interface AtomOptions {\n\t/** Optional identifier for the underlying node. */\n\tname?: string;\n\t/** Optional companion meta nodes. */\n\tmeta?: Record<string, unknown>;\n}\n\n/**\n * A read-only Jotai-compatible atom.\n *\n * @category compat\n */\nexport interface ReadableAtom<T> {\n\t/** Returns the current cached value. */\n\tget(): T;\n\t/** Subscribes to value changes. Returns an unsubscribe function. */\n\tsubscribe(callback: (value: T) => void): () => void;\n\t/** Access to companion meta nodes. */\n\treadonly meta: Record<string, Node>;\n\t/** @internal The underlying GraphReFly node. */\n\t_node: Node<T>;\n}\n\n/**\n * A writable Jotai-compatible atom.\n *\n * @category compat\n */\nexport interface WritableAtom<T> extends ReadableAtom<T> {\n\t/** Sets a new value. */\n\tset(value: T): void;\n\t/** Updates the value using a transformation function. */\n\tupdate(fn: (current: T) => T): void;\n}\n\n/** Function type for reading other atoms inside a derived atom. */\nexport type GetFn = <V>(a: ReadableAtom<V>) => V;\n/** Function type for writing to other atoms inside a writable derived atom. */\nexport type SetFn = <V>(a: WritableAtom<V>, value: V) => void;\n\n/** Function that computes the atom's value. */\nexport type ReadFn<T> = (get: GetFn) => T;\n/** Function that handles writes to the atom. */\nexport type WriteFn<T> = (get: GetFn, set: SetFn, value: T) => void;\n\n/**\n * Creates a Jotai-compatible atom built on GraphReFly primitives.\n *\n * Supports three overloads:\n * 1. `atom(initial)` — Writable primitive atom (wraps `state()`).\n * 2. `atom(read)` — Read-only derived atom (wraps `dynamicNode()`).\n * 3. `atom(read, write)` — Writable derived atom.\n *\n * @param initialOrRead - Initial value or a read function.\n * @param writeOrOptions - Write function or options object.\n * @param options - Optional configuration.\n * @returns WritableAtom or ReadableAtom.\n *\n * @example\n * ```ts\n * const count = atom(0);\n * count.set(1);\n * const doubled = atom((get) => get(count)! * 2);\n * ```\n *\n * @category compat\n */\nexport function atom<T>(initial: T, options?: AtomOptions): WritableAtom<T>;\nexport function atom<T>(read: ReadFn<T>, options?: AtomOptions): ReadableAtom<T>;\nexport function atom<T>(read: ReadFn<T>, write: WriteFn<T>, options?: AtomOptions): WritableAtom<T>;\nexport function atom<T>(\n\tinitialOrRead: T | ReadFn<T>,\n\twriteOrOptions?: WriteFn<T> | AtomOptions,\n\toptions?: AtomOptions,\n): ReadableAtom<T> | WritableAtom<T> {\n\tif (typeof initialOrRead === \"function\") {\n\t\tconst read = initialOrRead as ReadFn<T>;\n\t\tif (typeof writeOrOptions === \"function\") {\n\t\t\treturn createDerivedAtom(read, writeOrOptions as WriteFn<T>, options);\n\t\t}\n\t\treturn createDerivedAtom(read, undefined, writeOrOptions as AtomOptions);\n\t}\n\n\treturn createPrimitiveAtom(initialOrRead as T, writeOrOptions as AtomOptions);\n}\n\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined = n.get();\n\tlet err: any;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t\tif (t === ERROR) err = v;\n\t\t}\n\t});\n\tunsub();\n\tif (err) throw err;\n\treturn val as T;\n}\n\nfunction createPrimitiveAtom<T>(initial: T, options?: AtomOptions): WritableAtom<T> {\n\tconst n = state(initial, {\n\t\t...options,\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t});\n\treturn {\n\t\tget: () => {\n\t\t\tif (n.status === \"disconnected\") {\n\t\t\t\treturn pull(n);\n\t\t\t}\n\t\t\treturn n.get() as T;\n\t\t},\n\t\tset: (value: T) => n.down([[DATA, value]]),\n\t\tupdate: (fn: (current: T) => T) => {\n\t\t\tconst current = n.status === \"disconnected\" ? pull(n) : (n.get() as T);\n\t\t\tn.down([[DATA, fn(current)]]);\n\t\t},\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\treturn n.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) cb(v as T);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tmeta: n.meta,\n\t\t_node: n,\n\t};\n}\n\nfunction createDerivedAtom<T>(\n\tread: ReadFn<T>,\n\twrite?: WriteFn<T>,\n\toptions?: AtomOptions,\n): ReadableAtom<T> | WritableAtom<T> {\n\tconst n = dynamicNode(\n\t\t(get) =>\n\t\t\tread(<V>(a: ReadableAtom<V>) => {\n\t\t\t\tconst dn = a._node;\n\t\t\t\tif (dn.status === \"disconnected\") {\n\t\t\t\t\tpull(dn);\n\t\t\t\t}\n\t\t\t\treturn get(dn) as V;\n\t\t\t}),\n\t\t{\n\t\t\t...options,\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t},\n\t);\n\n\tconst result: ReadableAtom<T> = {\n\t\tget: () => {\n\t\t\tif (n.status === \"disconnected\") {\n\t\t\t\treturn pull(n);\n\t\t\t}\n\t\t\treturn n.get() as T;\n\t\t},\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\treturn n.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) cb(v as T);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tmeta: n.meta,\n\t\t_node: n,\n\t};\n\n\tif (write) {\n\t\tconst getFn: GetFn = <V>(a: ReadableAtom<V>) => a.get();\n\t\tconst setFn: SetFn = <V>(a: WritableAtom<V>, value: V) => a.set(value);\n\n\t\tconst writable = result as WritableAtom<T>;\n\t\twritable.set = (value: T) => write(getFn, setFn, value);\n\t\twritable.update = (fn: (current: T) => T) => {\n\t\t\tconst current = n.status === \"disconnected\" ? pull(n) : (n.get() as T);\n\t\t\treturn write(getFn, setFn, fn(current));\n\t\t};\n\t\treturn writable;\n\t}\n\n\treturn result;\n}\n","/**\n * Who is performing an operation (attribution + ABAC input).\n *\n * @see GRAPHREFLY-SPEC — roadmap Phase 1.5 (Actor & Guard).\n */\nexport type Actor = {\n\ttype: \"human\" | \"llm\" | \"wallet\" | \"system\" | string;\n\tid: string;\n} & Record<string, unknown>;\n\n/** Default actor when none is passed ({@link normalizeActor}). */\nexport const DEFAULT_ACTOR: Actor = { type: \"system\", id: \"\" };\n\n/**\n * Fills missing `type` / `id` on an actor and returns {@link DEFAULT_ACTOR} when input is undefined.\n *\n * @param actor - Optional partial actor from a transport hint.\n * @returns A normalized `Actor` safe to pass to guards and graph APIs.\n *\n * @example\n * ```ts\n * import { normalizeActor } from \"@graphrefly/graphrefly-ts\";\n *\n * normalizeActor({ type: \"human\", id: \"u1\" });\n * ```\n */\nexport function normalizeActor(actor?: Actor): Actor {\n\tif (actor == null) return DEFAULT_ACTOR;\n\tconst { type, id, ...rest } = actor;\n\treturn {\n\t\ttype: type ?? \"system\",\n\t\tid: id ?? \"\",\n\t\t...rest,\n\t} as Actor;\n}\n","/**\n * GraphReFly message protocol — §1 `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n * Emissions are always `[[Type, Data?], ...]` (no single-tuple shorthand).\n *\n * ## Canonical message ordering (within a composite batch)\n *\n * When multiple message types appear in a single `down()` call, the canonical\n * delivery order is determined by **signal tier**:\n *\n * | Tier | Signals | Role | Batch behavior |\n * |------|------------------------|-------------------|-------------------------------------|\n * | 0 | DIRTY, INVALIDATE | Notification | Immediate (never deferred) |\n * | 1 | PAUSE, RESUME | Flow control | Immediate (never deferred) |\n * | 2 | DATA, RESOLVED | Value settlement | Deferred inside `batch()` |\n * | 3 | COMPLETE, ERROR | Terminal lifecycle | Deferred to after phase-2 |\n * | 4 | TEARDOWN | Destruction | Immediate (usually sent alone) |\n *\n * **Rule:** Within `emitWithBatch`, messages are partitioned by tier and delivered\n * in tier order. This ensures phase-2 values (DATA/RESOLVED) reach sinks before\n * terminal signals (COMPLETE/ERROR) mark the node as done, preventing the\n * \"COMPLETE-before-DATA\" class of bugs. Sources that emit in canonical order\n * naturally partition correctly with zero overhead.\n *\n * Unknown message types (forward-compat) are tier 0 (immediate).\n *\n * ## Meta node bypass rules (centralized — GRAPHREFLY-SPEC §2.3)\n *\n * - **INVALIDATE** via `graph.signal()` — no-op on meta nodes (cached values preserved).\n * - **COMPLETE / ERROR** — not propagated from parent to meta (meta outlives terminal\n * state for post-mortem writes like setting `meta.error` after ERROR).\n * - **TEARDOWN** — propagated from parent to meta, releasing meta resources.\n */\n\n/** Value delivery (`DATA`, value). Tier 2 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 0 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 2 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 0 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 1 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 1 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 4 — immediate (usually sent alone). */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 3 — delivered after phase-2 in the same batch. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 3 — delivered after phase-2 in the same batch. */\nexport const ERROR = Symbol.for(\"graphrefly/ERROR\");\n\n/** Known protocol type symbols (open set — other symbols are valid and forward). */\nexport const knownMessageTypes: readonly symbol[] = [\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tINVALIDATE,\n\tPAUSE,\n\tRESUME,\n\tTEARDOWN,\n\tCOMPLETE,\n\tERROR,\n];\n\n/** One protocol tuple: `[Type, optional payload]`. */\nexport type Message = readonly [symbol, unknown?];\n\n/**\n * A batch of tuples — the wire shape for `node.down()` / `node.up()`.\n */\nexport type Messages = readonly Message[];\n\n/**\n * Whether `t` is one of the built-in protocol symbols in this module.\n *\n * @param t — Message type symbol (unknown types are still valid; they must forward).\n * @returns `true` for `DATA`, `DIRTY`, `RESOLVED`, etc.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, isKnownMessageType } from \"@graphrefly/graphrefly-ts\";\n *\n * isKnownMessageType(DATA); // true\n * isKnownMessageType(Symbol(\"custom\")); // false\n * ```\n */\nexport function isKnownMessageType(t: symbol): boolean {\n\treturn knownMessageTypes.includes(t);\n}\n\n/**\n * Returns the signal tier for a message type (see module-level ordering table).\n *\n * - 0: notification (DIRTY, INVALIDATE) — immediate\n * - 1: flow control (PAUSE, RESUME) — immediate\n * - 2: value (DATA, RESOLVED) — deferred inside `batch()`\n * - 3: terminal (COMPLETE, ERROR) — delivered after phase-2\n * - 4: destruction (TEARDOWN) — immediate, usually alone\n * - 0 for unknown types (forward-compat: immediate)\n *\n * @param t — Message type symbol.\n * @returns Tier number (0–4).\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, TEARDOWN, messageTier } from \"@graphrefly/graphrefly-ts\";\n *\n * messageTier(DIRTY); // 0\n * messageTier(DATA); // 2\n * messageTier(COMPLETE); // 3\n * messageTier(TEARDOWN); // 4\n * ```\n */\nexport function messageTier(t: symbol): number {\n\tif (t === DIRTY || t === INVALIDATE) return 0;\n\tif (t === PAUSE || t === RESUME) return 1;\n\tif (t === DATA || t === RESOLVED) return 2;\n\tif (t === COMPLETE || t === ERROR) return 3;\n\tif (t === TEARDOWN) return 4;\n\treturn 0; // unknown → immediate\n}\n\n/**\n * Returns whether this tuple is deferred by `batch()` (phase 2: `DATA` or `RESOLVED`).\n *\n * @param msg — Single message tuple.\n * @returns `true` if `msg` is `DATA` or `RESOLVED`.\n *\n * @example\n * ```ts\n * import { DATA, RESOLVED, DIRTY, isPhase2Message } from \"@graphrefly/graphrefly-ts\";\n *\n * isPhase2Message([DATA, 42]); // true\n * isPhase2Message([RESOLVED]); // true\n * isPhase2Message([DIRTY]); // false\n * ```\n */\nexport function isPhase2Message(msg: Message): boolean {\n\tconst t = msg[0];\n\treturn t === DATA || t === RESOLVED;\n}\n\n/**\n * Returns whether this message type is terminal (COMPLETE or ERROR).\n * Terminal messages are delivered after phase-2 in the same batch to prevent\n * the node from becoming terminal before value messages reach sinks.\n *\n * @param t — Message type symbol.\n * @returns `true` for `COMPLETE` or `ERROR`.\n *\n * @example\n * ```ts\n * import { COMPLETE, ERROR, DATA, isTerminalMessage } from \"@graphrefly/graphrefly-ts\";\n *\n * isTerminalMessage(COMPLETE); // true\n * isTerminalMessage(ERROR); // true\n * isTerminalMessage(DATA); // false\n * ```\n */\nexport function isTerminalMessage(t: symbol): boolean {\n\treturn t === COMPLETE || t === ERROR;\n}\n\n/**\n * Whether `t` should be propagated from a parent node to its companion meta nodes.\n * Only TEARDOWN propagates; COMPLETE/ERROR/INVALIDATE do not (meta outlives parent\n * terminal state for post-mortem writes).\n *\n * @param t — Message type symbol.\n * @returns `true` if the signal should reach meta nodes.\n *\n * @example\n * ```ts\n * import { TEARDOWN, COMPLETE, ERROR, propagatesToMeta } from \"@graphrefly/graphrefly-ts\";\n *\n * propagatesToMeta(TEARDOWN); // true\n * propagatesToMeta(COMPLETE); // false\n * propagatesToMeta(ERROR); // false\n * ```\n */\nexport function propagatesToMeta(t: symbol): boolean {\n\treturn t === TEARDOWN;\n}\n","import {\n\tDATA,\n\tisPhase2Message,\n\tisTerminalMessage,\n\ttype Message,\n\ttype Messages,\n\tRESOLVED,\n} from \"./messages.js\";\n\n/**\n * §1.3.7 — Inside a batch, DIRTY propagates immediately; DATA and RESOLVED are\n * deferred until the outermost `batch()` callback returns. Terminal signals\n * (COMPLETE, ERROR) are delivered after phase-2 messages in the same batch\n * (see canonical ordering in `messages.ts`).\n */\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\nconst pendingPhase2: Array<() => void> = [];\nconst pendingPhase3: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * deferred phase-2 work is draining.\n *\n * Matching Python's `is_batching()` semantics: nested emissions during drain\n * are deferred until the current drain pass completes, preventing ordering\n * bugs when callbacks trigger further DATA/RESOLVED.\n *\n * @returns `true` while inside `batch()` or while the drain loop is running.\n *\n * @example\n * ```ts\n * import { batch, isBatching } from \"@graphrefly/graphrefly-ts\";\n *\n * batch(() => {\n * console.log(isBatching()); // true\n * });\n * ```\n *\n * @category core\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral queue.\n * If `fn` throws (including from a nested `batch`), deferred DATA/RESOLVED for\n * that **outer** `batch` frame are discarded — phase-2 is not flushed after an\n * error. While the drain loop is running (`flushInProgress`), a nested `batch`\n * that throws must **not** clear the global queue (cross-language decision A4).\n *\n * During the drain loop, `isBatching()` remains true so nested `emitWithBatch`\n * calls still defer phase-2 messages. The drain loop runs until the queue is\n * quiescent (no pending work remains). Per-emission try/catch ensures one\n * throwing callback does not orphan remaining emissions; the first error is\n * re-thrown after all emissions drain. Callbacks that ran before the throw may\n * have applied phase-2 — partial graph state is intentional (decision C1).\n *\n * @param fn — Synchronous work that may call `emitWithBatch` / `node.down()`.\n * @returns `void` — all side-effects happen through `emitWithBatch` and the\n * phase-2 drain that runs after `fn` returns.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.batch(() => {\n * core.emitWithBatch(sink, [[core.DATA, 1]]);\n * });\n * ```\n *\n * @category core\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\t// Do not wipe the outer drain's queue (decision A4).\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) {\n\t\tflushInProgress = true;\n\t}\n\tlet firstError: unknown;\n\tlet hasError = false;\n\ttry {\n\t\tlet iterations = 0;\n\t\t// Drain phase-2 first, then phase-3. If phase-3 callbacks enqueue new\n\t\t// phase-2 work, the outer loop catches it and drains phase-2 again\n\t\t// before re-entering phase-3.\n\t\twhile (pendingPhase2.length > 0 || pendingPhase3.length > 0) {\n\t\t\t// Phase-2 (DATA/RESOLVED) — parent node values settle here.\n\t\t\twhile (pendingPhase2.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase2.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (!hasError) {\n\t\t\t\t\t\t\tfirstError = e;\n\t\t\t\t\t\t\thasError = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Phase-3 — meta companion emissions that must follow parent settlement.\n\t\t\tif (pendingPhase3.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase3.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (!hasError) {\n\t\t\t\t\t\t\tfirstError = e;\n\t\t\t\t\t\t\thasError = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) {\n\t\t\tflushInProgress = false;\n\t\t}\n\t}\n\tif (hasError) {\n\t\tthrow firstError;\n\t}\n}\n\n/**\n * Splits a message array into three groups by signal tier (see `messages.ts`):\n *\n * - **immediate** — tier 0–1: DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN, unknown\n * - **deferred** — tier 2: DATA, RESOLVED (phase-2, deferred inside `batch()`)\n * - **terminal** — tier 3: COMPLETE, ERROR (delivered after phase-2)\n *\n * Order within each group is preserved.\n *\n * @param messages — One `down()` payload.\n * @returns Three groups in canonical delivery order.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, partitionForBatch } from \"@graphrefly/graphrefly-ts\";\n *\n * partitionForBatch([[DIRTY], [DATA, 1], [COMPLETE]]);\n * // { immediate: [[DIRTY]], deferred: [[DATA, 1]], terminal: [[COMPLETE]] }\n * ```\n *\n * @category core\n */\nexport function partitionForBatch(messages: Messages): {\n\timmediate: Messages;\n\tdeferred: Messages;\n\tterminal: Messages;\n} {\n\tconst immediate: Message[] = [];\n\tconst deferred: Message[] = [];\n\tconst terminal: Message[] = [];\n\tfor (const m of messages) {\n\t\tif (isPhase2Message(m)) {\n\t\t\tdeferred.push(m);\n\t\t} else if (isTerminalMessage(m[0])) {\n\t\t\tterminal.push(m);\n\t\t} else {\n\t\t\timmediate.push(m);\n\t\t}\n\t}\n\treturn { immediate, deferred, terminal };\n}\n\n/**\n * Delivers messages through `emit`, applying batch semantics and canonical\n * tier-based ordering (see `messages.ts`):\n *\n * 1. **Immediate** (tier 0–1, 4): DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN,\n * unknown — emitted synchronously.\n * 2. **Phase-2** (tier 2): DATA, RESOLVED — deferred while `isBatching()`.\n * 3. **Terminal** (tier 3): COMPLETE, ERROR — always delivered after phase-2.\n * When batching, terminal is queued after deferred phase-2 in the pending list.\n * When not batching, terminal is emitted after phase-2 synchronously.\n *\n * This ordering prevents the \"COMPLETE-before-DATA\" class of bugs: terminal\n * signals never make a node terminal before phase-2 values reach sinks,\n * regardless of how the source assembled the message array.\n *\n * @param emit — Sink callback. May be called up to three times per invocation\n * (immediate, deferred, terminal) when not batching.\n * @param messages — Full `[[Type, Data?], ...]` array for one emission.\n * @returns `void` — delivery is performed through `emit` callbacks, synchronously\n * or deferred into the active batch queue.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.emitWithBatch((msgs) => console.log(msgs), [[core.DIRTY], [core.DATA, 42]]);\n * ```\n *\n * @category core\n */\nexport function emitWithBatch(\n\temit: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n): void {\n\tif (messages.length === 0) {\n\t\treturn;\n\t}\n\tconst queue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\n\t// Fast path: single-message batches (most common in graph-internal propagation)\n\t// skip partitionForBatch allocation entirely.\n\tif (messages.length === 1) {\n\t\tconst t = messages[0][0];\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => emit(messages));\n\t\t\t} else {\n\t\t\t\temit(messages);\n\t\t\t}\n\t\t} else if (isTerminalMessage(t)) {\n\t\t\t// Terminal single message: defer when batching so any preceding\n\t\t\t// phase-2 in the queue flushes first.\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => emit(messages));\n\t\t\t} else {\n\t\t\t\temit(messages);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate: emit synchronously.\n\t\t\temit(messages);\n\t\t}\n\t\treturn;\n\t}\n\t// Multi-message: three-way partition by tier.\n\tconst { immediate, deferred, terminal } = partitionForBatch(messages);\n\n\t// 1. Immediate signals (tier 0–1, 4) — emit synchronously now.\n\tif (immediate.length > 0) {\n\t\temit(immediate);\n\t}\n\n\t// 2. Deferred (tier 2) + Terminal (tier 3) — canonical order preserved.\n\tif (isBatching()) {\n\t\tif (deferred.length > 0) {\n\t\t\tqueue.push(() => emit(deferred));\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tqueue.push(() => emit(terminal));\n\t\t}\n\t} else {\n\t\tif (deferred.length > 0) {\n\t\t\temit(deferred);\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\temit(terminal);\n\t\t}\n\t}\n}\n","/**\n * Centralised timestamp utilities.\n *\n * Convention: all graphrefly-ts timestamps use nanoseconds (`_ns` suffix).\n *\n * - {@link monotonicNs} — monotonic clock (ordering, durations, timeline events).\n * - {@link wallClockNs} — wall-clock (mutation attribution, cron emission).\n *\n * **Precision limits (JS platform):**\n *\n * - `monotonicNs`: effective ~microsecond precision. `performance.now()` returns\n * milliseconds with ~5µs resolution; the last 3 digits of the nanosecond value\n * are always zero. Python's `time.monotonic_ns()` gives true nanoseconds.\n *\n * - `wallClockNs`: ~256ns precision loss at current epoch. `Date.now() * 1e6`\n * produces values around 1.8×10¹⁸ which exceed IEEE 754's 2⁵³ safe integer\n * limit. Python's `time.time_ns()` (arbitrary-precision `int`) has no loss.\n * In practice this is irrelevant — JS is single-threaded, so sub-microsecond\n * timestamp collisions cannot occur.\n */\n\n/** Monotonic nanosecond timestamp via `performance.now()`. */\nexport function monotonicNs(): number {\n\treturn Math.trunc(performance.now() * 1_000_000);\n}\n\n/** Wall-clock nanosecond timestamp via `Date.now()`. */\nexport function wallClockNs(): number {\n\treturn Date.now() * 1_000_000;\n}\n","import type { Actor } from \"./actor.js\";\n\n/**\n * Actions checked by {@link NodeGuard}. `write` covers both {@link Node.down} and\n * {@link Node.up} today; finer-grained strings may be added later (e.g. `\"write.data\"`).\n */\nexport type GuardAction = \"write\" | \"signal\" | \"observe\" | (string & {});\n\nexport type NodeGuard = (actor: Actor, action: GuardAction) => boolean;\n\nexport type GuardDeniedDetails = {\n\tactor: Actor;\n\taction: GuardAction;\n\t/** Registry or options name when known */\n\tnodeName?: string;\n};\n\n/**\n * Thrown when a {@link NodeGuard} denies an action for a given actor.\n *\n * Carries the rejected `actor`, `action`, and optional `nodeName` for diagnostic\n * messages and middleware error handling.\n *\n * @example\n * ```ts\n * import { GuardDenied, policy } from \"@graphrefly/graphrefly-ts\";\n *\n * const guard = policy((allow) => { allow(\"observe\"); });\n * try {\n * if (!guard({ type: \"llm\", id: \"agent-1\" }, \"write\")) {\n * throw new GuardDenied(\n * { actor: { type: \"llm\", id: \"agent-1\" }, action: \"write\", nodeName: \"userInput\" },\n * );\n * }\n * } catch (e) {\n * if (e instanceof GuardDenied) console.error(e.action, e.actor.type); // \"write\" \"llm\"\n * }\n * ```\n */\nexport class GuardDenied extends Error {\n\treadonly actor: Actor;\n\treadonly action: GuardAction;\n\treadonly nodeName?: string;\n\n\t/**\n\t * @param details - Actor, action, and optional node name for the denial.\n\t * @param message - Optional override for the default error message.\n\t */\n\tconstructor(details: GuardDeniedDetails, message?: string) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\t`GuardDenied: action \"${String(details.action)}\" denied for actor type \"${String(details.actor.type)}\"`,\n\t\t);\n\t\tthis.name = \"GuardDenied\";\n\t\tthis.actor = details.actor;\n\t\tthis.action = details.action;\n\t\tthis.nodeName = details.nodeName;\n\t}\n\n\t/** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */\n\tget node(): string | undefined {\n\t\treturn this.nodeName;\n\t}\n}\n\ntype Where = (actor: Actor) => boolean;\n\ntype Rule = {\n\tkind: \"allow\" | \"deny\";\n\tactions: Set<GuardAction>;\n\twhere: Where;\n};\n\nfunction normalizeActions(action: GuardAction | readonly GuardAction[]): GuardAction[] {\n\tif (Array.isArray(action)) {\n\t\treturn [...action];\n\t}\n\treturn [action as GuardAction];\n}\n\nfunction matchesActions(set: Set<GuardAction>, action: GuardAction): boolean {\n\treturn set.has(action) || set.has(\"*\" as GuardAction);\n}\n\nexport type PolicyAllow = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyDeny = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyRuleData = {\n\teffect: \"allow\" | \"deny\";\n\taction: GuardAction | readonly GuardAction[];\n\tactorType?: string | readonly string[];\n\tactorId?: string | readonly string[];\n\tclaims?: Record<string, unknown>;\n};\n\n/**\n * Declarative guard builder. Precedence: any matching **deny** blocks even if an allow also matches.\n * If no rule matches, the guard returns `false` (deny-by-default). Aligned with graphrefly-py `policy()`.\n *\n * @param build - Callback that registers `allow(...)` / `deny(...)` rules in order.\n * @returns A `NodeGuard` for use as `node({ guard })`.\n *\n * @example\n * ```ts\n * const guard = policy((allow, deny) => {\n * allow(\"observe\");\n * deny(\"write\", { where: (a) => a.type === \"llm\" });\n * });\n * ```\n */\nexport function policy(build: (allow: PolicyAllow, deny: PolicyDeny) => void): NodeGuard {\n\tconst rules: Rule[] = [];\n\tconst allow: PolicyAllow = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"allow\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tconst deny: PolicyDeny = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"deny\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tbuild(allow, deny);\n\treturn (actor, action) => {\n\t\tlet denied = false;\n\t\tlet allowed = false;\n\t\tfor (const r of rules) {\n\t\t\tif (!matchesActions(r.actions, action)) continue;\n\t\t\tif (!r.where(actor)) continue;\n\t\t\tif (r.kind === \"deny\") {\n\t\t\t\tdenied = true;\n\t\t\t} else {\n\t\t\t\tallowed = true;\n\t\t\t}\n\t\t}\n\t\tif (denied) return false;\n\t\treturn allowed;\n\t};\n}\n\n/**\n * Rebuild a declarative guard from persisted policy data (snapshot-safe).\n *\n * Rules are deny-overrides, same semantics as {@link policy}.\n */\nexport function policyFromRules(rules: readonly PolicyRuleData[]): NodeGuard {\n\treturn policy((allow, deny) => {\n\t\tfor (const rule of rules) {\n\t\t\tconst actorTypes =\n\t\t\t\trule.actorType == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);\n\t\t\tconst actorIds =\n\t\t\t\trule.actorId == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);\n\t\t\tconst claimEntries = Object.entries(rule.claims ?? {});\n\t\t\tconst where: Where = (actor) => {\n\t\t\t\tif (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;\n\t\t\t\tif (actorIds !== null && !actorIds.has(String(actor.id ?? \"\"))) return false;\n\t\t\t\tfor (const [key, value] of claimEntries) {\n\t\t\t\t\tif ((actor as Record<string, unknown>)[key] !== value) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tif (rule.effect === \"deny\") {\n\t\t\t\tdeny(rule.action, { where });\n\t\t\t} else {\n\t\t\t\tallow(rule.action, { where });\n\t\t\t}\n\t\t}\n\t});\n}\n\nconst STANDARD_WRITE_TYPES = [\"human\", \"llm\", \"wallet\", \"system\"] as const;\n\n/**\n * Derives a best-effort `meta.access` hint string by probing `guard` with the\n * standard actor types `human`, `llm`, `wallet`, `system` for the `\"write\"` action\n * (roadmap 1.5). Aligned with graphrefly-py `access_hint_for_guard`.\n *\n * @param guard - Guard function to probe (typically from {@link policy}).\n * @returns `\"restricted\"` when no standard type is allowed; `\"both\"` when both\n * `human` and `llm` are allowed (plus optionally `system`); the single allowed\n * type name when only one passes; or a `\"+\"` joined list otherwise.\n *\n * @example\n * ```ts\n * import { policy, accessHintForGuard } from \"@graphrefly/graphrefly-ts\";\n *\n * const guardBoth = policy((allow) => { allow(\"write\"); });\n * accessHintForGuard(guardBoth); // \"both\"\n *\n * const guardHuman = policy((allow) => {\n * allow(\"write\", { where: (a) => a.type === \"human\" });\n * });\n * accessHintForGuard(guardHuman); // \"human\"\n * ```\n */\nexport function accessHintForGuard(guard: NodeGuard): string {\n\tconst allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: \"\" }, \"write\"));\n\tif (allowed.length === 0) return \"restricted\";\n\tif (\n\t\tallowed.includes(\"human\") &&\n\t\tallowed.includes(\"llm\") &&\n\t\tallowed.every((t) => t === \"human\" || t === \"llm\" || t === \"system\")\n\t) {\n\t\treturn \"both\";\n\t}\n\tif (allowed.length === 1) return allowed[0];\n\treturn allowed.join(\"+\");\n}\n","/**\n * Node versioning — GRAPHREFLY-SPEC §7.\n *\n * Progressive, optional versioning for node identity and change tracking.\n *\n * - **V0**: `id` + `version` — identity & change detection (~16 bytes overhead)\n * - **V1**: + `cid` + `prev` — content addressing & linked history (~60 bytes overhead)\n *\n * **Lifecycle notes:**\n * - Version advances only on DATA (not RESOLVED, INVALIDATE, or TEARDOWN).\n * - `resetOnTeardown` clears the cached value but does NOT reset versioning state.\n * After teardown, `v.cid` still reflects the last DATA value, not the cleared cache.\n * The invariant `hash(node.get()) === v.cid` only holds in `settled`/`resolved` status.\n * - Resubscribable nodes preserve versioning across subscription lifetimes (monotonic counter).\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** V0: identity + monotonic version counter. */\nexport type V0 = {\n\treadonly id: string;\n\tversion: number;\n};\n\n/** V1: V0 + content-addressed identifier + previous cid link. */\nexport type V1 = V0 & {\n\tcid: string;\n\tprev: string | null;\n};\n\n/** Union of all versioning info shapes. */\nexport type NodeVersionInfo = V0 | V1;\n\n/** Supported versioning levels (extensible to 2, 3 later). */\nexport type VersioningLevel = 0 | 1;\n\n/** Function that hashes a value to a hex string (for V1 cid). */\nexport type HashFn = (value: unknown) => string;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface VersioningOptions {\n\t/** Override auto-generated id. */\n\tid?: string;\n\t/** Custom hash function for V1 cid (default: SHA-256 truncated to 16 hex chars). */\n\thash?: HashFn;\n}\n\n// ---------------------------------------------------------------------------\n// Default hash\n// ---------------------------------------------------------------------------\n\n/**\n * Canonicalize a value for deterministic cross-language hashing.\n *\n * - Integer-valued floats normalize to integer strings (`1.0` → `1`).\n * - `NaN`, `Infinity`, `-Infinity` are rejected (no JSON equivalent).\n * - `undefined` normalizes to `null`.\n * - Object keys are sorted lexicographically.\n *\n * This ensures TS `JSON.stringify` and Python `json.dumps(sort_keys=True)`\n * produce identical output for the same logical value.\n */\nexport function canonicalizeForHash(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow new TypeError(`Cannot hash non-finite number: ${value}`);\n\t\t}\n\t\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. ` +\n\t\t\t\t\t\"Cross-language cid parity is not guaranteed for unsafe integers.\",\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\" || typeof value === \"boolean\" || value === null) {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalizeForHash);\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst sorted: Record<string, unknown> = {};\n\t\tfor (const k of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tsorted[k] = canonicalizeForHash((value as Record<string, unknown>)[k]);\n\t\t}\n\t\treturn sorted;\n\t}\n\t// Fallback: coerce to null (bigint, symbol, function)\n\treturn null;\n}\n\n/**\n * Default content hash: SHA-256 of deterministic JSON, truncated to 16 hex chars (~64-bit).\n * Uses {@link canonicalizeForHash} for cross-language parity with Python `default_hash`.\n */\nexport function defaultHash(value: unknown): string {\n\tconst canonical = canonicalizeForHash(value ?? null);\n\tconst json = JSON.stringify(canonical);\n\treturn createHash(\"sha256\").update(json).digest(\"hex\").slice(0, 16);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create initial versioning state for a node.\n *\n * @param level - 0 for V0, 1 for V1.\n * @param initialValue - The node's initial cached value (used for V1 cid).\n * @param opts - Optional overrides (id, hash).\n */\nexport function createVersioning(\n\tlevel: VersioningLevel,\n\tinitialValue: unknown,\n\topts?: VersioningOptions,\n): NodeVersionInfo {\n\tconst id = opts?.id ?? randomUUID();\n\tif (level === 0) {\n\t\treturn { id, version: 0 } satisfies V0;\n\t}\n\tconst hash = opts?.hash ?? defaultHash;\n\tconst cid = hash(initialValue);\n\treturn { id, version: 0, cid, prev: null } satisfies V1;\n}\n\n// ---------------------------------------------------------------------------\n// Advance\n// ---------------------------------------------------------------------------\n\n/**\n * Advance versioning state after a DATA emission (value changed).\n *\n * Mutates `info` in place for performance (called on every DATA).\n * Only call when the cached value has actually changed (not on RESOLVED).\n *\n * @param info - The node's current versioning state.\n * @param newValue - The new cached value.\n * @param hashFn - Hash function (only used for V1).\n */\nexport function advanceVersion(info: NodeVersionInfo, newValue: unknown, hashFn: HashFn): void {\n\tinfo.version += 1;\n\tif (\"cid\" in info) {\n\t\t(info as V1).prev = (info as V1).cid;\n\t\t(info as V1).cid = hashFn(newValue);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this V1 versioning info? */\nexport function isV1(info: NodeVersionInfo): info is V1 {\n\treturn \"cid\" in info;\n}\n","import type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { emitWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, NodeVersionInfo, VersioningLevel } from \"./versioning.js\";\nimport { advanceVersion, createVersioning, defaultHash } from \"./versioning.js\";\n\n/** Lifecycle status of a node. */\nexport type NodeStatus =\n\t| \"disconnected\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\n/** Callback that receives downstream message batches. */\nexport type NodeSink = (messages: Messages) => void;\n\n/**\n * Compute function passed to `node()`.\n *\n * @returns A value to emit, `undefined` to skip emission, or a cleanup\n * function invoked before the next run or on teardown.\n */\nexport type NodeFn<T = unknown> = (\n\tdeps: readonly unknown[],\n\tactions: NodeActions,\n) => T | undefined | (() => void);\n\n/** Imperative actions available inside a {@link NodeFn}. */\nexport interface NodeActions {\n\t/** Emit raw messages downstream. */\n\tdown(messages: Messages): void;\n\t/** Emit a single value (auto-wraps in DIRTY/DATA or DIRTY/RESOLVED). */\n\temit(value: unknown): void;\n\t/** Send messages upstream toward sources. */\n\tup(messages: Messages): void;\n}\n\n/**\n * Callback for intercepting messages before the default dispatch.\n *\n * Called for every message from every dep. Return `true` to consume the\n * message (skip default handling), or `false` to let default dispatch run.\n *\n * @param msg — The message tuple `[Type, Data?]`.\n * @param depIndex — Which dep sent it (index into the deps array).\n * @param actions — `{ down(), emit(), up() }` — same as `NodeFn` receives.\n */\nexport type OnMessageHandler = (msg: Message, depIndex: number, actions: NodeActions) => boolean;\n\n/**\n * Internal inspector hook (opt-in): emits dependency message and run events\n * for graph-level observability features (`observe(..., { causal|derived })`).\n */\nexport type NodeInspectorHookEvent =\n\t| { kind: \"dep_message\"; depIndex: number; message: Message }\n\t| { kind: \"run\"; depValues: readonly unknown[] };\n\nexport type NodeInspectorHook = (event: NodeInspectorHookEvent) => void;\n\n/** Explicit describe `type` for {@link Graph.describe} / {@link describeNode} (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\n/** Options for {@link node}. */\nexport interface NodeOptions {\n\tname?: string;\n\t/**\n\t * Overrides inferred `type` in describe output. Sugar constructors set this;\n\t * omit to infer from deps / fn / manual emit usage.\n\t */\n\tdescribeKind?: NodeDescribeKind;\n\t/** Equality check for RESOLVED detection. Defaults to `Object.is`. */\n\tequals?: (a: unknown, b: unknown) => boolean;\n\tinitial?: unknown;\n\t/**\n\t * Each key becomes an independently subscribable companion node.\n\t * Meta nodes outlive the parent's subscription lifecycle: when all sinks\n\t * unsubscribe the parent disconnects upstream but meta nodes stay alive.\n\t * Send `[[TEARDOWN]]` to the parent to release meta node resources.\n\t */\n\tmeta?: Record<string, unknown>;\n\t/** Allow fresh subscriptions after COMPLETE/ERROR. */\n\tresubscribable?: boolean;\n\t/**\n\t * Invoked when a new {@link Node.subscribe} clears a terminal state on a\n\t * resubscribable node — reset operator-local counters/accumulators here.\n\t */\n\tonResubscribe?: () => void;\n\t/** Clear cached value on TEARDOWN. */\n\tresetOnTeardown?: boolean;\n\t/**\n\t * When `true` (default), auto-emit `[[COMPLETE]]` when all deps complete\n\t * (spec §1.3.5). Set `false` for derived/operator nodes that should not\n\t * auto-complete.\n\t */\n\tcompleteWhenDepsComplete?: boolean;\n\t/**\n\t * Intercept messages before the default dispatch (spec §2.6).\n\t *\n\t * Return `true` to consume the message (skip default handling),\n\t * or `false` to let the default dispatch run.\n\t */\n\tonMessage?: OnMessageHandler;\n\t/**\n\t * ABAC: `(actor, action) => boolean`. `write` applies to both {@link Node.down} and {@link Node.up}.\n\t * Companion {@link NodeOptions.meta | meta} nodes inherit this guard from the primary.\n\t */\n\tguard?: NodeGuard;\n\t/**\n\t * Opt-in versioning level (GRAPHREFLY-SPEC §7).\n\t * - `0` (V0): `id` + `version` — identity & change detection.\n\t * - `1` (V1): + `cid` + `prev` — content addressing & linked history.\n\t */\n\tversioning?: VersioningLevel;\n\t/** Override auto-generated versioning id. */\n\tversioningId?: string;\n\t/** Custom hash function for V1 cid computation. */\n\tversioningHash?: HashFn;\n}\n\n/**\n * Options for {@link Node.down} / {@link Node.up} (actor context, graph delivery mode, internal bypass).\n */\nexport type NodeTransportOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips guard checks (reactive internals, graph lifecycle TEARDOWN, etc.).\n\t * Not for untrusted call sites.\n\t */\n\tinternal?: boolean;\n\t/**\n\t * `signal` for {@link Graph.signal} deliveries; default `write` for {@link Graph.set} and direct `down`.\n\t */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/**\n * Optional hints passed to {@link Node.subscribe} to enable per-sink\n * optimizations.\n */\nexport interface SubscribeHints {\n\t/**\n\t * Subscriber has exactly one dep with `fn` — the source may skip DIRTY\n\t * dispatch when this is the sole subscriber. The subscriber synthesizes\n\t * dirty state locally via `onDepSettled`.\n\t */\n\tsingleDep?: boolean;\n\t/**\n\t * Actor to check against the node's `observe` guard.\n\t * When set, `subscribe()` throws {@link GuardDenied} if the actor is not\n\t * permitted to observe this node. Aligned with graphrefly-py `subscribe(actor=)`.\n\t */\n\tactor?: Actor;\n}\n\n/** A reactive node in the GraphReFly protocol. */\nexport interface Node<T = unknown> {\n\treadonly name?: string;\n\treadonly status: NodeStatus;\n\treadonly meta: Record<string, Node>;\n\t/** Returns the current cached value. */\n\tget(): T | undefined;\n\t/** Push messages downstream. */\n\tdown(messages: Messages, options?: NodeTransportOptions): void;\n\t/**\n\t * Registers a sink to receive downstream messages.\n\t *\n\t * @param sink - Callback receiving message batches.\n\t * @param hints - Optional optimization hints (e.g. `{ singleDep: true }`).\n\t * @returns An unsubscribe function (idempotent).\n\t */\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void;\n\t/** Send messages upstream (present on nodes with deps). */\n\tup?: (messages: Messages, options?: NodeTransportOptions) => void;\n\t/** Disconnect from upstream deps (present on nodes with deps). */\n\tunsubscribe?: () => void;\n\t/** Last successful guarded `down` / `up` (not set for `internal` deliveries). */\n\treadonly lastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/** Whether {@link NodeTransportOptions.actor | actor} may {@link Graph.observe | observe} this node. */\n\tallowsObserve(actor: Actor): boolean;\n\t/** Whether a {@link NodeOptions.guard | guard} is installed. */\n\thasGuard(): boolean;\n\t/** Versioning info (GRAPHREFLY-SPEC §7). `undefined` when versioning is not enabled. */\n\treadonly v: Readonly<NodeVersionInfo> | undefined;\n}\n\n// --- Bitmask helpers: integer for <=31 deps, Uint32Array for >31 ---\n\ninterface BitSet {\n\tset(index: number): void;\n\tclear(index: number): void;\n\thas(index: number): boolean;\n\t/**\n\t * True when all bits in `other` are also set in `this`.\n\t * IMPORTANT: `other` must be the same concrete type (both IntBitSet or both\n\t * ArrayBitSet). Cross-type calls will crash. Within `node()`, all masks for\n\t * a given node share the same `createBitSet(deps.length)` factory, so this\n\t * is always satisfied.\n\t */\n\tcovers(other: BitSet): boolean;\n\t/** True when at least one bit is set. */\n\tany(): boolean;\n\treset(): void;\n}\n\nfunction createIntBitSet(): BitSet {\n\tlet bits = 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\tbits |= 1 << i;\n\t\t},\n\t\tclear(i: number) {\n\t\t\tbits &= ~(1 << i);\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (bits & (1 << i)) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\treturn (\n\t\t\t\t(bits & (other as unknown as { _bits(): number })._bits()) ===\n\t\t\t\t(other as unknown as { _bits(): number })._bits()\n\t\t\t);\n\t\t},\n\t\tany() {\n\t\t\treturn bits !== 0;\n\t\t},\n\t\treset() {\n\t\t\tbits = 0;\n\t\t},\n\t\t_bits() {\n\t\t\treturn bits;\n\t\t},\n\t} as BitSet & { _bits(): number };\n}\n\nfunction createArrayBitSet(size: number): BitSet {\n\tconst words = new Uint32Array(Math.ceil(size / 32));\n\treturn {\n\t\tset(i: number) {\n\t\t\twords[i >>> 5] |= 1 << (i & 31);\n\t\t},\n\t\tclear(i: number) {\n\t\t\twords[i >>> 5] &= ~(1 << (i & 31));\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (words[i >>> 5] & (1 << (i & 31))) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst ow = (other as unknown as { _words: Uint32Array })._words;\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif ((words[w] & ow[w]) >>> 0 !== ow[w]) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\t\tany() {\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif (words[w] !== 0) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\treset() {\n\t\t\twords.fill(0);\n\t\t},\n\t\t_words: words,\n\t} as unknown as BitSet;\n}\n\nfunction createBitSet(size: number): BitSet {\n\treturn size <= 31 ? createIntBitSet() : createArrayBitSet(size);\n}\n\nconst isNodeArray = (value: unknown): value is readonly Node[] => Array.isArray(value);\n\nconst isNodeOptions = (value: unknown): value is NodeOptions =>\n\ttypeof value === \"object\" && value != null && !Array.isArray(value);\n\nconst isCleanupFn = (value: unknown): value is () => void => typeof value === \"function\";\n\nconst statusAfterMessage = (status: NodeStatus, msg: Message): NodeStatus => {\n\tconst t = msg[0];\n\tif (t === DIRTY) return \"dirty\";\n\tif (t === DATA) return \"settled\";\n\tif (t === RESOLVED) return \"resolved\";\n\tif (t === COMPLETE) return \"completed\";\n\tif (t === ERROR) return \"errored\";\n\tif (t === INVALIDATE) return \"dirty\";\n\tif (t === TEARDOWN) return \"disconnected\";\n\treturn status;\n};\n\n// --- NodeImpl: class-based for V8 hidden class optimization and prototype method sharing ---\n\n/**\n * Class-based implementation of the {@link Node} interface.\n *\n * All internal state lives on instance fields (`_` prefix, private by convention)\n * so that introspection (e.g. {@link describeNode}) can read them directly via\n * `instanceof NodeImpl` — no side-channel registry needed.\n *\n * Follows callbag-recharge's `ProducerImpl` pattern: V8 hidden class stability,\n * prototype method sharing, selective binding for commonly detached methods.\n */\nexport class NodeImpl<T = unknown> implements Node<T> {\n\t// --- Configuration (set once, never reassigned) ---\n\tprivate readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\t/** @internal — read by {@link describeNode} before inference. */\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\t_deps: readonly Node[];\n\t_fn: NodeFn<T> | undefined;\n\t_opts: NodeOptions;\n\t_equals: (a: unknown, b: unknown) => boolean;\n\t_onMessage: OnMessageHandler | undefined;\n\t/** @internal — read by {@link describeNode} for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\tprivate _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\t_hasDeps: boolean;\n\t_autoComplete: boolean;\n\t_isSingleDep: boolean;\n\n\t// --- Mutable state ---\n\t_cached: T | undefined;\n\t_status: NodeStatus;\n\t_terminal = false;\n\t_connected = false;\n\t_producerStarted = false;\n\t_connecting = false;\n\t_manualEmitUsed = false;\n\t_sinkCount = 0;\n\t_singleDepSinkCount = 0;\n\n\t// --- Object/collection state ---\n\t_depDirtyMask: BitSet;\n\t_depSettledMask: BitSet;\n\t_depCompleteMask: BitSet;\n\t_allDepsCompleteMask: BitSet;\n\t_lastDepValues: readonly unknown[] | undefined;\n\t_cleanup: (() => void) | undefined;\n\t_sinks: NodeSink | Set<NodeSink> | null = null;\n\t_singleDepSinks = new WeakSet<NodeSink>();\n\t_upstreamUnsubs: Array<() => void> = [];\n\t_actions: NodeActions;\n\t_boundEmitToSinks: (messages: Messages) => void;\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\tprivate _versioning: NodeVersionInfo | undefined;\n\tprivate _hashFn: HashFn;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn<T> | undefined, opts: NodeOptions) {\n\t\tthis._deps = deps;\n\t\tthis._fn = fn;\n\t\tthis._opts = opts;\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._guard = opts.guard;\n\t\tthis._hasDeps = deps.length > 0;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._isSingleDep = deps.length === 1 && fn != null;\n\n\t\tthis._cached = opts.initial as T | undefined;\n\t\tthis._status = this._hasDeps ? \"disconnected\" : \"settled\";\n\n\t\t// Versioning (GRAPHREFLY-SPEC §7)\n\t\tthis._hashFn = opts.versioningHash ?? defaultHash;\n\t\tthis._versioning =\n\t\t\topts.versioning != null\n\t\t\t\t? createVersioning(opts.versioning, this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\tthis._depDirtyMask = createBitSet(deps.length);\n\t\tthis._depSettledMask = createBitSet(deps.length);\n\t\tthis._depCompleteMask = createBitSet(deps.length);\n\t\tthis._allDepsCompleteMask = createBitSet(deps.length);\n\t\tfor (let i = 0; i < deps.length; i++) this._allDepsCompleteMask.set(i);\n\n\t\t// Build companion meta nodes\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = node({\n\t\t\t\tinitial: v,\n\t\t\t\tname: `${opts.name ?? \"node\"}:meta:${k}`,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t\t});\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions object: created once, references `this` methods.\n\t\t// Captures `this` via arrow-in-object so manualEmitUsed is set on the instance.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._manualEmitUsed = true;\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._manualEmitUsed = true;\n\t\t\t\tself._emitAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tself._upInternal(messages);\n\t\t\t},\n\t\t};\n\n\t\t// Bind commonly detached protocol methods\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t\tthis._boundEmitToSinks = this._emitToSinks.bind(this);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/**\n\t * When a node is registered with {@link Graph.add} without an options `name`,\n\t * the graph assigns the registry local name for introspection (parity with graphrefly-py).\n\t */\n\t_assignRegistryName(localName: string): void {\n\t\tif (this._optsName !== undefined || this._registryName !== undefined) return;\n\t\tthis._registryName = localName;\n\t}\n\n\t/**\n\t * @internal Attach/remove inspector hook for graph-level observability.\n\t * Returns a disposer that restores the previous hook.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tconst prev = this._inspectorHook;\n\t\tthis._inspectorHook = hook;\n\t\treturn () => {\n\t\t\tif (this._inspectorHook === hook) {\n\t\t\t\tthis._inspectorHook = prev;\n\t\t\t}\n\t\t};\n\t}\n\n\t// --- Public interface (Node<T>) ---\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\tget v(): Readonly<NodeVersionInfo> | undefined {\n\t\treturn this._versioning;\n\t}\n\n\t/**\n\t * Retroactively apply versioning to a node that was created without it.\n\t * No-op if versioning is already enabled.\n\t *\n\t * Version starts at 0 regardless of prior DATA emissions — it tracks\n\t * changes from the moment versioning is enabled, not historical ones.\n\t *\n\t * @internal — used by {@link Graph.setVersioning}.\n\t */\n\t_applyVersioning(level: VersioningLevel, opts?: { id?: string; hash?: HashFn }): void {\n\t\tif (this._versioning != null) return;\n\t\tthis._hashFn = opts?.hash ?? this._hashFn;\n\t\tthis._versioning = createVersioning(level, this._cached, {\n\t\t\tid: opts?.id,\n\t\t\thash: this._hashFn,\n\t\t});\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\tget(): T | undefined {\n\t\treturn this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\tprivate _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet lifecycleMessages = messages;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._opts.resubscribable) {\n\t\t\tconst terminalPassthrough = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (terminalPassthrough.length === 0) return;\n\t\t\tlifecycleMessages = terminalPassthrough;\n\t\t\tsinkMessages = terminalPassthrough;\n\t\t}\n\t\tthis._handleLocalLifecycle(lifecycleMessages);\n\t\t// Single-dep optimization: skip DIRTY to sinks when sole subscriber is single-dep\n\t\t// AND the batch contains a phase-2 message (DATA/RESOLVED). Standalone DIRTY\n\t\t// (without follow-up) must pass through so downstream is notified.\n\t\tif (this._canSkipDirty()) {\n\t\t\t// Inline check: does the batch contain DATA or RESOLVED?\n\t\t\tlet hasPhase2 = false;\n\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\tconst t = sinkMessages[i][0];\n\t\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\t\thasPhase2 = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPhase2) {\n\t\t\t\t// Inline filter: remove DIRTY messages\n\t\t\t\tconst filtered: Message[] = [];\n\t\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\t\tif (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);\n\t\t\t\t}\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\temitWithBatch(this._boundEmitToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\temitWithBatch(this._boundEmitToSinks, sinkMessages);\n\t}\n\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void {\n\t\tif (hints?.actor != null && this._guard != null) {\n\t\t\tconst actor = normalizeActor(hints.actor);\n\t\t\tif (!this._guard(actor, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\tif (this._terminal && this._opts.resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._status = this._hasDeps ? \"disconnected\" : \"settled\";\n\t\t\tthis._opts.onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\tif (this._hasDeps) {\n\t\t\tthis._connectUpstream();\n\t\t} else if (this._fn) {\n\t\t\tthis._startProducer();\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tif (this._singleDepSinks.has(sink)) {\n\t\t\t\tthis._singleDepSinkCount -= 1;\n\t\t\t\tthis._singleDepSinks.delete(sink);\n\t\t\t}\n\t\t\tif (this._sinks == null) return;\n\t\t\tif (typeof this._sinks === \"function\") {\n\t\t\t\tif (this._sinks === sink) this._sinks = null;\n\t\t\t} else {\n\t\t\t\tthis._sinks.delete(sink);\n\t\t\t\tif (this._sinks.size === 1) {\n\t\t\t\t\tconst [only] = this._sinks;\n\t\t\t\t\tthis._sinks = only;\n\t\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\t\tthis._sinks = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._sinks == null) {\n\t\t\t\tthis._disconnectUpstream();\n\t\t\t\tthis._stopProducer();\n\t\t\t}\n\t\t};\n\t}\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tif (options === undefined) {\n\t\t\t\tdep.up?.(messages);\n\t\t\t} else {\n\t\t\t\tdep.up?.(messages, options);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _upInternal(messages: Messages): void {\n\t\tif (!this._hasDeps) return;\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tif (!this._hasDeps) return;\n\t\tthis._disconnectUpstream();\n\t}\n\n\t// --- Private methods (prototype, _ prefix) ---\n\n\t_emitToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others mid-iteration.\n\t\t// Iterating the live Set would skip not-yet-visited sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\t_handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\t// GRAPHREFLY-SPEC §1.2: clear cached state; do not auto-emit from here.\n\t\t\t\tconst cleanupFn = this._cleanup;\n\t\t\t\tthis._cleanup = undefined;\n\t\t\t\tcleanupFn?.();\n\t\t\t\tthis._cached = undefined;\n\t\t\t\tthis._lastDepValues = undefined;\n\t\t\t}\n\t\t\tthis._status = statusAfterMessage(this._status, m);\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._opts.resetOnTeardown) {\n\t\t\t\t\tthis._cached = undefined;\n\t\t\t\t}\n\t\t\t\t// Invoke cleanup for compute nodes (deps+fn) — spec §2.4\n\t\t\t\t// requires cleanup on teardown, not just before next invocation.\n\t\t\t\t// _stopProducer handles cleanup for producer nodes separately.\n\t\t\t\tconst teardownCleanup = this._cleanup;\n\t\t\t\tthis._cleanup = undefined;\n\t\t\t\tteardownCleanup?.();\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._disconnectUpstream();\n\t\t\t\t\tthis._stopProducer();\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Propagate other meta-eligible signals (centralized in messages.ts).\n\t\t\tif (t !== TEARDOWN && propagatesToMeta(t)) {\n\t\t\t\tthis._propagateToMeta(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Propagate a signal to all companion meta nodes (best-effort). */\n\t_propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\t(metaNode as NodeImpl)._downInternal([[t]]);\n\t\t\t} catch {\n\t\t\t\t/* best-effort: other meta nodes still receive the signal */\n\t\t\t}\n\t\t}\n\t}\n\n\t_canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\t_emitAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tconst unchanged = this._equals(this._cached, value);\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._cached = value as T;\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n\n\t_runFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._terminal && !this._opts.resubscribable) return;\n\t\tif (this._connecting) return;\n\n\t\ttry {\n\t\t\tconst n = this._deps.length;\n\t\t\tconst depValues = new Array(n);\n\t\t\tfor (let i = 0; i < n; i++) depValues[i] = this._deps[i].get();\n\t\t\t// Identity check BEFORE cleanup: if all dep values are unchanged,\n\t\t\t// skip cleanup+fn entirely so effect nodes don't teardown/restart on no-op.\n\t\t\tconst prev = this._lastDepValues;\n\t\t\tif (n > 0 && prev != null && prev.length === n) {\n\t\t\t\tlet allSame = true;\n\t\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\t\tif (!Object.is(depValues[i], prev[i])) {\n\t\t\t\t\t\tallSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (allSame) {\n\t\t\t\t\tif (this._status === \"dirty\") {\n\t\t\t\t\t\tthis._downInternal([[RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevCleanup = this._cleanup;\n\t\t\tthis._cleanup = undefined;\n\t\t\tprevCleanup?.();\n\t\t\tthis._manualEmitUsed = false;\n\t\t\tthis._lastDepValues = depValues;\n\t\t\tthis._inspectorHook?.({ kind: \"run\", depValues });\n\t\t\tconst out = this._fn(depValues, this._actions);\n\t\t\tif (isCleanupFn(out)) {\n\t\t\t\tthis._cleanup = out;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this._manualEmitUsed) return;\n\t\t\tif (out === undefined) return;\n\t\t\tthis._emitAutoValue(out);\n\t\t} catch (err) {\n\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t}\n\t}\n\n\t_onDepDirty(index: number): void {\n\t\tconst wasDirty = this._depDirtyMask.has(index);\n\t\tthis._depDirtyMask.set(index);\n\t\tthis._depSettledMask.clear(index);\n\t\tif (!wasDirty) {\n\t\t\tthis._downInternal([[DIRTY]]);\n\t\t}\n\t}\n\n\t_onDepSettled(index: number): void {\n\t\tif (!this._depDirtyMask.has(index)) {\n\t\t\tthis._onDepDirty(index);\n\t\t}\n\t\tthis._depSettledMask.set(index);\n\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\tthis._depDirtyMask.reset();\n\t\t\tthis._depSettledMask.reset();\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\t_maybeCompleteFromDeps(): void {\n\t\tif (\n\t\t\tthis._autoComplete &&\n\t\t\tthis._deps.length > 0 &&\n\t\t\tthis._depCompleteMask.covers(this._allDepsCompleteMask)\n\t\t) {\n\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t}\n\t}\n\n\t_handleDepMessages(index: number, messages: Messages): void {\n\t\tfor (const msg of messages) {\n\t\t\tthis._inspectorHook?.({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\t\t\t// User-defined message handler gets first look (spec §2.6).\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!this._fn) {\n\t\t\t\t// Passthrough: forward all messages except COMPLETE when multi-dep.\n\t\t\t\t// Multi-dep passthrough must wait for ALL deps to complete (§1.3.5).\n\t\t\t\tif (t === COMPLETE && this._deps.length > 1) {\n\t\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._onDepDirty(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._onDepSettled(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\t// Complete implies no longer pending — clear dirty/settled bits\n\t\t\t\t// so a preceding DIRTY from this dep doesn't block settlement.\n\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\tthis._depSettledMask.clear(index);\n\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t} else if (!this._depDirtyMask.any() && this._status === \"dirty\") {\n\t\t\t\t\t// D2: dep went DIRTY→COMPLETE without DATA — node was marked\n\t\t\t\t\t// dirty but no settlement came. Recompute so downstream\n\t\t\t\t\t// gets RESOLVED (value unchanged) or DATA (value changed).\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Forward unknown message types\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\t_connectUpstream(): void {\n\t\tif (!this._hasDeps || this._connected) return;\n\t\tthis._connected = true;\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\tthis._status = \"settled\";\n\t\tconst subHints: SubscribeHints | undefined = this._isSingleDep\n\t\t\t? { singleDep: true }\n\t\t\t: undefined;\n\t\tthis._connecting = true;\n\t\ttry {\n\t\t\tfor (let i = 0; i < this._deps.length; i += 1) {\n\t\t\t\tconst dep = this._deps[i];\n\t\t\t\tthis._upstreamUnsubs.push(\n\t\t\t\t\tdep.subscribe((msgs) => this._handleDepMessages(i, msgs), subHints),\n\t\t\t\t);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._connecting = false;\n\t\t}\n\t\tif (this._fn) {\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\t_stopProducer(): void {\n\t\tif (!this._producerStarted) return;\n\t\tthis._producerStarted = false;\n\t\tconst producerCleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tproducerCleanup?.();\n\t}\n\n\t_startProducer(): void {\n\t\tif (this._deps.length !== 0 || !this._fn || this._producerStarted) return;\n\t\tthis._producerStarted = true;\n\t\tthis._runFn();\n\t}\n\n\t_disconnectUpstream(): void {\n\t\tif (!this._connected) return;\n\t\tfor (const unsub of this._upstreamUnsubs.splice(0)) {\n\t\t\tunsub();\n\t\t}\n\t\tthis._connected = false;\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\tthis._status = \"disconnected\";\n\t}\n}\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (GRAPHREFLY-SPEC §2).\n *\n * Typical shapes: `node([])` / `node([], opts)` for a manual source; `node(producerFn, opts)` for a\n * producer; `node(deps, computeFn, opts)` for derived nodes and operators.\n *\n * @param depsOrFn - Dependency nodes, a {@link NodeFn} (producer), or {@link NodeOptions} alone.\n * @param fnOrOpts - With deps: compute function or options. Omitted for producer-only form.\n * @param optsArg - Options when both `deps` and `fn` are provided.\n * @returns `Node<T>` - Configured node instance (lazy until subscribed).\n *\n * @remarks\n * **Protocol:** DIRTY / DATA / RESOLVED ordering, completion, and batch deferral follow `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n *\n * @example\n * ```ts\n * import { node, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = node([a], ([x]) => (x as number) + 1);\n * ```\n *\n * @seeAlso [Specification](/spec)\n *\n * @category core\n */\nexport function node<T = unknown>(\n\tdepsOrFn?: readonly Node[] | NodeFn<T> | NodeOptions,\n\tfnOrOpts?: NodeFn<T> | NodeOptions,\n\toptsArg?: NodeOptions,\n): Node<T> {\n\tconst deps: readonly Node[] = isNodeArray(depsOrFn) ? depsOrFn : [];\n\tconst fn: NodeFn<T> | undefined =\n\t\ttypeof depsOrFn === \"function\"\n\t\t\t? depsOrFn\n\t\t\t: typeof fnOrOpts === \"function\"\n\t\t\t\t? fnOrOpts\n\t\t\t\t: undefined;\n\tlet opts: NodeOptions = {};\n\tif (isNodeArray(depsOrFn)) {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t} else if (isNodeOptions(depsOrFn)) {\n\t\topts = depsOrFn;\n\t} else {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t}\n\n\treturn new NodeImpl<T>(deps, fn, opts);\n}\n","/**\n * `dynamicNode` — runtime dep tracking with diamond resolution (Phase 0.3b).\n *\n * Unlike `node()` where deps are fixed at construction, `dynamicNode` discovers\n * deps at runtime via a tracking `get()` proxy. After each recompute, deps are\n * diffed: new deps are connected, removed deps are disconnected, and bitmasks\n * are rebuilt. Kept deps retain their subscriptions (no teardown/reconnect churn).\n *\n * This ports callbag-recharge's `dynamicDerived` pattern to GraphReFly's protocol.\n */\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { emitWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport {\n\tnode as createNode,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeInspectorHook,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node.js\";\n\n/**\n * The tracking `get` function passed to `dynamicNode`'s compute function.\n * Each call to `get(dep)` reads the dep's current value and records it as a dependency.\n */\nexport type DynGet = <V>(dep: Node<V>) => V | undefined;\n\n/**\n * Compute function for `dynamicNode`. Receives a tracking `get` proxy.\n * Deps are discovered by which nodes are passed to `get()` during execution.\n */\nexport type DynamicNodeFn<T> = (get: DynGet) => T;\n\n/** Options for `dynamicNode`. */\nexport type DynamicNodeOptions = Pick<\n\tNodeOptions,\n\t| \"name\"\n\t| \"equals\"\n\t| \"meta\"\n\t| \"resubscribable\"\n\t| \"resetOnTeardown\"\n\t| \"guard\"\n\t| \"onMessage\"\n\t| \"onResubscribe\"\n\t| \"completeWhenDepsComplete\"\n\t| \"describeKind\"\n>;\n\n/**\n * Creates a node with runtime dep tracking. Deps are discovered each time the\n * compute function runs by tracking which nodes are passed to the `get()` proxy.\n *\n * After each recompute:\n * - New deps (not in previous set) are subscribed\n * - Removed deps (not in current set) are unsubscribed\n * - Kept deps retain their existing subscriptions\n * - Bitmasks are rebuilt to match the new dep set\n *\n * The node participates fully in diamond resolution via the standard two-phase\n * DIRTY/RESOLVED protocol across all dynamically-tracked deps.\n *\n * @param fn - Compute function receiving a tracking `get` proxy.\n * @param opts - Optional configuration.\n * @returns `Node<T>` with dynamic dep tracking.\n *\n * @example\n * ```ts\n * import { dynamicNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const cond = state(true);\n * const a = state(1);\n * const b = state(2);\n *\n * // Deps change based on cond's value\n * const d = dynamicNode((get) => {\n * const useA = get(cond);\n * return useA ? get(a) : get(b);\n * });\n * ```\n *\n * @category core\n */\nexport function dynamicNode<T = unknown>(fn: DynamicNodeFn<T>, opts?: DynamicNodeOptions): Node<T> {\n\treturn new DynamicNodeImpl<T>(fn, opts ?? {});\n}\n\n/** @internal — exported for {@link describeNode} `instanceof` check. */\nexport class DynamicNodeImpl<T = unknown> implements Node<T> {\n\tprivate readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\tprivate readonly _fn: DynamicNodeFn<T>;\n\tprivate readonly _equals: (a: unknown, b: unknown) => boolean;\n\tprivate readonly _resubscribable: boolean;\n\tprivate readonly _resetOnTeardown: boolean;\n\tprivate readonly _autoComplete: boolean;\n\tprivate readonly _onMessage: OnMessageHandler | undefined;\n\tprivate readonly _onResubscribe: (() => void) | undefined;\n\t/** @internal — read by {@link describeNode} for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\tprivate _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\n\t// Sink tracking\n\tprivate _sinkCount = 0;\n\tprivate _singleDepSinkCount = 0;\n\tprivate _singleDepSinks = new WeakSet<NodeSink>();\n\n\t// Actions object (for onMessage handler)\n\tprivate readonly _actions: NodeActions;\n\tprivate readonly _boundEmitToSinks: (messages: Messages) => void;\n\n\t// Mutable state\n\tprivate _cached: T | undefined;\n\tprivate _status: NodeStatus = \"disconnected\";\n\tprivate _terminal = false;\n\tprivate _connected = false;\n\tprivate _rewiring = false; // re-entrancy guard\n\n\t// Dynamic deps tracking\n\tprivate _deps: Node[] = [];\n\tprivate _depUnsubs: Array<() => void> = [];\n\tprivate _depIndexMap = new Map<Node, number>(); // node → index in _deps\n\tprivate _dirtyBits = new Set<number>();\n\tprivate _settledBits = new Set<number>();\n\tprivate _completeBits = new Set<number>();\n\n\t// Sinks\n\tprivate _sinks: NodeSink | Set<NodeSink> | null = null;\n\n\tconstructor(fn: DynamicNodeFn<T>, opts: DynamicNodeOptions) {\n\t\tthis._fn = fn;\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._resubscribable = opts.resubscribable ?? false;\n\t\tthis._resetOnTeardown = opts.resetOnTeardown ?? false;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._onResubscribe = opts.onResubscribe;\n\t\tthis._guard = opts.guard;\n\t\tthis._inspectorHook = undefined;\n\n\t\t// Build companion meta nodes (same pattern as NodeImpl)\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = createNode({\n\t\t\t\tinitial: v,\n\t\t\t\tname: `${opts.name ?? \"dynamicNode\"}:meta:${k}`,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t\t});\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions object: created once, references `this` methods.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._emitAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tfor (const dep of self._deps) {\n\t\t\t\t\tdep.up?.(messages, { internal: true });\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\n\t\t// Bind commonly detached protocol methods\n\t\tthis._boundEmitToSinks = this._emitToSinks.bind(this);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/** @internal */\n\t_assignRegistryName(localName: string): void {\n\t\tif (this._optsName !== undefined || this._registryName !== undefined) return;\n\t\tthis._registryName = localName;\n\t}\n\n\t/**\n\t * @internal Attach/remove inspector hook for graph-level observability.\n\t * Returns a disposer that restores the previous hook.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tconst prev = this._inspectorHook;\n\t\tthis._inspectorHook = hook;\n\t\treturn () => {\n\t\t\tif (this._inspectorHook === hook) {\n\t\t\t\tthis._inspectorHook = prev;\n\t\t\t}\n\t\t};\n\t}\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\t/** Versioning not yet supported on DynamicNodeImpl. */\n\tget v(): undefined {\n\t\treturn undefined;\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\tget(): T | undefined {\n\t\treturn this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\tprivate _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._resubscribable) {\n\t\t\tconst pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (pass.length === 0) return;\n\t\t\tsinkMessages = pass as Messages;\n\t\t}\n\t\tthis._handleLocalLifecycle(sinkMessages);\n\t\t// Single-dep optimization: skip DIRTY to sinks when sole subscriber is single-dep\n\t\t// AND the batch contains a phase-2 message (DATA/RESOLVED). Standalone DIRTY\n\t\t// (without follow-up) must pass through so downstream is notified.\n\t\tif (this._canSkipDirty()) {\n\t\t\t// Inline check: does the batch contain DATA or RESOLVED?\n\t\t\tlet hasPhase2 = false;\n\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\tconst t = sinkMessages[i][0];\n\t\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\t\thasPhase2 = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPhase2) {\n\t\t\t\t// Inline filter: remove DIRTY messages\n\t\t\t\tconst filtered: Message[] = [];\n\t\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\t\tif (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);\n\t\t\t\t}\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\temitWithBatch(this._boundEmitToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\temitWithBatch(this._boundEmitToSinks, sinkMessages);\n\t}\n\n\tprivate _canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void {\n\t\tif (hints?.actor != null && this._guard != null) {\n\t\t\tconst actor = normalizeActor(hints.actor);\n\t\t\tif (!this._guard(actor, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\tif (this._terminal && this._resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._status = \"disconnected\";\n\t\t\tthis._onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\tif (!this._connected) {\n\t\t\tthis._connect();\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tif (this._singleDepSinks.has(sink)) {\n\t\t\t\tthis._singleDepSinkCount -= 1;\n\t\t\t\tthis._singleDepSinks.delete(sink);\n\t\t\t}\n\t\t\tif (this._sinks == null) return;\n\t\t\tif (typeof this._sinks === \"function\") {\n\t\t\t\tif (this._sinks === sink) this._sinks = null;\n\t\t\t} else {\n\t\t\t\tthis._sinks.delete(sink);\n\t\t\t\tif (this._sinks.size === 1) {\n\t\t\t\t\tconst [only] = this._sinks;\n\t\t\t\t\tthis._sinks = only;\n\t\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\t\tthis._sinks = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._sinks == null) {\n\t\t\t\tthis._disconnect();\n\t\t\t}\n\t\t};\n\t}\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, options);\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tthis._disconnect();\n\t}\n\n\t// --- Private methods ---\n\n\tprivate _emitToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\tprivate _handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) this._cached = m[1] as T;\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\tthis._cached = undefined;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._status = \"settled\";\n\t\t\t} else if (t === DIRTY) {\n\t\t\t\tthis._status = \"dirty\";\n\t\t\t} else if (t === COMPLETE) {\n\t\t\t\tthis._status = \"completed\";\n\t\t\t\tthis._terminal = true;\n\t\t\t} else if (t === ERROR) {\n\t\t\t\tthis._status = \"errored\";\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._resetOnTeardown) this._cached = undefined;\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._disconnect();\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Propagate other meta-eligible signals (centralized in messages.ts).\n\t\t\tif (t !== TEARDOWN && propagatesToMeta(t)) {\n\t\t\t\tthis._propagateToMeta(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Propagate a signal to all companion meta nodes (best-effort). */\n\tprivate _propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\tmetaNode.down([[t]], { internal: true });\n\t\t\t} catch {\n\t\t\t\t/* best-effort: other meta nodes still receive the signal */\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _emitAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tconst unchanged = this._equals(this._cached, value);\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._cached = value as T;\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n\n\tprivate _connect(): void {\n\t\tif (this._connected) return;\n\t\tthis._connected = true;\n\t\tthis._status = \"settled\";\n\t\tthis._dirtyBits.clear();\n\t\tthis._settledBits.clear();\n\t\tthis._completeBits.clear();\n\t\tthis._runFn();\n\t}\n\n\tprivate _disconnect(): void {\n\t\tif (!this._connected) return;\n\t\tfor (const unsub of this._depUnsubs) unsub();\n\t\tthis._depUnsubs = [];\n\t\tthis._deps = [];\n\t\tthis._depIndexMap.clear();\n\t\tthis._dirtyBits.clear();\n\t\tthis._settledBits.clear();\n\t\tthis._completeBits.clear();\n\t\tthis._connected = false;\n\t\tthis._status = \"disconnected\";\n\t}\n\n\tprivate _runFn(): void {\n\t\tif (this._terminal && !this._resubscribable) return;\n\t\tif (this._rewiring) return;\n\n\t\t// Track deps during fn execution\n\t\tconst trackedDeps: Node[] = [];\n\t\tconst trackedSet = new Set<Node>();\n\n\t\tconst get: DynGet = <V>(dep: Node<V>): V | undefined => {\n\t\t\tif (!trackedSet.has(dep)) {\n\t\t\t\ttrackedSet.add(dep);\n\t\t\t\ttrackedDeps.push(dep);\n\t\t\t}\n\t\t\treturn dep.get();\n\t\t};\n\n\t\ttry {\n\t\t\t// Collect dep values for inspector hook\n\t\t\tconst depValues: unknown[] = [];\n\t\t\tfor (const dep of this._deps) {\n\t\t\t\tdepValues.push(dep.get());\n\t\t\t}\n\t\t\tthis._inspectorHook?.({ kind: \"run\", depValues });\n\n\t\t\tconst result = this._fn(get);\n\t\t\tthis._rewire(trackedDeps);\n\t\t\tif (result === undefined) return;\n\t\t\tthis._emitAutoValue(result);\n\t\t} catch (err) {\n\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t}\n\t}\n\n\tprivate _rewire(newDeps: Node[]): void {\n\t\tthis._rewiring = true;\n\t\ttry {\n\t\t\tconst oldMap = this._depIndexMap;\n\t\t\tconst newMap = new Map<Node, number>();\n\t\t\tconst newUnsubs: Array<() => void> = [];\n\n\t\t\t// Reuse or create subscriptions\n\t\t\tfor (let i = 0; i < newDeps.length; i++) {\n\t\t\t\tconst dep = newDeps[i];\n\t\t\t\tnewMap.set(dep, i);\n\t\t\t\tconst oldIdx = oldMap.get(dep);\n\t\t\t\tif (oldIdx !== undefined) {\n\t\t\t\t\t// Kept dep — reuse subscription but update index\n\t\t\t\t\tnewUnsubs.push(this._depUnsubs[oldIdx]);\n\t\t\t\t\t// Mark old unsub as consumed\n\t\t\t\t\tthis._depUnsubs[oldIdx] = () => {};\n\t\t\t\t} else {\n\t\t\t\t\t// New dep — subscribe\n\t\t\t\t\tconst idx = i;\n\t\t\t\t\tconst unsub = dep.subscribe((msgs) => this._handleDepMessages(idx, msgs));\n\t\t\t\t\tnewUnsubs.push(unsub);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Disconnect removed deps\n\t\t\tfor (const [dep, oldIdx] of oldMap) {\n\t\t\t\tif (!newMap.has(dep)) {\n\t\t\t\t\tthis._depUnsubs[oldIdx]();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._deps = newDeps;\n\t\t\tthis._depUnsubs = newUnsubs;\n\t\t\tthis._depIndexMap = newMap;\n\t\t\tthis._dirtyBits.clear();\n\t\t\tthis._settledBits.clear();\n\t\t\t// Preserve complete bits for deps that are still present\n\t\t\tconst newCompleteBits = new Set<number>();\n\t\t\tfor (const oldIdx of this._completeBits) {\n\t\t\t\tconst dep = [...oldMap.entries()].find(([, idx]) => idx === oldIdx)?.[0];\n\t\t\t\tif (dep && newMap.has(dep)) {\n\t\t\t\t\tnewCompleteBits.add(newMap.get(dep)!);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._completeBits = newCompleteBits;\n\t\t} finally {\n\t\t\tthis._rewiring = false;\n\t\t}\n\t}\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\tif (this._rewiring) return; // suppress signals during rewire\n\n\t\tfor (const msg of messages) {\n\t\t\tthis._inspectorHook?.({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\t\t\t// User-defined message handler gets first look (spec §2.6).\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._dirtyBits.add(index);\n\t\t\t\tthis._settledBits.delete(index);\n\t\t\t\tif (this._dirtyBits.size === 1) {\n\t\t\t\t\t// First dirty — propagate\n\t\t\t\t\temitWithBatch(this._boundEmitToSinks, [[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tif (!this._dirtyBits.has(index)) {\n\t\t\t\t\tthis._dirtyBits.add(index);\n\t\t\t\t\temitWithBatch(this._boundEmitToSinks, [[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tthis._settledBits.add(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._dirtyBits.clear();\n\t\t\t\t\tthis._settledBits.clear();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._completeBits.add(index);\n\t\t\t\tthis._dirtyBits.delete(index);\n\t\t\t\tthis._settledBits.delete(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._dirtyBits.clear();\n\t\t\t\t\tthis._settledBits.clear();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tthis._autoComplete &&\n\t\t\t\t\tthis._completeBits.size >= this._deps.length &&\n\t\t\t\t\tthis._deps.length > 0\n\t\t\t\t) {\n\t\t\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\tprivate _allDirtySettled(): boolean {\n\t\tif (this._dirtyBits.size === 0) return false;\n\t\tfor (const idx of this._dirtyBits) {\n\t\t\tif (!this._settledBits.has(idx)) return false;\n\t\t}\n\t\treturn true;\n\t}\n}\n","import { type Node, type NodeFn, type NodeOptions, node } from \"./node.js\";\n\n/**\n * Creates a manual source with no upstream deps. Emit values with {@link Node.down}.\n *\n * Spec: `state(initial, opts?)` is `node([], { initial, ...opts })` (GRAPHREFLY-SPEC §2.7).\n *\n * @param initial - Initial cached value.\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n * @returns `Node<T>` - Stateful node you drive imperatively.\n *\n * @example\n * ```ts\n * import { DATA, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(0);\n * n.down([[DATA, 1]]);\n * ```\n *\n * @category core\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n/**\n * Creates a producer node with no deps; `fn` runs when the first subscriber connects.\n *\n * @param fn - Receives deps (empty) and {@link NodeActions}; use `emit` / `down` to push.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Producer node.\n *\n * @example\n * ```ts\n * import { producer } from \"@graphrefly/graphrefly-ts\";\n *\n * const tick = producer((_d, a) => {\n * a.emit(1);\n * });\n * ```\n *\n * @category core\n */\nexport function producer<T = unknown>(fn: NodeFn<T>, opts?: NodeOptions): Node<T> {\n\treturn node<T>(fn, { describeKind: \"producer\", ...opts });\n}\n\n/**\n * Creates a derived node from dependencies and a compute function (same primitive as operators).\n *\n * @param deps - Upstream nodes.\n * @param fn - Compute function; return value is emitted, or use `actions` explicitly.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Derived node.\n *\n * @example\n * ```ts\n * import { derived, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n *\n * @category core\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: NodeFn<T>,\n\topts?: NodeOptions,\n): Node<T> {\n\treturn node<T>(deps, fn, { describeKind: \"derived\", ...opts });\n}\n\n/**\n * Runs a side-effect when deps settle; return value is not auto-emitted.\n *\n * @param deps - Nodes to watch.\n * @param fn - Side-effect body.\n * @returns `Node<unknown>` - Effect node.\n *\n * @example\n * ```ts\n * import { effect, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(1);\n * effect([n], ([v]) => {\n * console.log(v);\n * });\n * ```\n *\n * @category core\n */\nexport function effect(deps: readonly Node[], fn: NodeFn<unknown>): Node<unknown> {\n\treturn node(deps, fn, { describeKind: \"effect\" });\n}\n\n/** Unary transform used by {@link pipe} (typically returns a new node wrapping `n`). */\nexport type PipeOperator = (n: Node) => Node;\n\n/**\n * Composes unary operators left-to-right; returns the final node. Does not register a {@link Graph}.\n *\n * @param source - Starting node.\n * @param ops - Each operator maps `Node` to `Node` (curried operators from `extra` use a factory pattern — wrap or use direct calls).\n * @returns `Node` - Result of the last operator.\n *\n * @example\n * ```ts\n * import { filter, map, pipe, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state(1);\n * const out = pipe(\n * src,\n * (n) => map(n, (x) => x + 1),\n * (n) => filter(n, (x) => x > 0),\n * );\n * ```\n *\n * @category core\n */\nexport function pipe(source: Node, ...ops: PipeOperator[]): Node {\n\tlet current = source;\n\tfor (const op of ops) {\n\t\tcurrent = op(current);\n\t}\n\treturn current;\n}\n","import { batch } from \"../../core/batch.js\";\nimport { type DynGet, dynamicNode } from \"../../core/dynamic-node.js\";\nimport { DATA, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { state } from \"../../core/sugar.js\";\n\n/**\n * A Nanostores-compatible atom.\n *\n * @category compat\n */\nexport interface NanoAtom<T> {\n\t/** Get current value. */\n\tget(): T;\n\t/** Set a new value (writable atoms only). */\n\tset(value: T): void;\n\t/** Subscribe to value changes. Callback receives the new value.\n\t * Returns unsubscribe function. Called immediately with current value. */\n\tsubscribe(cb: (value: T) => void): () => void;\n\t/** Listen to value changes (no immediate call). Returns unsubscribe. */\n\tlisten(cb: (value: T) => void): () => void;\n\t/** The underlying GraphReFly node. */\n\treadonly _node: Node<T>;\n}\n\n/**\n * A Nanostores-compatible computed store.\n *\n * @category compat\n */\nexport interface NanoComputed<T> {\n\t/** Get current value. */\n\tget(): T;\n\t/** Subscribe to value changes. Called immediately with current value.\n\t * Returns unsubscribe function. */\n\tsubscribe(cb: (value: T) => void): () => void;\n\t/** Listen to value changes (no immediate call). Returns unsubscribe. */\n\tlisten(cb: (value: T) => void): () => void;\n\t/** The underlying GraphReFly node. */\n\treadonly _node: Node<T>;\n}\n\n/**\n * A Nanostores-compatible map.\n *\n * @category compat\n */\nexport interface NanoMap<T extends Record<string, unknown>> extends NanoAtom<T> {\n\t/** Set a single key. */\n\tsetKey<K extends keyof T>(key: K, value: T[K]): void;\n}\n\nconst START_LISTENERS = new WeakMap<Node<any>, Set<() => void>>();\nconst STOP_LISTENERS = new WeakMap<Node<any>, Set<() => void>>();\n\nfunction trigger(node: Node<any>, map: WeakMap<Node<any>, Set<() => void>>) {\n\tconst callbacks = map.get(node);\n\tif (callbacks) {\n\t\tfor (const cb of callbacks) cb();\n\t}\n}\n\nfunction createStore<T>(node: Node<T>, extra: any = {}): any {\n\tlet listeners = 0;\n\tconst store = {\n\t\t...extra,\n\t\tget: () => getVal(node),\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\tif (listeners === 0) trigger(node, START_LISTENERS);\n\t\t\tlisteners++;\n\t\t\tconst sub = node.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) cb(v as T);\n\t\t\t\t}\n\t\t\t});\n\t\t\tcb(getVal(node));\n\t\t\treturn () => {\n\t\t\t\tsub();\n\t\t\t\tlisteners--;\n\t\t\t\tif (listeners === 0) trigger(node, STOP_LISTENERS);\n\t\t\t};\n\t\t},\n\t\tlisten: (cb: (value: T) => void) => {\n\t\t\tif (listeners === 0) trigger(node, START_LISTENERS);\n\t\t\tlisteners++;\n\t\t\tconst sub = node.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) cb(v as T);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsub();\n\t\t\t\tlisteners--;\n\t\t\t\tif (listeners === 0) trigger(node, STOP_LISTENERS);\n\t\t\t};\n\t\t},\n\t\t_node: node,\n\t};\n\treturn store;\n}\n\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined = n.get();\n\tlet err: any;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t\tif (t === ERROR) err = v;\n\t\t}\n\t});\n\tunsub();\n\tif (err) throw err;\n\treturn val as T;\n}\n\nfunction getVal<T>(n: Node<T>): T {\n\tif (n.status === \"disconnected\") {\n\t\treturn pull(n);\n\t}\n\treturn n.get() as T;\n}\n\n/**\n * Creates a nanostores-compatible atom.\n *\n * @param initial - Initial value.\n * @returns `NanoAtom<T>`\n *\n * @category compat\n */\nexport function atom<T>(initial: T): NanoAtom<T> {\n\tconst n = state<T>(initial, {\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t});\n\n\treturn createStore(n, {\n\t\tset: (value: T) => n.down([[DATA, value]]),\n\t});\n}\n\n/**\n * Creates a nanostores-compatible computed store.\n *\n * @param stores - One or more atoms/computed stores.\n * @param fn - Compute function.\n * @returns `NanoComputed<T>`\n *\n * @category compat\n */\nexport function computed<T, A>(\n\tstoreA: NanoAtom<A> | NanoComputed<A>,\n\tfn: (a: A) => T,\n): NanoComputed<T>;\nexport function computed<T, A, B>(\n\tstores: [NanoAtom<A> | NanoComputed<A>, NanoAtom<B> | NanoComputed<B>],\n\tfn: (a: A, b: B) => T,\n): NanoComputed<T>;\nexport function computed<T, A, B, C>(\n\tstores: [\n\t\tNanoAtom<A> | NanoComputed<A>,\n\t\tNanoAtom<B> | NanoComputed<B>,\n\t\tNanoAtom<C> | NanoComputed<C>,\n\t],\n\tfn: (a: A, b: B, c: C) => T,\n): NanoComputed<T>;\nexport function computed<T>(stores: any, fn: (...args: any[]) => T): NanoComputed<T> {\n\tconst storeArray: Array<NanoAtom<any> | NanoComputed<any>> = Array.isArray(stores)\n\t\t? stores\n\t\t: [stores];\n\n\tconst n = dynamicNode(\n\t\t(get: DynGet) => {\n\t\t\tconst vals = storeArray.map((s) => {\n\t\t\t\tconst node = s._node;\n\t\t\t\tif (node.status === \"disconnected\") {\n\t\t\t\t\tpull(node);\n\t\t\t\t}\n\t\t\t\treturn get(node);\n\t\t\t});\n\t\t\treturn fn(...vals);\n\t\t},\n\t\t{\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t\tequals: Object.is as any,\n\t\t},\n\t);\n\n\treturn createStore(n);\n}\n\n/**\n * Creates a nanostores-compatible map.\n *\n * @param initial - Initial object value.\n * @returns `NanoMap<T>`\n *\n * @category compat\n */\nexport function map<T extends Record<string, unknown>>(initial: T): NanoMap<T> {\n\tconst n = state<T>(initial, {\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t\tequals: () => false,\n\t});\n\n\treturn createStore(n, {\n\t\tset: (value: T) => n.down([[DATA, value]]),\n\t\tsetKey: <K extends keyof T>(key: K, value: T[K]) => {\n\t\t\tconst current = getVal(n);\n\t\t\tn.down([[DATA, { ...current, [key]: value }]]);\n\t\t},\n\t});\n}\n\n/**\n * Returns the current value of the store.\n *\n * @category compat\n */\nexport function getValue<T>(store: NanoAtom<T> | NanoComputed<T>): T {\n\treturn store.get();\n}\n\n/**\n * Adds a listener for the store start (first listener connected).\n *\n * @category compat\n */\nexport function onStart(store: NanoAtom<any> | NanoComputed<any>, cb: () => void): void {\n\tconst node = store._node;\n\tlet callbacks = START_LISTENERS.get(node);\n\tif (!callbacks) {\n\t\tcallbacks = new Set();\n\t\tSTART_LISTENERS.set(node, callbacks);\n\t}\n\tcallbacks.add(cb);\n}\n\n/**\n * Adds a listener for the store stop (last listener disconnected).\n *\n * @category compat\n */\nexport function onStop(store: NanoAtom<any> | NanoComputed<any>, cb: () => void): void {\n\tconst node = store._node;\n\tlet callbacks = STOP_LISTENERS.get(node);\n\tif (!callbacks) {\n\t\tcallbacks = new Set();\n\t\tSTOP_LISTENERS.set(node, callbacks);\n\t}\n\tcallbacks.add(cb);\n}\n\n/**\n * Adds a listener for the store mount (first listener connected).\n *\n * @returns A cleanup function called when the last listener is removed.\n * @category compat\n */\nexport function onMount(\n\tstore: NanoAtom<any> | NanoComputed<any>,\n\tcb: () => (() => void) | undefined,\n): void {\n\tonStart(store, () => {\n\t\tconst stop = cb();\n\t\tif (typeof stop === \"function\") onStop(store, stop);\n\t});\n}\n\n/**\n * Batches multiple store updates.\n *\n * @category compat\n */\nexport function action<Args extends any[], Return>(\n\t_store: NanoAtom<any> | NanoComputed<any>,\n\t_name: string,\n\tfn: (...args: Args) => Return,\n): (...args: Args) => Return {\n\treturn (...args: Args) => {\n\t\tlet result: any;\n\t\tbatch(() => {\n\t\t\tresult = fn(...args);\n\t\t});\n\t\treturn result as Return;\n\t};\n}\n","// ---------------------------------------------------------------------------\n// NestJS integration — Module, DI, Lifecycle, RxJS bridge (Phase 5.5)\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly into NestJS's DI container and RxJS-based ecosystem.\n// NestJS and RxJS are peer dependencies — install them in your NestJS app.\n//\n// Usage:\n// import { GraphReflyModule, InjectGraph, InjectNode, toObservable }\n// from '@graphrefly/graphrefly-ts/compat/nestjs';\n// ---------------------------------------------------------------------------\n\n// RxJS bridge (re-exported from extra for convenience)\nexport { observeGraph$, observeNode$, toMessages$, toObservable } from \"../../extra/observable.js\";\n\n// Decorators\nexport {\n\tCOMMAND_HANDLERS,\n\tCommandHandler,\n\ttype CommandHandlerMeta,\n\tCQRS_EVENT_HANDLERS,\n\tCRON_HANDLERS,\n\tEVENT_HANDLERS,\n\tEventHandler,\n\ttype EventHandlerMeta,\n\tGraphCron,\n\ttype GraphCronMeta,\n\tGraphInterval,\n\ttype GraphIntervalMeta,\n\tINTERVAL_HANDLERS,\n\tInjectCqrsGraph,\n\tInjectGraph,\n\tInjectNode,\n\tOnGraphEvent,\n\ttype OnGraphEventMeta,\n\tQUERY_HANDLERS,\n\tQueryHandler,\n\ttype QueryHandlerMeta,\n\tSAGA_HANDLERS,\n\tSagaHandler,\n\ttype SagaHandlerMeta,\n} from \"./decorators.js\";\n// Explorer (event/schedule discovery)\nexport { GraphReflyEventExplorer } from \"./explorer.js\";\n// Gateway helpers (Phase 5.1)\nexport {\n\tObserveGateway,\n\ttype ObserveGatewayOptions,\n\ttype ObserveSSEOptions,\n\ttype ObserveSubscriptionOptions,\n\ttype ObserveWsCommand,\n\ttype ObserveWsMessage,\n\tobserveSSE,\n\tobserveSubscription,\n} from \"./gateway.js\";\n// Actor bridge (Phase 5.1)\nexport {\n\tACTOR_KEY,\n\ttype ActorExtractor,\n\tfromHeader,\n\tfromJwtPayload,\n\tGraphReflyGuard,\n\tGraphReflyGuardImpl,\n\tgetActor,\n} from \"./guard.js\";\n// Module & DI\nexport {\n\ttype GraphReflyCqrsOptions,\n\ttype GraphReflyFeatureOptions,\n\tGraphReflyModule,\n\ttype GraphReflyRootOptions,\n} from \"./module.js\";\n// Injection tokens\nexport {\n\tGRAPHREFLY_REQUEST_GRAPH,\n\tGRAPHREFLY_ROOT_GRAPH,\n\tgetGraphToken,\n\tgetNodeToken,\n} from \"./tokens.js\";\n","// ---------------------------------------------------------------------------\n// RxJS bridge — reactive interop between GraphReFly nodes and RxJS Observables.\n// ---------------------------------------------------------------------------\n// Generic utilities for bridging GraphReFly's message protocol to RxJS\n// Observables. Works anywhere RxJS is available (NestJS, Angular, standalone).\n//\n// Usage:\n// import { toObservable, observeNode$ } from '@graphrefly/graphrefly-ts/extra';\n// const values$ = toObservable(myNode); // Observable<T>\n// const msgs$ = toMessages$(myNode); // Observable<Messages>\n// const node$ = observeNode$(graph, \"path\"); // Observable<T> via graph.observe\n// const all$ = observeGraph$(graph); // Observable<{ path, messages }>\n// ---------------------------------------------------------------------------\n\nimport { Observable } from \"rxjs\";\nimport { COMPLETE, DATA, ERROR, type Messages } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport type { Graph, GraphObserveAll, GraphObserveOne, ObserveOptions } from \"../graph/graph.js\";\n\n/**\n * Bridge a `Node<T>` to an RxJS `Observable<T>`.\n *\n * Emits the node's value on each `DATA` message. Maps `ERROR` to\n * `subscriber.error()` and `COMPLETE` to `subscriber.complete()`.\n * Protocol-internal signals (DIRTY, RESOLVED, PAUSE, etc.) are skipped.\n *\n * Unsubscribing the Observable unsubscribes the node.\n */\nexport function toObservable<T>(node: Node<T>): Observable<T> {\n\treturn new Observable<T>((subscriber) => {\n\t\tconst unsub = node.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsubscriber.next(m[1] as T);\n\t\t\t\t} else if (m[0] === ERROR) {\n\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (m[0] === COMPLETE) {\n\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn unsub;\n\t});\n}\n\n/**\n * Bridge a `Node<T>` to an `Observable<Messages>` — raw message batches.\n *\n * Each emission is a full `[[Type, Data?], ...]` batch. The Observable\n * terminates on ERROR or COMPLETE (the terminal batch is still emitted\n * as the final `next()` before the Observable signal).\n */\nexport function toMessages$<T>(node: Node<T>): Observable<Messages> {\n\treturn new Observable<Messages>((subscriber) => {\n\t\tconst unsub = node.subscribe((msgs) => {\n\t\t\tif (subscriber.closed) return;\n\t\t\tsubscriber.next(msgs);\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn unsub;\n\t});\n}\n\n/**\n * Observe a single node in a `Graph` as an `Observable<T>`.\n *\n * Equivalent to `toObservable(graph.resolve(path))` but routes through\n * `graph.observe()` so actor guards are respected when provided.\n */\nexport function observeNode$<T>(\n\tgraph: Graph,\n\tpath: string,\n\toptions?: ObserveOptions,\n): Observable<T> {\n\treturn new Observable<T>((subscriber) => {\n\t\tconst handle: GraphObserveOne = graph.observe(path, options);\n\t\tconst unsub = handle.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsubscriber.next(m[1] as T);\n\t\t\t\t} else if (m[0] === ERROR) {\n\t\t\t\t\tsubscriber.error(m[1]);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (m[0] === COMPLETE) {\n\t\t\t\t\tsubscriber.complete();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn unsub;\n\t});\n}\n\n/**\n * Observe all nodes in a `Graph` as an `Observable<{ path, messages }>`.\n *\n * Each emission carries the qualified node path and the raw message batch.\n * The Observable never self-completes (graphs are long-lived); dispose by\n * unsubscribing.\n */\nexport function observeGraph$(\n\tgraph: Graph,\n\toptions?: ObserveOptions,\n): Observable<{ path: string; messages: Messages }> {\n\treturn new Observable((subscriber) => {\n\t\tconst handle: GraphObserveAll = graph.observe(options);\n\t\tconst unsub = handle.subscribe((nodePath, messages) => {\n\t\t\tif (subscriber.closed) return;\n\t\t\tsubscriber.next({ path: nodePath, messages });\n\t\t});\n\t\treturn unsub;\n\t});\n}\n","// ---------------------------------------------------------------------------\n// NestJS decorators for GraphReFly DI, events, and scheduling.\n// ---------------------------------------------------------------------------\n// NOTE: esbuild (used by vitest/vite) uses TC39 Stage 3 decorators, not\n// legacy TypeScript experimental decorators. Method decorators receive\n// (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext). We use\n// context.addInitializer() to register metadata when the class instance is\n// created, which runs before NestJS lifecycle hooks.\n// ---------------------------------------------------------------------------\n\nimport { Inject } from \"@nestjs/common\";\nimport {\n\tGRAPHREFLY_REQUEST_GRAPH,\n\tGRAPHREFLY_ROOT_GRAPH,\n\tgetGraphToken,\n\tgetNodeToken,\n} from \"./tokens.js\";\n\n/** Class constructor key for decorator registries and Nest `ModuleRef.get()`. */\nexport type DecoratorHostConstructor = abstract new (...args: unknown[]) => unknown;\n\n/**\n * TC39 Stage 3 class method decorator first argument (the method itself).\n * Narrower than `Function` for Biome `noBannedTypes`.\n */\nexport type DecoratorBoundMethod = (...args: unknown[]) => unknown;\n\n// ---------------------------------------------------------------------------\n// Global registries (populated by decorator initializers, read by explorer)\n// ---------------------------------------------------------------------------\n\nexport interface OnGraphEventMeta {\n\tnodeName: string;\n\tmethodKey: string | symbol;\n}\n\nexport interface GraphIntervalMeta {\n\tms: number;\n\tmethodKey: string | symbol;\n}\n\nexport interface GraphCronMeta {\n\texpr: string;\n\tmethodKey: string | symbol;\n}\n\n/** Registry: constructor → event handler metadata. */\nexport const EVENT_HANDLERS = new Map<DecoratorHostConstructor, OnGraphEventMeta[]>();\n/** Registry: constructor → interval metadata. */\nexport const INTERVAL_HANDLERS = new Map<DecoratorHostConstructor, GraphIntervalMeta[]>();\n/** Registry: constructor → cron metadata. */\nexport const CRON_HANDLERS = new Map<DecoratorHostConstructor, GraphCronMeta[]>();\n\n// ---------------------------------------------------------------------------\n// CQRS decorator metadata & registries (Phase 5.5 — CQRS replacement)\n// ---------------------------------------------------------------------------\n\nexport interface CommandHandlerMeta {\n\tcqrsName: string;\n\tcommandName: string;\n\tmethodKey: string | symbol;\n}\n\nexport interface EventHandlerMeta {\n\tcqrsName: string;\n\teventName: string;\n\tmethodKey: string | symbol;\n}\n\nexport interface QueryHandlerMeta {\n\tcqrsName: string;\n\tprojectionName: string;\n\tmethodKey: string | symbol;\n}\n\nexport interface SagaHandlerMeta {\n\tcqrsName: string;\n\teventNames: readonly string[];\n\tsagaName: string;\n\tmethodKey: string | symbol;\n}\n\n/** Registry: constructor → command handler metadata. */\nexport const COMMAND_HANDLERS = new Map<DecoratorHostConstructor, CommandHandlerMeta[]>();\n/** Registry: constructor → event handler metadata. */\nexport const CQRS_EVENT_HANDLERS = new Map<DecoratorHostConstructor, EventHandlerMeta[]>();\n/** Registry: constructor → query handler metadata. */\nexport const QUERY_HANDLERS = new Map<DecoratorHostConstructor, QueryHandlerMeta[]>();\n/** Registry: constructor → saga handler metadata. */\nexport const SAGA_HANDLERS = new Map<DecoratorHostConstructor, SagaHandlerMeta[]>();\n\n// ---------------------------------------------------------------------------\n// DI decorators\n// ---------------------------------------------------------------------------\n\n/**\n * Inject a `Graph` instance into a NestJS service or controller.\n *\n * - No argument → injects the root graph (from `forRoot()`).\n * - With `name` → injects the named feature graph (from `forFeature({ name })`).\n * - With `\"request\"` → injects the request-scoped graph (requires `requestScope: true`).\n *\n * @example\n * ```ts\n * @Injectable()\n * export class PaymentService {\n * constructor(\n * @InjectGraph() private root: Graph,\n * @InjectGraph(\"payments\") private payments: Graph,\n * ) {}\n * }\n * ```\n */\nexport function InjectGraph(name?: string): ParameterDecorator & PropertyDecorator {\n\tif (name === \"request\") return Inject(GRAPHREFLY_REQUEST_GRAPH);\n\treturn Inject(name ? getGraphToken(name) : GRAPHREFLY_ROOT_GRAPH);\n}\n\n/**\n * Inject a `CqrsGraph` instance into a NestJS service or controller.\n *\n * Typed alternative to `@InjectGraph(name)` — returns `CqrsGraph` instead of `Graph`,\n * giving access to `.command()`, `.dispatch()`, `.event()`, `.projection()`, `.saga()`.\n *\n * @param name - The CQRS graph name (from `forCqrs({ name })`).\n *\n * @example\n * ```ts\n * @Injectable()\n * export class OrderService {\n * constructor(@InjectCqrsGraph(\"orders\") private orders: CqrsGraph) {\n * orders.dispatch(\"placeOrder\", { id: \"1\" }); // fully typed\n * }\n * }\n * ```\n */\nexport function InjectCqrsGraph(name: string): ParameterDecorator & PropertyDecorator {\n\treturn Inject(getGraphToken(name));\n}\n\n/**\n * Inject a `Node` from the graph by its qualified path.\n *\n * The path must be declared in the `nodes` array of `forRoot()` or `forFeature()`.\n * The module registers a factory provider that resolves the node from the root graph\n * at injection time.\n *\n * @example\n * ```ts\n * GraphReflyModule.forRoot({ nodes: [\"payment::validate\"] })\n *\n * @Injectable()\n * export class PaymentService {\n * constructor(@InjectNode(\"payment::validate\") private validate: Node<boolean>) {}\n * }\n * ```\n */\nexport function InjectNode(path: string): ParameterDecorator & PropertyDecorator {\n\treturn Inject(getNodeToken(path));\n}\n\n// ---------------------------------------------------------------------------\n// Event & schedule method decorators (TC39 Stage 3 decorator API)\n// ---------------------------------------------------------------------------\n\n/**\n * Subscribe a method to a graph node's DATA emissions — replaces `@OnEvent()`.\n *\n * The method is called with the value payload on each `DATA` message from the\n * named node. Routes through `graph.observe()` so actor guards are respected.\n * Subscription is created on module init and disposed on destroy.\n *\n * For full protocol access (DIRTY, COMPLETE, ERROR, custom types), use\n * `graph.observe()` directly instead of this decorator.\n *\n * @param nodeName - Qualified node path (e.g. `\"orders::placed\"`).\n *\n * @example\n * ```ts\n * @Injectable()\n * export class OrderService {\n * @OnGraphEvent(\"orders::placed\")\n * handleOrder(value: Order) { ... }\n * }\n * ```\n */\nexport function OnGraphEvent(\n\tnodeName: string,\n): (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void {\n\treturn (_value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => {\n\t\tconst methodKey = context.name;\n\t\tcontext.addInitializer(function (this: unknown) {\n\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\tconst existing = EVENT_HANDLERS.get(ctor) ?? [];\n\t\t\texisting.push({ nodeName, methodKey });\n\t\t\tEVENT_HANDLERS.set(ctor, existing);\n\t\t});\n\t};\n}\n\n/**\n * Run a method on a fixed interval — replaces `@Interval()` from `@nestjs/schedule`.\n *\n * Backed by a `fromTimer` node added to the root graph as `__schedule__.<className>.<methodName>`.\n * Visible in `graph.describe()`, pausable via `graph.signal(name, [[PAUSE]])`.\n *\n * @param ms - Interval in milliseconds.\n *\n * @example\n * ```ts\n * @Injectable()\n * export class CleanupService {\n * @GraphInterval(5000)\n * pruneStale() { ... }\n * }\n * ```\n */\nexport function GraphInterval(\n\tms: number,\n): (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void {\n\treturn (_value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => {\n\t\tconst methodKey = context.name;\n\t\tcontext.addInitializer(function (this: unknown) {\n\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\tconst existing = INTERVAL_HANDLERS.get(ctor) ?? [];\n\t\t\texisting.push({ ms, methodKey });\n\t\t\tINTERVAL_HANDLERS.set(ctor, existing);\n\t\t});\n\t};\n}\n\n/**\n * Run a method on a cron schedule — replaces `@Cron()` from `@nestjs/schedule`.\n *\n * Backed by a `fromCron` node added to the root graph as `__schedule__.<className>.<methodName>`.\n * Visible in `graph.describe()`, pausable via PAUSE/RESUME signals.\n *\n * @param expr - 5-field cron expression (`min hour dom month dow`).\n *\n * @example\n * ```ts\n * @Injectable()\n * export class ReportService {\n * @GraphCron(\"0 9 * * 1\")\n * weeklyReport() { ... }\n * }\n * ```\n */\nexport function GraphCron(\n\texpr: string,\n): (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void {\n\treturn (_value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => {\n\t\tconst methodKey = context.name;\n\t\tcontext.addInitializer(function (this: unknown) {\n\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\tconst existing = CRON_HANDLERS.get(ctor) ?? [];\n\t\t\texisting.push({ expr, methodKey });\n\t\t\tCRON_HANDLERS.set(ctor, existing);\n\t\t});\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// CQRS method decorators (Phase 5.5 — CQRS replacement)\n// ---------------------------------------------------------------------------\n\n/**\n * Register a method as a CQRS command handler — replaces `@CommandHandler()` from `@nestjs/cqrs`.\n *\n * The method receives `(payload, { emit })` — same signature as `CqrsGraph.command()` handlers.\n * Wired reactively via the explorer on module init.\n *\n * @param cqrsName - Name of the CQRS graph (from `forCqrs({ name })`).\n * @param commandName - Command to handle.\n *\n * @example\n * ```ts\n * @Injectable()\n * export class OrderService {\n * @CommandHandler(\"orders\", \"placeOrder\")\n * handlePlace(payload: PlaceOrderDto, { emit }: CommandActions) {\n * emit(\"orderPlaced\", { orderId: payload.id, amount: payload.amount });\n * }\n * }\n * ```\n */\nexport function CommandHandler(\n\tcqrsName: string,\n\tcommandName: string,\n): (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void {\n\treturn (_value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => {\n\t\tconst methodKey = context.name;\n\t\tcontext.addInitializer(function (this: unknown) {\n\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\tconst existing = COMMAND_HANDLERS.get(ctor) ?? [];\n\t\t\texisting.push({ cqrsName, commandName, methodKey });\n\t\t\tCOMMAND_HANDLERS.set(ctor, existing);\n\t\t});\n\t};\n}\n\n/**\n * Subscribe a method to CQRS event stream DATA — replaces `@EventsHandler()` from `@nestjs/cqrs`.\n *\n * The method receives each `CqrsEvent` envelope as events arrive. Subscription is reactive\n * via `graph.observe()` — actor guards are respected.\n *\n * @param cqrsName - Name of the CQRS graph.\n * @param eventName - Event stream to subscribe to.\n *\n * @example\n * ```ts\n * @Injectable()\n * export class NotificationService {\n * @EventHandler(\"orders\", \"orderPlaced\")\n * onOrderPlaced(event: CqrsEvent<{ orderId: string }>) {\n * console.log(\"Order placed:\", event.payload.orderId);\n * }\n * }\n * ```\n */\nexport function EventHandler(\n\tcqrsName: string,\n\teventName: string,\n): (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void {\n\treturn (_value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => {\n\t\tconst methodKey = context.name;\n\t\tcontext.addInitializer(function (this: unknown) {\n\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\tconst existing = CQRS_EVENT_HANDLERS.get(ctor) ?? [];\n\t\t\texisting.push({ cqrsName, eventName, methodKey });\n\t\t\tCQRS_EVENT_HANDLERS.set(ctor, existing);\n\t\t});\n\t};\n}\n\n/**\n * Subscribe a method to CQRS projection changes — replaces `@QueryHandler()` from `@nestjs/cqrs`.\n *\n * The method is called reactively whenever the projection's value changes (DATA emission).\n * This is push-based, not request-response — the projection recomputes on upstream events.\n *\n * @param cqrsName - Name of the CQRS graph.\n * @param projectionName - Projection to observe.\n *\n * @example\n * ```ts\n * @Injectable()\n * export class DashboardService {\n * @QueryHandler(\"orders\", \"orderCount\")\n * onCountChanged(count: number) {\n * this.broadcast({ type: \"orderCount\", value: count });\n * }\n * }\n * ```\n */\nexport function QueryHandler(\n\tcqrsName: string,\n\tprojectionName: string,\n): (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void {\n\treturn (_value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => {\n\t\tconst methodKey = context.name;\n\t\tcontext.addInitializer(function (this: unknown) {\n\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\tconst existing = QUERY_HANDLERS.get(ctor) ?? [];\n\t\t\texisting.push({ cqrsName, projectionName, methodKey });\n\t\t\tQUERY_HANDLERS.set(ctor, existing);\n\t\t});\n\t};\n}\n\n/**\n * Register a method as a CQRS saga — replaces RxJS saga streams from `@nestjs/cqrs`.\n *\n * The method receives each new `CqrsEvent` from the specified event streams. Backed by\n * `CqrsGraph.saga()` — tracks last-processed entry, only delivers new events.\n *\n * @param cqrsName - Name of the CQRS graph.\n * @param sagaName - Name for this saga node in the graph.\n * @param eventNames - Event streams to react to.\n *\n * @example\n * ```ts\n * @Injectable()\n * export class FulfillmentService {\n * @SagaHandler(\"orders\", \"fulfillment\", [\"orderPlaced\", \"paymentConfirmed\"])\n * onOrderFlow(event: CqrsEvent) {\n * if (event.type === \"paymentConfirmed\") this.shipOrder(event.payload);\n * }\n * }\n * ```\n */\nexport function SagaHandler(\n\tcqrsName: string,\n\tsagaName: string,\n\teventNames: readonly string[],\n): (value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void {\n\treturn (_value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => {\n\t\tconst methodKey = context.name;\n\t\tcontext.addInitializer(function (this: unknown) {\n\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\tconst existing = SAGA_HANDLERS.get(ctor) ?? [];\n\t\t\texisting.push({ cqrsName, eventNames, sagaName, methodKey });\n\t\t\tSAGA_HANDLERS.set(ctor, existing);\n\t\t});\n\t};\n}\n","// ---------------------------------------------------------------------------\n// NestJS DI tokens for GraphReFly integration.\n// ---------------------------------------------------------------------------\n\n/** Injection token for the root `Graph` singleton created by `forRoot()`. */\nexport const GRAPHREFLY_ROOT_GRAPH = Symbol.for(\"graphrefly:root-graph\");\n\n/** Injection token for `forRoot()` / `forFeature()` options. */\nexport const GRAPHREFLY_MODULE_OPTIONS = Symbol.for(\"graphrefly:module-options\");\n\n/** Injection token for the request-scoped `Graph` created by request scope config. */\nexport const GRAPHREFLY_REQUEST_GRAPH = Symbol.for(\"graphrefly:request-graph\");\n\n/**\n * Get the injection token for a named feature graph.\n *\n * Feature graphs registered via `GraphReflyModule.forFeature({ name })` are\n * injectable using this token (or via the `@InjectGraph(name)` decorator).\n */\nexport function getGraphToken(name: string): symbol {\n\treturn Symbol.for(`graphrefly:graph:${name}`);\n}\n\n/**\n * Get the injection token for a node at a qualified path.\n *\n * Nodes declared in `forRoot({ nodes })` or `forFeature({ nodes })` are\n * injectable using this token (or via the `@InjectNode(path)` decorator).\n */\nexport function getNodeToken(path: string): symbol {\n\treturn Symbol.for(`graphrefly:node:${path}`);\n}\n","/**\n * Core reactive sources, sinks, and utilities (roadmap §2.3).\n *\n * Each API returns a {@link Node} built with {@link node}, {@link producer},\n * {@link derived}, or {@link effect} — no second protocol.\n *\n * Protocol/system/ingest adapters (fromHTTP, fromWebSocket, fromKafka, etc.)\n * live in {@link ./adapters.ts}.\n */\n\nimport { existsSync, watch } from \"node:fs\";\nimport { resolve as resolvePath } from \"node:path\";\nimport { wallClockNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, ERROR, type Message } from \"../core/messages.js\";\nimport { type Node, type NodeOptions, type NodeSink, node } from \"../core/node.js\";\nimport { producer } from \"../core/sugar.js\";\nimport { type CronSchedule, matchesCron, parseCron } from \"./cron.js\";\n\ntype ExtraOpts = Omit<NodeOptions, \"describeKind\">;\n\nfunction sourceOpts(opts?: ExtraOpts): NodeOptions {\n\treturn { describeKind: \"producer\", ...opts };\n}\n\n/** @internal kept for toArray which is an operator, not a producer */\nfunction operatorOpts(opts?: ExtraOpts): NodeOptions {\n\treturn { describeKind: \"operator\", ...opts };\n}\n\n/** Options for {@link fromTimer} / {@link fromPromise} / {@link fromAsyncIter}. */\nexport type AsyncSourceOpts = ExtraOpts & { signal?: AbortSignal };\n\n/**\n * Values accepted by {@link fromAny}.\n *\n * @category extra\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Options for {@link fromCron}. */\nexport type FromCronOptions = ExtraOpts & {\n\t/** Polling interval in ms. Default `60_000`. */\n\ttickMs?: number;\n\t/** Output format: `\"timestamp_ns\"` (default) emits wall-clock nanoseconds; `\"date\"` emits a `Date` object. */\n\toutput?: \"timestamp_ns\" | \"date\";\n};\n\n/** DOM-style event target (browser or `node:events`). */\nexport type EventTargetLike = {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (ev: unknown) => void,\n\t\toptions?: boolean | { capture?: boolean; passive?: boolean; once?: boolean },\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (ev: unknown) => void,\n\t\toptions?: boolean | { capture?: boolean; passive?: boolean; once?: boolean },\n\t): void;\n};\n\nexport type FSEventType = \"change\" | \"rename\" | \"create\" | \"delete\";\nexport type FSEvent = {\n\ttype: FSEventType;\n\tpath: string;\n\troot: string;\n\trelative_path: string;\n\tsrc_path?: string;\n\tdest_path?: string;\n\ttimestamp_ns: number;\n};\n\nexport type FromFSWatchOptions = ExtraOpts & {\n\trecursive?: boolean;\n\tdebounce?: number;\n\tinclude?: string[];\n\texclude?: string[];\n};\n\n/** @internal Shared with adapters.ts for glob matching in fromFSWatch / fromGitHook. */\nexport function escapeRegexChar(ch: string): string {\n\treturn /[\\\\^$+?.()|[\\]{}]/.test(ch) ? `\\\\${ch}` : ch;\n}\n\n/** @internal */\nexport function globToRegExp(glob: string): RegExp {\n\tlet out = \"^\";\n\tfor (let i = 0; i < glob.length; i += 1) {\n\t\tconst ch = glob[i];\n\t\tif (ch === \"*\") {\n\t\t\tconst next = glob[i + 1];\n\t\t\tif (next === \"*\") {\n\t\t\t\tout += \".*\";\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tout += \"[^/]*\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tout += escapeRegexChar(ch);\n\t}\n\tout += \"$\";\n\treturn new RegExp(out);\n}\n\n/** @internal */\nexport function matchesAnyPattern(path: string, patterns: RegExp[]): boolean {\n\tfor (const pattern of patterns) {\n\t\tif (pattern.test(path)) return true;\n\t}\n\treturn false;\n}\n\nfunction wrapSubscribeHook<T>(inner: Node<T>, before: (sink: NodeSink) => void): Node<T> {\n\tconst wrapper = node<T>([inner], ([val]) => val as T, {\n\t\tdescribeKind: \"operator\",\n\t\tinitial: inner.get(),\n\t});\n\tconst origSubscribe = wrapper.subscribe.bind(wrapper);\n\t(wrapper as { subscribe: typeof wrapper.subscribe }).subscribe = (sink, hints) => {\n\t\tbefore(sink);\n\t\treturn origSubscribe(sink, hints);\n\t};\n\treturn wrapper;\n}\n\n/**\n * Builds a timer-driven source: one-shot (first tick then `COMPLETE`) or periodic (`0`, `1`, `2`, …).\n *\n * @param ms - Milliseconds before the first emission.\n * @param opts - Producer options plus optional `period` for repeating ticks and optional `signal` (`AbortSignal`) to cancel with `ERROR`.\n * @returns `Node<number>` — tick counter from `0`; teardown clears timers.\n *\n * @example\n * ```ts\n * import { fromTimer } from \"@graphrefly/graphrefly-ts\";\n *\n * fromTimer(250, { period: 1_000 });\n * ```\n *\n * @category extra\n */\nexport function fromTimer(ms: number, opts?: AsyncSourceOpts & { period?: number }): Node<number> {\n\tconst { signal, period, ...rest } = opts ?? {};\n\treturn producer<number>((_d, a) => {\n\t\tlet done = false;\n\t\tlet count = 0;\n\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tdone = true;\n\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst finish = () => {\n\t\t\tif (done) return;\n\t\t\ta.emit(count++);\n\t\t\tif (period != null) {\n\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\tif (done) return;\n\t\t\t\t\ta.emit(count++);\n\t\t\t\t}, period);\n\t\t\t} else {\n\t\t\t\tdone = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tqueueMicrotask(() => a.down([[COMPLETE]]));\n\t\t\t}\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tif (done) return;\n\t\t\tcleanup();\n\t\t\ta.down([[ERROR, signal!.reason]]);\n\t\t};\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn;\n\t\t}\n\t\tt = setTimeout(finish, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\treturn cleanup;\n\t}, sourceOpts(rest));\n}\n\n/**\n * Polls on an interval; when the current minute matches a 5-field cron expression, emits once (see {@link parseCron}).\n *\n * @param expr - Cron string (`min hour dom month dow`).\n * @param opts - Producer options plus `tickMs` (default `60_000`) and `output` (`timestamp_ns` default, or `date` for `Date` values).\n * @returns `Node<number>` (nanosecond timestamp) or `Node<Date>` when `output: \"date\"`.\n *\n * @example\n * ```ts\n * import { fromCron } from \"@graphrefly/graphrefly-ts\";\n *\n * fromCron(\"0 9 * * 1\");\n * ```\n *\n * @category extra\n */\nexport function fromCron(expr: string, opts?: FromCronOptions & { output: \"date\" }): Node<Date>;\nexport function fromCron(expr: string, opts?: FromCronOptions): Node<number>;\nexport function fromCron(expr: string, opts?: FromCronOptions): Node<number | Date> {\n\tconst schedule: CronSchedule = parseCron(expr);\n\tconst { tickMs: tickOpt, output, ...rest } = opts ?? {};\n\tconst tickMs = tickOpt ?? 60_000;\n\tconst emitDate = output === \"date\";\n\treturn producer<number | Date>(\n\t\t(_d, a) => {\n\t\t\tlet lastFiredKey = -1;\n\t\t\tconst check = () => {\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key =\n\t\t\t\t\tnow.getFullYear() * 100_000_000 +\n\t\t\t\t\t(now.getMonth() + 1) * 1_000_000 +\n\t\t\t\t\tnow.getDate() * 10_000 +\n\t\t\t\t\tnow.getHours() * 100 +\n\t\t\t\t\tnow.getMinutes();\n\t\t\t\tif (key !== lastFiredKey && matchesCron(schedule, now)) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\ta.emit(emitDate ? now : wallClockNs());\n\t\t\t\t}\n\t\t\t};\n\t\t\tcheck();\n\t\t\tconst id = setInterval(check, tickMs);\n\t\t\treturn () => clearInterval(id);\n\t\t},\n\t\t{ ...sourceOpts(rest), name: rest.name ?? `cron:${expr}` },\n\t);\n}\n\n/**\n * Wraps a DOM-style `addEventListener` target; each event becomes a `DATA` emission.\n *\n * @param target - Object with `addEventListener` / `removeEventListener`.\n * @param type - Event name (e.g. `\"click\"`).\n * @param opts - Producer options plus listener options (`capture`, `passive`, `once`).\n * @returns `Node<T>` — event payloads; teardown removes the listener.\n *\n * @example\n * ```ts\n * import { fromEvent } from \"@graphrefly/graphrefly-ts\";\n *\n * fromEvent(document.body, \"click\");\n * ```\n *\n * @category extra\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts?: ExtraOpts & { capture?: boolean; passive?: boolean; once?: boolean },\n): Node<T> {\n\tconst { capture, passive, once, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tconst handler = (e: unknown) => {\n\t\t\ta.emit(e as T);\n\t\t};\n\t\tconst options = { capture, passive, once };\n\t\ttarget.addEventListener(type, handler, options);\n\t\treturn () => target.removeEventListener(type, handler, options);\n\t}, sourceOpts(rest));\n}\n\n/**\n * Watches filesystem paths and emits debounced change events.\n *\n * Uses `fs.watch` only (no polling fallback). Teardown closes all watchers.\n *\n * @category extra\n */\nexport function fromFSWatch(paths: string | string[], opts?: FromFSWatchOptions): Node<FSEvent> {\n\tconst list = Array.isArray(paths) ? paths : [paths];\n\tif (list.length === 0) {\n\t\tthrow new RangeError(\"fromFSWatch expects at least one path\");\n\t}\n\tconst { recursive = true, debounce = 100, include, exclude, ...rest } = opts ?? {};\n\tconst includePatterns = include?.map(globToRegExp) ?? [];\n\tconst excludePatterns = (exclude ?? [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\"]).map(\n\t\tglobToRegExp,\n\t);\n\treturn producer<FSEvent>((_d, a) => {\n\t\tconst pending = new Map<string, FSEvent>();\n\t\tconst watchers: ReturnType<typeof watch>[] = [];\n\t\tlet stopped = false;\n\t\tlet terminalEmitted = false;\n\t\tlet generation = 0;\n\t\tconst closeWatchers = () => {\n\t\t\tfor (const watcher of watchers.splice(0)) watcher.close();\n\t\t};\n\t\tconst emitError = (err: unknown) => {\n\t\t\tif (terminalEmitted) return;\n\t\t\tterminalEmitted = true;\n\t\t\tstopped = true;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t\tpending.clear();\n\t\t\tcloseWatchers();\n\t\t\ta.down([[ERROR, err]]);\n\t\t};\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst flush = (token: number) => {\n\t\t\ttimer = undefined;\n\t\t\tif (stopped || terminalEmitted) return;\n\t\t\tif (pending.size === 0) return;\n\t\t\tconst batchMessages: Message[] = [];\n\t\t\tfor (const evt of pending.values()) batchMessages.push([DATA, evt]);\n\t\t\tpending.clear();\n\t\t\tif (stopped || terminalEmitted || token !== generation) return;\n\t\t\ta.down(batchMessages);\n\t\t};\n\t\ttry {\n\t\t\tfor (const basePath of list) {\n\t\t\t\tconst watcher = watch(\n\t\t\t\t\tbasePath,\n\t\t\t\t\t{ recursive },\n\t\t\t\t\t(eventType: \"rename\" | \"change\", fileName: string | Buffer | null) => {\n\t\t\t\t\t\tif (stopped || terminalEmitted) return;\n\t\t\t\t\t\tif (fileName == null) return;\n\t\t\t\t\t\tconst rel = String(fileName).replaceAll(\"\\\\\", \"/\");\n\t\t\t\t\t\tconst abs = resolvePath(basePath, String(fileName));\n\t\t\t\t\t\tconst normalized = abs.replaceAll(\"\\\\\", \"/\");\n\t\t\t\t\t\tconst root = resolvePath(basePath).replaceAll(\"\\\\\", \"/\");\n\t\t\t\t\t\tconst relForMatch = rel.startsWith(\"./\") ? rel.slice(2) : rel;\n\t\t\t\t\t\tconst included =\n\t\t\t\t\t\t\tincludePatterns.length === 0 ||\n\t\t\t\t\t\t\tmatchesAnyPattern(normalized, includePatterns) ||\n\t\t\t\t\t\t\tmatchesAnyPattern(relForMatch, includePatterns);\n\t\t\t\t\t\tif (!included) return;\n\t\t\t\t\t\tconst excluded =\n\t\t\t\t\t\t\tmatchesAnyPattern(normalized, excludePatterns) ||\n\t\t\t\t\t\t\tmatchesAnyPattern(relForMatch, excludePatterns);\n\t\t\t\t\t\tif (excluded) return;\n\t\t\t\t\t\tlet kind: FSEventType = \"change\";\n\t\t\t\t\t\tif (eventType === \"rename\") {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tkind = existsSync(normalized) ? \"create\" : \"delete\";\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tkind = \"rename\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpending.set(normalized, {\n\t\t\t\t\t\t\ttype: kind,\n\t\t\t\t\t\t\tpath: normalized,\n\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\trelative_path: relForMatch,\n\t\t\t\t\t\t\ttimestamp_ns: wallClockNs(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\t\t\tconst token = generation;\n\t\t\t\t\t\ttimer = setTimeout(() => flush(token), debounce);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\twatcher.on(\"error\", (err) => emitError(err));\n\t\t\t\twatchers.push(watcher);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\temitError(err);\n\t\t}\n\t\treturn () => {\n\t\t\tstopped = true;\n\t\t\tgeneration += 1;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t\tcloseWatchers();\n\t\t\tpending.clear();\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/**\n * Drains a synchronous iterable; each item is `DATA`, then `COMPLETE`, or `ERROR` if iteration throws.\n *\n * @param iterable - Values to emit in order.\n * @param opts - Optional producer options.\n * @returns `Node<T>` — one emission per element.\n *\n * @example\n * ```ts\n * import { fromIter } from \"@graphrefly/graphrefly-ts\";\n *\n * fromIter([1, 2, 3]);\n * ```\n *\n * @category extra\n */\nexport function fromIter<T>(iterable: Iterable<T>, opts?: ExtraOpts): Node<T> {\n\treturn producer<T>((_d, a) => {\n\t\tlet cancelled = false;\n\t\ttry {\n\t\t\tfor (const x of iterable) {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ta.emit(x);\n\t\t\t}\n\t\t\tif (!cancelled) a.down([[COMPLETE]]);\n\t\t} catch (e) {\n\t\t\tif (!cancelled) a.down([[ERROR, e]]);\n\t\t}\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t}, sourceOpts(opts));\n}\n\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\n/**\n * Lifts a Promise (or thenable) to a single-value stream: one `DATA` then `COMPLETE`, or `ERROR` on rejection.\n *\n * @param p - Promise to await.\n * @param opts - Producer options plus optional `signal` for abort → `ERROR` with reason.\n * @returns `Node<T>` — settles once.\n *\n * @example\n * ```ts\n * import { fromPromise } from \"@graphrefly/graphrefly-ts\";\n *\n * fromPromise(Promise.resolve(42));\n * ```\n *\n * @category extra\n */\nexport function fromPromise<T>(p: Promise<T> | PromiseLike<T>, opts?: AsyncSourceOpts): Node<T> {\n\tconst { signal, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tlet settled = false;\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\ta.down([[ERROR, signal!.reason]]);\n\t\t};\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn;\n\t\t}\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid Promise.resolve(p).then(\n\t\t\t(v) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\ta.emit(v as T);\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t},\n\t\t\t(e) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\ta.down([[ERROR, e]]);\n\t\t\t},\n\t\t);\n\t\treturn () => {\n\t\t\tsettled = true;\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/**\n * Reads an async iterable; each `next()` value becomes `DATA`; `COMPLETE` when done; `ERROR` on failure.\n *\n * @param iterable - Async source (`for await` shape).\n * @param opts - Producer options plus optional `signal` to abort the pump.\n * @returns `Node<T>` — async pull stream.\n *\n * @example\n * ```ts\n * import { fromAsyncIter } from \"@graphrefly/graphrefly-ts\";\n *\n * async function* gen() {\n * yield 1;\n * }\n * fromAsyncIter(gen());\n * ```\n *\n * @category extra\n */\nexport function fromAsyncIter<T>(iterable: AsyncIterable<T>, opts?: AsyncSourceOpts): Node<T> {\n\tconst { signal: outerSignal, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tconst ac = new AbortController();\n\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\tif (outerSignal?.aborted) {\n\t\t\tac.abort(outerSignal.reason);\n\t\t} else {\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t}\n\t\tconst signal = outerSignal ?? ac.signal;\n\t\tlet cancelled = false;\n\t\tconst it = iterable[Symbol.asyncIterator]();\n\t\tconst pump = (): void => {\n\t\t\tif (cancelled || signal.aborted) return;\n\t\t\tvoid Promise.resolve(it.next()).then(\n\t\t\t\t(step) => {\n\t\t\t\t\tif (cancelled || signal.aborted) return;\n\t\t\t\t\tif (step.done) {\n\t\t\t\t\t\tqueueMicrotask(() => a.down([[COMPLETE]]));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ta.emit(step.value as T);\n\t\t\t\t\tqueueMicrotask(pump);\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (!cancelled && !signal.aborted) a.down([[ERROR, e]]);\n\t\t\t\t},\n\t\t\t);\n\t\t};\n\t\tqueueMicrotask(pump);\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\tac.abort();\n\t\t\tvoid Promise.resolve(it.return?.()).catch(() => undefined);\n\t\t};\n\t}, sourceOpts(rest));\n}\n\nfunction isNode(x: unknown): x is Node {\n\treturn (\n\t\tx != null &&\n\t\ttypeof (x as Node).subscribe === \"function\" &&\n\t\ttypeof (x as Node).get === \"function\"\n\t);\n}\n\n/**\n * Coerces a value to a `Node` by shape: existing `Node` passthrough, thenable → {@link fromPromise},\n * async iterable → {@link fromAsyncIter}, sync iterable → {@link fromIter}, else scalar → {@link of}.\n *\n * @param input - Any value to wrap.\n * @param opts - Passed through when a Promise/async path is chosen.\n * @returns `Node` of the inferred element type.\n *\n * @example\n * ```ts\n * import { fromAny, state } from \"@graphrefly/graphrefly-ts\";\n *\n * fromAny(state(1));\n * fromAny(Promise.resolve(2));\n * ```\n *\n * @category extra\n */\nexport function fromAny<T>(input: NodeInput<T>, opts?: AsyncSourceOpts): Node<T> {\n\tif (isNode(input)) {\n\t\treturn input as Node<T>;\n\t}\n\tif (isThenable(input)) {\n\t\treturn fromPromise(input as PromiseLike<T>, opts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as { [Symbol.asyncIterator]?: unknown; [Symbol.iterator]?: unknown };\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn fromAsyncIter(input as AsyncIterable<T>, opts);\n\t\t}\n\t\tif (typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn fromIter(input as Iterable<T>, opts);\n\t\t}\n\t}\n\t// scalar fallback\n\treturn of(input as T);\n}\n\n/**\n * Emits each argument as `DATA` in order, then `COMPLETE` (implemented via {@link fromIter}).\n *\n * @param values - Values to emit.\n * @returns `Node<T>` — finite sequence.\n *\n * @example\n * ```ts\n * import { of } from \"@graphrefly/graphrefly-ts\";\n *\n * of(1, 2, 3);\n * ```\n *\n * @category extra\n */\nexport function of<T>(...values: T[]): Node<T> {\n\treturn fromIter(values, undefined);\n}\n\n/**\n * Completes immediately with no `DATA` (cold `EMPTY` analogue).\n *\n * @param opts - Optional producer options.\n * @returns `Node<T>` — terminal `COMPLETE` only.\n *\n * @example\n * ```ts\n * import { empty } from \"@graphrefly/graphrefly-ts\";\n *\n * empty();\n * ```\n *\n * @category extra\n */\nexport function empty<T = never>(opts?: ExtraOpts): Node<T> {\n\treturn producer<T>((_d, a) => {\n\t\ta.down([[COMPLETE]]);\n\t\treturn undefined;\n\t}, sourceOpts(opts));\n}\n\n/**\n * Never emits and never completes until teardown (cold `NEVER` analogue).\n *\n * @param opts - Optional producer options.\n * @returns `Node<T>` — silent until unsubscribed.\n *\n * @example\n * ```ts\n * import { never } from \"@graphrefly/graphrefly-ts\";\n *\n * never();\n * ```\n *\n * @category extra\n */\nexport function never<T = never>(opts?: ExtraOpts): Node<T> {\n\treturn producer<T>(() => undefined, sourceOpts(opts));\n}\n\n/**\n * Emits `ERROR` as soon as the producer starts (cold error source).\n *\n * @param err - Error payload forwarded as `ERROR` data.\n * @param opts - Optional producer options.\n * @returns `Node<never>` — terminates with `ERROR`.\n *\n * @example\n * ```ts\n * import { throwError } from \"@graphrefly/graphrefly-ts\";\n *\n * throwError(new Error(\"fail\"));\n * ```\n *\n * @category extra\n */\nexport function throwError(err: unknown, opts?: ExtraOpts): Node<never> {\n\treturn producer<never>((_d, a) => {\n\t\ta.down([[ERROR, err]]);\n\t\treturn undefined;\n\t}, sourceOpts(opts));\n}\n\n/**\n * Subscribes immediately and runs `fn` for each upstream `DATA`; returns unsubscribe.\n *\n * @param source - Upstream node.\n * @param fn - Side effect per value.\n * @param opts - Effect node options.\n * @returns Unsubscribe function (idempotent).\n *\n * @example\n * ```ts\n * import { forEach, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const u = forEach(state(1), (v) => console.log(v));\n * u();\n * ```\n *\n * @category extra\n */\nexport function forEach<T>(source: Node<T>, fn: (value: T) => void, opts?: ExtraOpts): () => void {\n\tconst inner = node([source as Node], () => undefined, {\n\t\tdescribeKind: \"effect\",\n\t\t...opts,\n\t\tonMessage(msg: Message, _i, _a) {\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\tfn(msg[1] as T);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n\treturn inner.subscribe(() => {});\n}\n\n/**\n * Buffers every `DATA`; on upstream `COMPLETE` emits one `DATA` with the full array then `COMPLETE`.\n *\n * @param source - Upstream node.\n * @param opts - Optional node options (operator describe kind).\n * @returns `Node<T[]>` — single array emission before completion.\n *\n * @example\n * ```ts\n * import { of, toArray } from \"@graphrefly/graphrefly-ts\";\n *\n * toArray(of(1, 2, 3));\n * ```\n *\n * @category extra\n */\nexport function toArray<T>(source: Node<T>, opts?: ExtraOpts): Node<T[]> {\n\tconst acc: T[] = [];\n\treturn node<T[]>([source as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg: Message, _i, a) {\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\tacc.push(msg[1] as T);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\ta.emit([...acc]);\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n/**\n * Multicasts upstream: one subscription to `source` while this wrapper has subscribers (via {@link producer}).\n *\n * @param source - Upstream node to share.\n * @param opts - Producer options; `initial` seeds from `source.get()` when set by factory.\n * @returns `Node<T>` — hot ref-counted bridge.\n *\n * @example\n * ```ts\n * import { share, state } from \"@graphrefly/graphrefly-ts\";\n *\n * share(state(0));\n * ```\n *\n * @category extra\n */\nexport function share<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\treturn producer<T>(\n\t\t(_d, a) =>\n\t\t\tsource.subscribe((msgs) => {\n\t\t\t\ta.down(msgs);\n\t\t\t}),\n\t\t{ ...sourceOpts(opts), initial: source.get() },\n\t);\n}\n\n/**\n * Like {@link share} with a bounded replay buffer: new subscribers receive the last `bufferSize`\n * `DATA` payloads (as separate batches) before live updates.\n *\n * @param source - Upstream node.\n * @param bufferSize - Maximum past values to replay (≥ 1).\n * @param opts - Producer options.\n * @returns `Node<T>` — multicast with replay on subscribe.\n *\n * @example\n * ```ts\n * import { replay, state } from \"@graphrefly/graphrefly-ts\";\n *\n * replay(state(0), 3);\n * ```\n *\n * @category extra\n */\nexport function replay<T>(source: Node<T>, bufferSize: number, opts?: ExtraOpts): Node<T> {\n\tif (bufferSize < 1) throw new RangeError(\"replay expects bufferSize >= 1\");\n\tconst buf: T[] = [];\n\tconst inner = producer<T>(\n\t\t(_d, a) =>\n\t\t\tsource.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\t\tbuf.push(m[1] as T);\n\t\t\t\t\t\tif (buf.length > bufferSize) buf.shift();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ta.down(msgs);\n\t\t\t}),\n\t\t{ ...sourceOpts(opts), initial: source.get() },\n\t);\n\treturn wrapSubscribeHook(inner, (sink) => {\n\t\tfor (const v of buf) {\n\t\t\tsink([[DATA, v]]);\n\t\t}\n\t});\n}\n\n/**\n * {@link replay} with `bufferSize === 1` — replays the latest `DATA` to new subscribers.\n *\n * @param source - Upstream node.\n * @param opts - Producer options.\n * @returns `Node<T>` — share + last-value replay.\n *\n * @example\n * ```ts\n * import { cached, state } from \"@graphrefly/graphrefly-ts\";\n *\n * cached(state(0));\n * ```\n *\n * @category extra\n */\nexport function cached<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\treturn replay(source, 1, opts);\n}\n\n/**\n * Converts the first `DATA` on `source` into a Promise; rejects on `ERROR` or `COMPLETE` without data.\n *\n * @param source - Node to read once.\n * @returns Promise of the first value.\n *\n * @example\n * ```ts\n * import { firstValueFrom, of } from \"@graphrefly/graphrefly-ts\";\n *\n * await firstValueFrom(of(42));\n * ```\n *\n * @category extra\n */\nexport function firstValueFrom<T>(source: Node<T>): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst unsub = source.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (settled) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tresolve(m[1] as T);\n\t\t\t\t\tqueueMicrotask(() => unsub());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(m[1]);\n\t\t\t\t\tqueueMicrotask(() => unsub());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(new Error(\"completed without DATA\"));\n\t\t\t\t\tqueueMicrotask(() => unsub());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}\n\n// ——————————————————————————————————————————————————————————————\n// RxJS-compatible aliases\n// ——————————————————————————————————————————————————————————————\n\n/**\n * RxJS-named alias for {@link replay} — multicast with a replay buffer of size `bufferSize`.\n *\n * @param source - Upstream node.\n * @param bufferSize - Replay depth (≥ 1).\n * @param opts - Producer options.\n * @returns Same behavior as `replay`.\n *\n * @example\n * ```ts\n * import { shareReplay, state } from \"@graphrefly/graphrefly-ts\";\n *\n * shareReplay(state(0), 5);\n * ```\n *\n * @category extra\n */\nexport const shareReplay = replay;\n","/**\n * Minimal 5-field cron parser and matcher (minute hour day-of-month month day-of-week).\n * Ported from callbag-recharge `extra/cron.ts` for `fromCron` (roadmap §2.3).\n */\nexport interface CronSchedule {\n\tminutes: Set<number>;\n\thours: Set<number>;\n\tdaysOfMonth: Set<number>;\n\tmonths: Set<number>;\n\tdaysOfWeek: Set<number>;\n}\n\nfunction parseField(field: string, min: number, max: number): Set<number> {\n\tconst result = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\tconst [range, stepStr] = part.split(\"/\");\n\t\tconst step = stepStr ? Number.parseInt(stepStr, 10) : 1;\n\t\tif (Number.isNaN(step) || step < 1) throw new Error(`Invalid cron step: ${part}`);\n\t\tlet start: number;\n\t\tlet end: number;\n\t\tif (range === \"*\") {\n\t\t\tstart = min;\n\t\t\tend = max;\n\t\t} else if (range.includes(\"-\")) {\n\t\t\tconst [a, b] = range.split(\"-\");\n\t\t\tstart = Number.parseInt(a, 10);\n\t\t\tend = Number.parseInt(b, 10);\n\t\t} else {\n\t\t\tstart = Number.parseInt(range, 10);\n\t\t\tend = start;\n\t\t}\n\t\tif (Number.isNaN(start) || Number.isNaN(end)) throw new Error(`Invalid cron field: ${field}`);\n\t\tif (start < min || end > max)\n\t\t\tthrow new Error(`Cron field out of range: ${field} (${min}-${max})`);\n\t\tif (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);\n\t\tfor (let i = start; i <= end; i += step) result.add(i);\n\t}\n\treturn result;\n}\n\n/**\n * Parses a standard 5-field cron expression into a {@link CronSchedule}.\n *\n * Supports `*`, ranges (`1-5`), steps (`*\\/5`, `0-30/10`), and comma-separated\n * lists. Fields are: minute (0–59), hour (0–23), day-of-month (1–31),\n * month (1–12), day-of-week (0–6, Sunday = 0).\n *\n * @param expr - Five-field whitespace-separated cron string (e.g. `\"0 9 * * 1-5\"`).\n * @returns Parsed {@link CronSchedule} with one `Set<number>` per field.\n * @throws Error when the expression does not have exactly 5 fields, contains\n * out-of-range values, or uses an invalid step.\n *\n * @example\n * ```ts\n * import { parseCron } from \"@graphrefly/graphrefly-ts\";\n *\n * const sched = parseCron(\"0 9 * * 1-5\"); // weekdays at 09:00\n * sched.hours; // Set { 9 }\n * sched.daysOfWeek; // Set { 1, 2, 3, 4, 5 }\n * ```\n */\nexport function parseCron(expr: string): CronSchedule {\n\tconst parts = expr.trim().split(/\\s+/);\n\tif (parts.length !== 5) throw new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);\n\treturn {\n\t\tminutes: parseField(parts[0], 0, 59),\n\t\thours: parseField(parts[1], 0, 23),\n\t\tdaysOfMonth: parseField(parts[2], 1, 31),\n\t\tmonths: parseField(parts[3], 1, 12),\n\t\tdaysOfWeek: parseField(parts[4], 0, 6),\n\t};\n}\n\n/**\n * Returns `true` if `date` satisfies every field of `schedule`.\n *\n * @param schedule - Parsed schedule from {@link parseCron}.\n * @param date - Moment to test (local time via `getMinutes`, `getHours`, etc.).\n * @returns `true` when all five cron fields match the given date.\n *\n * @example\n * ```ts\n * import { parseCron, matchesCron } from \"@graphrefly/graphrefly-ts\";\n *\n * const sched = parseCron(\"30 8 * * 1\"); // Mondays at 08:30\n * const monday = new Date(\"2026-03-30T08:30:00\"); // a Monday\n * matchesCron(sched, monday); // true\n * ```\n */\nexport function matchesCron(schedule: CronSchedule, date: Date): boolean {\n\treturn (\n\t\tschedule.minutes.has(date.getMinutes()) &&\n\t\tschedule.hours.has(date.getHours()) &&\n\t\tschedule.daysOfMonth.has(date.getDate()) &&\n\t\tschedule.months.has(date.getMonth() + 1) &&\n\t\tschedule.daysOfWeek.has(date.getDay())\n\t);\n}\n","// ---------------------------------------------------------------------------\n// GraphReflyEventExplorer — discovers @OnGraphEvent, @GraphInterval, @GraphCron\n// decorated methods and wires them to the root graph.\n// ---------------------------------------------------------------------------\n// Registered by `forRoot()`. On module init, reads global decorator registries,\n// resolves provider instances via ModuleRef, and creates reactive subscriptions\n// / timer nodes. On module destroy, disposes all subscriptions and removes\n// schedule nodes from the graph.\n//\n// Runtime is fully reactive — push-based via graph.observe().\n// No polling, no microtasks, no promises. Timer nodes use central fromTimer /\n// fromCron primitives.\n// ---------------------------------------------------------------------------\n\nimport type { OnModuleDestroy, OnModuleInit } from \"@nestjs/common\";\nimport type { ModuleRef } from \"@nestjs/core\";\nimport { DATA, type Messages } from \"../../core/messages.js\";\nimport { fromCron, fromTimer } from \"../../extra/sources.js\";\nimport type { Graph, GraphObserveOne } from \"../../graph/graph.js\";\nimport type { CqrsGraph } from \"../../patterns/cqrs.js\";\nimport {\n\tCOMMAND_HANDLERS,\n\ttype CommandHandlerMeta,\n\tCQRS_EVENT_HANDLERS,\n\tCRON_HANDLERS,\n\ttype DecoratorBoundMethod,\n\ttype DecoratorHostConstructor,\n\tEVENT_HANDLERS,\n\ttype EventHandlerMeta,\n\ttype GraphCronMeta,\n\ttype GraphIntervalMeta,\n\tINTERVAL_HANDLERS,\n\ttype OnGraphEventMeta,\n\tQUERY_HANDLERS,\n\ttype QueryHandlerMeta,\n\tSAGA_HANDLERS,\n\ttype SagaHandlerMeta,\n} from \"./decorators.js\";\nimport { getGraphToken } from \"./tokens.js\";\n\n/** Monotonic counter for schedule node name disambiguation. */\nlet scheduleSeq = 0;\n\nexport class GraphReflyEventExplorer implements OnModuleInit, OnModuleDestroy {\n\tprivate readonly disposers: Array<() => void> = [];\n\tprivate readonly scheduleNodeNames: string[] = [];\n\n\tconstructor(\n\t\tprivate readonly graph: Graph,\n\t\tprivate readonly moduleRef: ModuleRef,\n\t) {}\n\n\tonModuleInit(): void {\n\t\tthis.wireEvents();\n\t\tthis.wireIntervals();\n\t\tthis.wireCrons();\n\t\tthis.wireCqrsCommands();\n\t\tthis.wireCqrsEvents();\n\t\tthis.wireCqrsQueries();\n\t\tthis.wireCqrsSagas();\n\t}\n\n\tonModuleDestroy(): void {\n\t\tfor (const dispose of this.disposers) dispose();\n\t\tthis.disposers.length = 0;\n\n\t\tfor (const name of this.scheduleNodeNames) {\n\t\t\ttry {\n\t\t\t\tthis.graph.remove(name);\n\t\t\t} catch {\n\t\t\t\t// Node may already be gone if graph.destroy() ran first.\n\t\t\t}\n\t\t}\n\t\tthis.scheduleNodeNames.length = 0;\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// @OnGraphEvent — reactive subscription via graph.observe()\n\t// -----------------------------------------------------------------------\n\n\tprivate wireEvents(): void {\n\t\tfor (const [ctor, metas] of EVENT_HANDLERS) {\n\t\t\tconst instance = this.resolveInstance(ctor);\n\t\t\tif (!instance) continue;\n\n\t\t\tfor (const meta of metas) {\n\t\t\t\tthis.wireEventHandler(instance, meta);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate wireEventHandler(instance: object, meta: OnGraphEventMeta): void {\n\t\tconst method = (instance as Record<string | symbol, DecoratorBoundMethod>)[meta.methodKey];\n\t\tif (typeof method !== \"function\") return;\n\n\t\tconst bound = method.bind(instance);\n\n\t\t// Route through graph.observe() so actor guards are respected.\n\t\tconst handle = this.observeNode(meta.nodeName);\n\t\tconst unsub = handle.subscribe((msgs: Messages) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tbound(m[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.disposers.push(unsub);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// @GraphInterval — reactive via fromTimer central timer primitive\n\t// -----------------------------------------------------------------------\n\n\tprivate wireIntervals(): void {\n\t\tfor (const [ctor, metas] of INTERVAL_HANDLERS) {\n\t\t\tconst instance = this.resolveInstance(ctor);\n\t\t\tif (!instance) continue;\n\n\t\t\tfor (const meta of metas) {\n\t\t\t\tthis.wireIntervalHandler(instance, ctor, meta);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate wireIntervalHandler(\n\t\tinstance: object,\n\t\tctor: DecoratorHostConstructor,\n\t\tmeta: GraphIntervalMeta,\n\t): void {\n\t\tconst method = (instance as Record<string | symbol, DecoratorBoundMethod>)[meta.methodKey];\n\t\tif (typeof method !== \"function\") return;\n\n\t\tconst bound = method.bind(instance);\n\t\tconst className = ctor.name ?? \"anonymous\";\n\t\tconst nodeName = `__schedule__.${className}.${String(meta.methodKey)}.${scheduleSeq++}`;\n\n\t\tconst timerNode = fromTimer(meta.ms, { period: meta.ms, name: nodeName });\n\t\tthis.graph.add(nodeName, timerNode);\n\t\tthis.scheduleNodeNames.push(nodeName);\n\n\t\t// Subscribe through graph.observe() for consistency.\n\t\tconst handle = this.observeNode(nodeName);\n\t\tconst unsub = handle.subscribe((msgs: Messages) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === DATA) bound(m[1]);\n\t\t\t}\n\t\t});\n\t\tthis.disposers.push(unsub);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// @GraphCron — reactive via fromCron central timer primitive\n\t// -----------------------------------------------------------------------\n\n\tprivate wireCrons(): void {\n\t\tfor (const [ctor, metas] of CRON_HANDLERS) {\n\t\t\tconst instance = this.resolveInstance(ctor);\n\t\t\tif (!instance) continue;\n\n\t\t\tfor (const meta of metas) {\n\t\t\t\tthis.wireCronHandler(instance, ctor, meta);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate wireCronHandler(\n\t\tinstance: object,\n\t\tctor: DecoratorHostConstructor,\n\t\tmeta: GraphCronMeta,\n\t): void {\n\t\tconst method = (instance as Record<string | symbol, DecoratorBoundMethod>)[meta.methodKey];\n\t\tif (typeof method !== \"function\") return;\n\n\t\tconst bound = method.bind(instance);\n\t\tconst className = ctor.name ?? \"anonymous\";\n\t\tconst nodeName = `__schedule__.${className}.${String(meta.methodKey)}.${scheduleSeq++}`;\n\n\t\tconst cronNode = fromCron(meta.expr, { name: nodeName });\n\t\tthis.graph.add(nodeName, cronNode);\n\t\tthis.scheduleNodeNames.push(nodeName);\n\n\t\t// Subscribe through graph.observe() for consistency.\n\t\tconst handle = this.observeNode(nodeName);\n\t\tconst unsub = handle.subscribe((msgs: Messages) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === DATA) bound(m[1]);\n\t\t\t}\n\t\t});\n\t\tthis.disposers.push(unsub);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// @CommandHandler — register method as CqrsGraph command handler\n\t// -----------------------------------------------------------------------\n\n\tprivate wireCqrsCommands(): void {\n\t\tfor (const [ctor, metas] of COMMAND_HANDLERS) {\n\t\t\tconst instance = this.resolveInstance(ctor);\n\t\t\tif (!instance) continue;\n\n\t\t\tfor (const meta of metas) {\n\t\t\t\tthis.wireCqrsCommand(instance, meta);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate wireCqrsCommand(instance: object, meta: CommandHandlerMeta): void {\n\t\tconst method = (instance as Record<string | symbol, DecoratorBoundMethod>)[meta.methodKey];\n\t\tif (typeof method !== \"function\") return;\n\n\t\tconst bound = method.bind(instance);\n\t\tconst cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);\n\t\tif (!cqrsGraph) return;\n\n\t\tcqrsGraph.command(meta.commandName, bound);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// @EventHandler — subscribe method to CQRS event stream\n\t// -----------------------------------------------------------------------\n\n\tprivate wireCqrsEvents(): void {\n\t\tfor (const [ctor, metas] of CQRS_EVENT_HANDLERS) {\n\t\t\tconst instance = this.resolveInstance(ctor);\n\t\t\tif (!instance) continue;\n\n\t\t\tfor (const meta of metas) {\n\t\t\t\tthis.wireCqrsEventHandler(instance, meta);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate wireCqrsEventHandler(instance: object, meta: EventHandlerMeta): void {\n\t\tconst method = (instance as Record<string | symbol, DecoratorBoundMethod>)[meta.methodKey];\n\t\tif (typeof method !== \"function\") return;\n\n\t\tconst bound = method.bind(instance);\n\t\tconst cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);\n\t\tif (!cqrsGraph) return;\n\n\t\t// Ensure the event stream exists.\n\t\tcqrsGraph.event(meta.eventName);\n\n\t\t// Snapshot the highest seq already in the log so we only deliver new events.\n\t\t// Tracking by seq (monotonic per-graph) is robust against reactive log trim.\n\t\tconst eventNode = cqrsGraph.resolve(meta.eventName);\n\t\tconst currentSnap = eventNode.get() as\n\t\t\t| { value: { entries: readonly { seq: number }[] } }\n\t\t\t| undefined;\n\t\tconst existingEntries = currentSnap?.value?.entries;\n\t\tlet lastSeq =\n\t\t\texistingEntries && existingEntries.length > 0\n\t\t\t\t? existingEntries[existingEntries.length - 1].seq\n\t\t\t\t: 0;\n\n\t\t// Subscribe reactively via graph.observe() — respects actor guards.\n\t\tconst handle = this.observeNodeOn(cqrsGraph, meta.eventName);\n\t\tconst unsub = handle.subscribe((msgs: Messages) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tconst snap = m[1] as { value: { entries: readonly { seq: number }[] } };\n\t\t\t\t\tfor (const entry of snap.value.entries) {\n\t\t\t\t\t\tif (entry.seq > lastSeq) {\n\t\t\t\t\t\t\tbound(entry);\n\t\t\t\t\t\t\tlastSeq = entry.seq;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.disposers.push(unsub);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// @QueryHandler — subscribe method to CQRS projection changes\n\t// -----------------------------------------------------------------------\n\n\tprivate wireCqrsQueries(): void {\n\t\tfor (const [ctor, metas] of QUERY_HANDLERS) {\n\t\t\tconst instance = this.resolveInstance(ctor);\n\t\t\tif (!instance) continue;\n\n\t\t\tfor (const meta of metas) {\n\t\t\t\tthis.wireCqrsQuery(instance, meta);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate wireCqrsQuery(instance: object, meta: QueryHandlerMeta): void {\n\t\tconst method = (instance as Record<string | symbol, DecoratorBoundMethod>)[meta.methodKey];\n\t\tif (typeof method !== \"function\") return;\n\n\t\tconst bound = method.bind(instance);\n\t\tconst cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);\n\t\tif (!cqrsGraph) return;\n\n\t\t// Subscribe reactively to the projection node — push on every DATA.\n\t\tconst handle = this.observeNodeOn(cqrsGraph, meta.projectionName);\n\t\tconst unsub = handle.subscribe((msgs: Messages) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tbound(m[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.disposers.push(unsub);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// @SagaHandler — register method as CqrsGraph saga (subgraph side effect)\n\t// -----------------------------------------------------------------------\n\n\tprivate wireCqrsSagas(): void {\n\t\tfor (const [ctor, metas] of SAGA_HANDLERS) {\n\t\t\tconst instance = this.resolveInstance(ctor);\n\t\t\tif (!instance) continue;\n\n\t\t\tfor (const meta of metas) {\n\t\t\t\tthis.wireCqrsSaga(instance, meta);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate wireCqrsSaga(instance: object, meta: SagaHandlerMeta): void {\n\t\tconst method = (instance as Record<string | symbol, DecoratorBoundMethod>)[meta.methodKey];\n\t\tif (typeof method !== \"function\") return;\n\n\t\tconst bound = method.bind(instance);\n\t\tconst cqrsGraph = this.resolveCqrsGraph(meta.cqrsName);\n\t\tif (!cqrsGraph) return;\n\n\t\tcqrsGraph.saga(meta.sagaName, meta.eventNames, bound);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// Helpers\n\t// -----------------------------------------------------------------------\n\n\tprivate observeNode(name: string): GraphObserveOne {\n\t\t// Overload resolution picks ObserveResult; cast to the correct single-node type.\n\t\treturn this.graph.observe(name) as unknown as GraphObserveOne;\n\t}\n\n\tprivate observeNodeOn(graph: Graph, name: string): GraphObserveOne {\n\t\treturn graph.observe(name) as unknown as GraphObserveOne;\n\t}\n\n\tprivate resolveCqrsGraph(name: string): CqrsGraph | null {\n\t\ttry {\n\t\t\treturn this.moduleRef.get(getGraphToken(name), { strict: false }) as CqrsGraph;\n\t\t} catch {\n\t\t\tconsole.warn(\n\t\t\t\t`[GraphReFly] CqrsGraph \"${name}\" not found in DI — ` +\n\t\t\t\t\t`did you import GraphReflyModule.forCqrs({ name: \"${name}\" })?`,\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate resolveInstance(ctor: DecoratorHostConstructor): object | null {\n\t\ttry {\n\t\t\treturn this.moduleRef.get(ctor, { strict: false });\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n}\n","/**\n * Watermark-based backpressure controller — reactive PAUSE/RESUME flow control.\n *\n * Purely synchronous, event-driven. No timers, no polling, no Promises.\n * Each controller instance uses a unique lockId so multiple controllers\n * on the same upstream node do not collide.\n *\n * @module\n */\n\nimport { type Messages, PAUSE, RESUME } from \"../core/messages.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type WatermarkOptions = {\n\t/** Pending count at which PAUSE is sent upstream. */\n\thighWaterMark: number;\n\t/** Pending count at which RESUME is sent upstream (after being paused). */\n\tlowWaterMark: number;\n};\n\nexport type WatermarkController = {\n\t/** Call when a DATA message is buffered/enqueued. Returns `true` if PAUSE was just sent. */\n\tonEnqueue(): boolean;\n\t/** Call when a buffered item is consumed. Returns `true` if RESUME was just sent. */\n\tonDequeue(): boolean;\n\t/** Current un-consumed item count. */\n\treadonly pending: number;\n\t/** Whether upstream is currently paused by this controller. */\n\treadonly paused: boolean;\n\t/** Dispose: if paused, sends RESUME to unblock upstream. */\n\tdispose(): void;\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nlet nextLockId = 0;\n\n/**\n * Creates a watermark-based backpressure controller.\n *\n * @param sendUp - Callback that delivers messages upstream (typically `handle.up`).\n * @param opts - High/low watermark thresholds (item counts).\n * @returns A {@link WatermarkController}.\n *\n * @example\n * ```ts\n * const handle = graph.observe(\"fast-source\");\n * const wm = createWatermarkController(\n * (msgs) => handle.up(msgs),\n * { highWaterMark: 64, lowWaterMark: 16 },\n * );\n *\n * // In sink callback:\n * handle.subscribe((msgs) => {\n * for (const msg of msgs) {\n * if (msg[0] === DATA) {\n * buffer.push(msg[1]);\n * wm.onEnqueue();\n * }\n * }\n * });\n *\n * // When consumer drains:\n * const item = buffer.shift();\n * wm.onDequeue();\n * ```\n *\n * @category extra\n */\nexport function createWatermarkController(\n\tsendUp: (messages: Messages) => void,\n\topts: WatermarkOptions,\n): WatermarkController {\n\tif (opts.highWaterMark < 1) throw new RangeError(\"highWaterMark must be >= 1\");\n\tif (opts.lowWaterMark < 0) throw new RangeError(\"lowWaterMark must be >= 0\");\n\tif (opts.lowWaterMark >= opts.highWaterMark)\n\t\tthrow new RangeError(\"lowWaterMark must be < highWaterMark\");\n\tconst lockId = Symbol(`bp-${++nextLockId}`);\n\tlet pending = 0;\n\tlet paused = false;\n\n\treturn {\n\t\tonEnqueue(): boolean {\n\t\t\tpending += 1;\n\t\t\tif (!paused && pending >= opts.highWaterMark) {\n\t\t\t\tpaused = true;\n\t\t\t\tsendUp([[PAUSE, lockId]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tonDequeue(): boolean {\n\t\t\tif (pending > 0) pending -= 1;\n\t\t\tif (paused && pending <= opts.lowWaterMark) {\n\t\t\t\tpaused = false;\n\t\t\t\tsendUp([[RESUME, lockId]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tget pending() {\n\t\t\treturn pending;\n\t\t},\n\t\tget paused() {\n\t\t\treturn paused;\n\t\t},\n\t\tdispose() {\n\t\t\tif (paused) {\n\t\t\t\tpaused = false;\n\t\t\t\tsendUp([[RESUME, lockId]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","// ---------------------------------------------------------------------------\n// NestJS Gateway helpers — reactive bridges from graph.observe() to transports.\n// ---------------------------------------------------------------------------\n// All helpers are push-based: they subscribe to `graph.observe()` with actor\n// context and forward DATA messages to the transport. No polling.\n//\n// Actor-scoped observation respects node guards (Phase 1.5). Clients only\n// see DATA values from nodes their Actor is allowed to observe.\n// ---------------------------------------------------------------------------\n\nimport type { Actor } from \"../../core/actor.js\";\nimport { COMPLETE, DATA, ERROR, type Messages, TEARDOWN } from \"../../core/messages.js\";\nimport { createWatermarkController, type WatermarkController } from \"../../extra/backpressure.js\";\nimport type { Graph, GraphObserveOne } from \"../../graph/graph.js\";\n\n// ---------------------------------------------------------------------------\n// Shared types\n// ---------------------------------------------------------------------------\n\n/**\n * Client-to-server commands for the WebSocket observe protocol.\n */\nexport type ObserveWsCommand =\n\t| { type: \"subscribe\"; path: string }\n\t| { type: \"unsubscribe\"; path: string }\n\t| { type: \"ack\"; path: string; count?: number };\n\n/**\n * Server-to-client messages for the WebSocket observe protocol.\n */\nexport type ObserveWsMessage<T = unknown> =\n\t| { type: \"data\"; path: string; value: T }\n\t| { type: \"error\"; path: string; error: string }\n\t| { type: \"complete\"; path: string }\n\t| { type: \"subscribed\"; path: string }\n\t| { type: \"unsubscribed\"; path: string }\n\t| { type: \"err\"; message: string };\n\n// ---------------------------------------------------------------------------\n// observeSSE — graph.observe() → SSE ReadableStream\n// ---------------------------------------------------------------------------\n\nexport type ObserveSSEOptions = {\n\tactor?: Actor;\n\tserialize?: (value: unknown) => string;\n\tkeepAliveMs?: number;\n\tsignal?: AbortSignal;\n\t/** Pending DATA count at which PAUSE is sent upstream. Enables backpressure when set. */\n\thighWaterMark?: number;\n\t/** Pending DATA count at which RESUME is sent upstream. Defaults to `Math.floor(highWaterMark / 2)`. */\n\tlowWaterMark?: number;\n};\n\n/**\n * Creates an SSE `ReadableStream` that streams DATA values from a graph node.\n *\n * Routes through `graph.observe(path, { actor })` so node guards are respected.\n * The stream emits `event: data` for DATA, `event: error` for ERROR, and\n * `event: complete` for COMPLETE (then closes). TEARDOWN also closes the stream.\n *\n * @param graph - The graph to observe.\n * @param path - Qualified node path to observe.\n * @param opts - Actor context, serialization, keep-alive.\n * @returns A `ReadableStream<Uint8Array>` suitable for NestJS SSE endpoints.\n *\n * @example\n * ```ts\n * @Sse(\"events/:path\")\n * streamEvents(@Param(\"path\") path: string, @Req() req: Request) {\n * return observeSSE(this.graph, path, { actor: getActor(req) });\n * }\n * ```\n */\nexport function observeSSE(\n\tgraph: Graph,\n\tpath: string,\n\topts?: ObserveSSEOptions,\n): ReadableStream<Uint8Array> {\n\tconst { actor, serialize = defaultSerialize, keepAliveMs, signal } = opts ?? {};\n\tconst encoder = new TextEncoder();\n\tlet stop: (() => void) | undefined;\n\tconst useBackpressure = opts?.highWaterMark != null;\n\n\tlet wm: WatermarkController | undefined;\n\tlet pullResolve: (() => void) | undefined;\n\n\t// When backpressure is enabled we tag buffered entries so pull() only calls\n\t// onDequeue for DATA frames (not keepalive, ERROR, or COMPLETE frames).\n\ttype BufEntry = { frame: Uint8Array; counted: boolean };\n\tconst taggedBuf: BufEntry[] = [];\n\tlet closed = false;\n\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tlet keepAlive: ReturnType<typeof setInterval> | undefined;\n\t\t\tlet unsub: () => void = () => {};\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tif (keepAlive !== undefined) clearInterval(keepAlive);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t// Unsub first to prevent further sink callbacks during dispose.\n\t\t\t\tunsub();\n\t\t\t\twm?.dispose();\n\t\t\t\t// Resolve any parked pull() promise so the stream can finish.\n\t\t\t\tpullResolve?.();\n\t\t\t\tpullResolve = undefined;\n\t\t\t\t// Flush remaining buffered frames before closing.\n\t\t\t\tfor (const entry of taggedBuf) controller.enqueue(entry.frame);\n\t\t\t\ttaggedBuf.length = 0;\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tstop = close;\n\t\t\tconst onAbort = () => close();\n\n\t\t\tconst handle = graph.observe(path, { actor }) as unknown as GraphObserveOne;\n\n\t\t\tif (useBackpressure) {\n\t\t\t\twm = createWatermarkController((msgs) => handle.up(msgs), {\n\t\t\t\t\thighWaterMark: opts!.highWaterMark!,\n\t\t\t\t\tlowWaterMark: opts!.lowWaterMark ?? Math.floor(opts!.highWaterMark! / 2),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tunsub = handle.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tconst t = msg[0];\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tconst frame = encoder.encode(sseFrame(\"data\", serialize(msg[1])));\n\t\t\t\t\t\tif (useBackpressure) {\n\t\t\t\t\t\t\ttaggedBuf.push({ frame, counted: true });\n\t\t\t\t\t\t\twm!.onEnqueue();\n\t\t\t\t\t\t\tpullResolve?.();\n\t\t\t\t\t\t\tpullResolve = undefined;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontroller.enqueue(frame);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tconst frame = encoder.encode(sseFrame(\"error\", serialize(msg[1])));\n\t\t\t\t\t\tif (useBackpressure) {\n\t\t\t\t\t\t\ttaggedBuf.push({ frame, counted: false });\n\t\t\t\t\t\t\tpullResolve?.();\n\t\t\t\t\t\t\tpullResolve = undefined;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontroller.enqueue(frame);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclose();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else if (t === COMPLETE || t === TEARDOWN) {\n\t\t\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\t\t\tconst frame = encoder.encode(sseFrame(\"complete\"));\n\t\t\t\t\t\t\tif (useBackpressure) {\n\t\t\t\t\t\t\t\ttaggedBuf.push({ frame, counted: false });\n\t\t\t\t\t\t\t\tpullResolve?.();\n\t\t\t\t\t\t\t\tpullResolve = undefined;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontroller.enqueue(frame);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tclose();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// DIRTY, RESOLVED, and other protocol internals are not exposed to SSE clients\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (keepAliveMs !== undefined && keepAliveMs > 0) {\n\t\t\t\tkeepAlive = setInterval(() => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tif (useBackpressure) {\n\t\t\t\t\t\t// Keepalive frames bypass watermark accounting entirely.\n\t\t\t\t\t\ttaggedBuf.push({ frame: encoder.encode(\": keepalive\\n\\n\"), counted: false });\n\t\t\t\t\t\tpullResolve?.();\n\t\t\t\t\t\tpullResolve = undefined;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcontroller.enqueue(encoder.encode(\": keepalive\\n\\n\"));\n\t\t\t\t\t}\n\t\t\t\t}, keepAliveMs);\n\t\t\t}\n\t\t\tif (signal?.aborted) onAbort();\n\t\t\telse signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t},\n\t\tpull(controller) {\n\t\t\tif (!useBackpressure) return;\n\t\t\tif (closed) return;\n\t\t\tif (taggedBuf.length > 0) {\n\t\t\t\tconst entry = taggedBuf.shift()!;\n\t\t\t\tcontroller.enqueue(entry.frame);\n\t\t\t\tif (entry.counted) wm!.onDequeue();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// No data available — park until the sink callback pushes more.\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tpullResolve = resolve;\n\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\t// Guard against double-close (cancel may fire after COMPLETE/ERROR already closed).\n\t\t\ttry {\n\t\t\t\tstop?.();\n\t\t\t} catch {\n\t\t\t\t/* already closed */\n\t\t\t}\n\t\t},\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// observeSubscription — graph.observe() → AsyncIterableIterator (GraphQL)\n// ---------------------------------------------------------------------------\n\nexport type ObserveSubscriptionOptions<T = unknown> = {\n\tactor?: Actor;\n\t/**\n\t * Optional value filter. Only matching DATA values are enqueued.\n\t *\n\t * **Note:** `filter` and `highWaterMark` are semantically decoupled — the\n\t * watermark counts items that pass the filter, not total upstream work.\n\t * If the filter rejects most items, backpressure may never engage despite\n\t * high upstream throughput. For upstream-level resource protection, place a\n\t * filtering derived node in the graph before the observe point instead.\n\t */\n\tfilter?: (value: T) => boolean;\n\t/** Pending DATA count at which PAUSE is sent upstream. Enables backpressure when set. */\n\thighWaterMark?: number;\n\t/** Pending DATA count at which RESUME is sent upstream. Defaults to `Math.floor(highWaterMark / 2)`. */\n\tlowWaterMark?: number;\n};\n\n/**\n * Creates an `AsyncIterableIterator` that yields DATA values from a graph node.\n *\n * Designed for GraphQL subscription resolvers (Apollo, Mercurius, etc.).\n * Routes through `graph.observe(path, { actor })` for guard-scoped access.\n *\n * The iterator completes on COMPLETE/TEARDOWN and throws on ERROR.\n *\n * @param graph - The graph to observe.\n * @param path - Qualified node path to observe.\n * @param opts - Actor context, optional value filter.\n * @returns An async iterable that yields DATA payloads.\n *\n * @example\n * ```ts\n * // Apollo-style resolver\n * Subscription: {\n * orderStatus: {\n * subscribe: (_parent, args, ctx) =>\n * observeSubscription(ctx.graph, `orders::${args.id}::status`, {\n * actor: ctx.actor,\n * }),\n * },\n * }\n * ```\n */\nexport function observeSubscription<T = unknown>(\n\tgraph: Graph,\n\tpath: string,\n\topts?: ObserveSubscriptionOptions<T>,\n): AsyncIterableIterator<T> {\n\tconst { actor, filter } = opts ?? {};\n\n\ttype QueueItem = { done: false; value: T } | { done: true; value?: undefined; error?: Error };\n\n\tconst queue: QueueItem[] = [];\n\tconst waiters: Array<{\n\t\tresolve: (result: IteratorResult<T>) => void;\n\t\treject: (err: unknown) => void;\n\t}> = [];\n\tlet disposed = false;\n\n\tconst handle = graph.observe(path, { actor }) as unknown as GraphObserveOne;\n\n\tconst wm =\n\t\topts?.highWaterMark != null\n\t\t\t? createWatermarkController((msgs) => handle.up(msgs), {\n\t\t\t\t\thighWaterMark: opts.highWaterMark,\n\t\t\t\t\tlowWaterMark: opts.lowWaterMark ?? Math.floor(opts.highWaterMark / 2),\n\t\t\t\t})\n\t\t\t: undefined;\n\n\tconst dispose = () => {\n\t\tif (disposed) return;\n\t\tdisposed = true;\n\t\twm?.dispose();\n\t\tunsub();\n\t};\n\n\tconst push = (item: QueueItem) => {\n\t\tif (disposed) return;\n\t\tif (waiters.length > 0) {\n\t\t\tconst w = waiters.shift()!;\n\t\t\tif (item.done && item.error) w.reject(item.error);\n\t\t\telse if (item.done) w.resolve({ done: true, value: undefined });\n\t\t\telse w.resolve({ done: false, value: item.value as T });\n\t\t\t// Direct handoff to waiter — no queue growth, no watermark increment.\n\t\t} else {\n\t\t\tqueue.push(item);\n\t\t\tif (!item.done) wm?.onEnqueue();\n\t\t}\n\t};\n\n\tconst unsub = handle.subscribe((msgs: Messages) => {\n\t\tfor (const msg of msgs) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tconst value = msg[1] as T;\n\t\t\t\tif (filter && !filter(value)) continue;\n\t\t\t\tpush({ done: false, value });\n\t\t\t} else if (t === ERROR) {\n\t\t\t\tconst err = msg[1] instanceof Error ? msg[1] : new Error(String(msg[1]));\n\t\t\t\tpush({ done: true, error: err });\n\t\t\t\tdispose();\n\t\t\t\treturn;\n\t\t\t} else if (t === COMPLETE || t === TEARDOWN) {\n\t\t\t\tpush({ done: true });\n\t\t\t\tdispose();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t});\n\n\tconst iterator: AsyncIterableIterator<T> = {\n\t\tnext(): Promise<IteratorResult<T>> {\n\t\t\tif (queue.length > 0) {\n\t\t\t\tconst item = queue.shift()!;\n\t\t\t\tif (!item.done) wm?.onDequeue();\n\t\t\t\tif (item.done && item.error) return Promise.reject(item.error);\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\titem.done ? { done: true, value: undefined } : { done: false, value: item.value as T },\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (disposed) return Promise.resolve({ done: true, value: undefined });\n\t\t\treturn new Promise<IteratorResult<T>>((resolve, reject) => {\n\t\t\t\twaiters.push({ resolve, reject });\n\t\t\t});\n\t\t},\n\t\treturn(): Promise<IteratorReturnResult<undefined>> {\n\t\t\tdispose();\n\t\t\t// Resolve any pending waiters\n\t\t\tfor (const w of waiters) w.resolve({ done: true, value: undefined });\n\t\t\twaiters.length = 0;\n\t\t\treturn Promise.resolve({ done: true, value: undefined });\n\t\t},\n\t\tthrow(err: unknown): Promise<IteratorResult<T>> {\n\t\t\tdispose();\n\t\t\treturn Promise.reject(err);\n\t\t},\n\t\t[Symbol.asyncIterator]() {\n\t\t\treturn this;\n\t\t},\n\t};\n\n\treturn iterator;\n}\n\n// ---------------------------------------------------------------------------\n// ObserveGateway — graph.observe() → WebSocket (multi-path subscription)\n// ---------------------------------------------------------------------------\n\nexport type ObserveGatewayOptions = {\n\textractActor?: (client: unknown) => Actor | undefined;\n\tparse?: (data: string) => ObserveWsCommand;\n\t/** Pending DATA count per subscription at which PAUSE is sent upstream. Enables backpressure when set. */\n\thighWaterMark?: number;\n\t/** Pending DATA count per subscription at which RESUME is sent upstream. Defaults to `Math.floor(highWaterMark / 2)`. */\n\tlowWaterMark?: number;\n};\n\n/**\n * Manages per-client WebSocket subscriptions to graph nodes via `observe()`.\n *\n * Not a NestJS decorator or base class — a standalone helper that can be\n * wired into any WebSocket gateway. Each client can subscribe/unsubscribe\n * to individual node paths. Actor-scoped observation respects node guards.\n *\n * @example\n * ```ts\n * @WebSocketGateway()\n * export class GraphGateway {\n * private gw = new ObserveGateway(this.graph);\n *\n * constructor(@InjectGraph() private graph: Graph) {}\n *\n * handleConnection(client: WebSocket) {\n * this.gw.handleConnection(client);\n * }\n *\n * handleDisconnect(client: WebSocket) {\n * this.gw.handleDisconnect(client);\n * }\n *\n * @SubscribeMessage(\"observe\")\n * onObserve(client: WebSocket, data: unknown) {\n * this.gw.handleMessage(client, data);\n * }\n * }\n * ```\n */\nexport class ObserveGateway {\n\tprivate readonly clients = new Map<\n\t\tunknown,\n\t\tMap<string, { unsub: () => void; wm?: WatermarkController }>\n\t>();\n\tprivate readonly extractActor: (client: unknown) => Actor | undefined;\n\tprivate readonly parse: (data: string) => ObserveWsCommand;\n\tprivate readonly highWaterMark: number | undefined;\n\tprivate readonly lowWaterMark: number | undefined;\n\n\tconstructor(\n\t\tprivate readonly graph: Graph,\n\t\topts?: ObserveGatewayOptions,\n\t) {\n\t\tthis.extractActor = opts?.extractActor ?? (() => undefined);\n\t\tthis.parse = opts?.parse ?? defaultParseCommand;\n\t\tthis.highWaterMark = opts?.highWaterMark;\n\t\tthis.lowWaterMark = opts?.lowWaterMark;\n\t}\n\n\t/**\n\t * Register a new client. Call from `handleConnection`.\n\t */\n\thandleConnection(client: unknown): void {\n\t\tif (!this.clients.has(client)) {\n\t\t\tthis.clients.set(client, new Map());\n\t\t}\n\t}\n\n\t/**\n\t * Unregister a client and dispose all its subscriptions. Call from `handleDisconnect`.\n\t */\n\thandleDisconnect(client: unknown): void {\n\t\tconst subs = this.clients.get(client);\n\t\tif (!subs) return;\n\t\tfor (const entry of subs.values()) {\n\t\t\tentry.wm?.dispose();\n\t\t\tentry.unsub();\n\t\t}\n\t\tthis.clients.delete(client);\n\t}\n\n\t/**\n\t * Handle an incoming client message (subscribe/unsubscribe/ack command).\n\t *\n\t * @param client - The WebSocket client reference.\n\t * @param raw - Raw message data (string or parsed object).\n\t * @param send - Function to send a message back to the client.\n\t * Defaults to `client.send(JSON.stringify(msg))`.\n\t */\n\thandleMessage(client: unknown, raw: unknown, send?: (msg: ObserveWsMessage) => void): void {\n\t\tconst sender = send ?? defaultSend.bind(null, client);\n\t\tlet cmd: ObserveWsCommand;\n\t\ttry {\n\t\t\tcmd = typeof raw === \"string\" ? this.parse(raw) : (raw as ObserveWsCommand);\n\t\t} catch {\n\t\t\tsender({ type: \"err\", message: \"invalid command\" });\n\t\t\treturn;\n\t\t}\n\n\t\tif (cmd.type === \"subscribe\") {\n\t\t\tthis.subscribe(client, cmd.path, sender);\n\t\t} else if (cmd.type === \"unsubscribe\") {\n\t\t\tthis.unsubscribe(client, cmd.path, sender);\n\t\t} else if (cmd.type === \"ack\") {\n\t\t\tthis.ack(client, cmd.path, cmd.count ?? 1);\n\t\t} else {\n\t\t\tsender({ type: \"err\", message: `unknown command type: ${(cmd as { type: string }).type}` });\n\t\t}\n\t}\n\n\t/**\n\t * Number of active subscriptions for a client. Useful for tests.\n\t */\n\tsubscriptionCount(client: unknown): number {\n\t\treturn this.clients.get(client)?.size ?? 0;\n\t}\n\n\t/**\n\t * Dispose all clients and subscriptions.\n\t */\n\tdestroy(): void {\n\t\tfor (const [client] of this.clients) {\n\t\t\tthis.handleDisconnect(client);\n\t\t}\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// Internal\n\t// -----------------------------------------------------------------------\n\n\tprivate subscribe(client: unknown, path: string, send: (msg: ObserveWsMessage) => void): void {\n\t\tlet subs = this.clients.get(client);\n\t\tif (!subs) {\n\t\t\tsubs = new Map();\n\t\t\tthis.clients.set(client, subs);\n\t\t}\n\t\tif (subs.has(path)) {\n\t\t\tsend({ type: \"subscribed\", path });\n\t\t\treturn;\n\t\t}\n\n\t\tconst actor = this.extractActor(client);\n\t\tlet handle: GraphObserveOne;\n\t\ttry {\n\t\t\thandle = this.graph.observe(path, { actor }) as unknown as GraphObserveOne;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tsend({ type: \"err\", message });\n\t\t\treturn;\n\t\t}\n\n\t\tconst wm =\n\t\t\tthis.highWaterMark != null\n\t\t\t\t? createWatermarkController((msgs) => handle.up(msgs), {\n\t\t\t\t\t\thighWaterMark: this.highWaterMark,\n\t\t\t\t\t\tlowWaterMark: this.lowWaterMark ?? Math.floor(this.highWaterMark / 2),\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\tconst cleanup = () => {\n\t\t\twm?.dispose();\n\t\t\tunsub();\n\t\t\tsubs!.delete(path);\n\t\t};\n\n\t\tconst unsub = handle.subscribe((msgs: Messages) => {\n\t\t\tfor (const msg of msgs) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\twm?.onEnqueue();\n\t\t\t\t\ttrySend(send, { type: \"data\", path, value: msg[1] });\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tconst errMsg = msg[1] instanceof Error ? msg[1].message : String(msg[1]);\n\t\t\t\t\ttrySend(send, { type: \"error\", path, error: errMsg });\n\t\t\t\t\tcleanup();\n\t\t\t\t\treturn;\n\t\t\t\t} else if (t === COMPLETE || t === TEARDOWN) {\n\t\t\t\t\ttrySend(send, { type: \"complete\", path });\n\t\t\t\t\tcleanup();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// DIRTY, RESOLVED not exposed to WS clients\n\t\t\t}\n\t\t});\n\n\t\tsubs.set(path, { unsub, wm });\n\t\tsend({ type: \"subscribed\", path });\n\t}\n\n\tprivate unsubscribe(client: unknown, path: string, send: (msg: ObserveWsMessage) => void): void {\n\t\tconst subs = this.clients.get(client);\n\t\tconst entry = subs?.get(path);\n\t\tif (entry) {\n\t\t\tentry.wm?.dispose();\n\t\t\tentry.unsub();\n\t\t\tsubs!.delete(path);\n\t\t}\n\t\tsend({ type: \"unsubscribed\", path });\n\t}\n\n\tprivate ack(client: unknown, path: string, count: number): void {\n\t\tconst entry = this.clients.get(client)?.get(path);\n\t\tif (!entry?.wm) return;\n\t\tconst n = Math.min(Math.max(0, Math.floor(count)), 1024);\n\t\tfor (let i = 0; i < n; i++) entry.wm.onDequeue();\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultSerialize(value: unknown): string {\n\tif (value instanceof Error) return value.message;\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction sseFrame(event: string, data?: string): string {\n\tlet frame = `event: ${event}\\n`;\n\tif (data !== undefined) {\n\t\tfor (const line of data.split(\"\\n\")) {\n\t\t\tframe += `data: ${line}\\n`;\n\t\t}\n\t}\n\tframe += \"\\n\";\n\treturn frame;\n}\n\nfunction defaultParseCommand(data: string): ObserveWsCommand {\n\treturn JSON.parse(data) as ObserveWsCommand;\n}\n\nfunction defaultSend(client: unknown, msg: ObserveWsMessage): void {\n\ttry {\n\t\t(client as { send: (data: string) => void }).send(JSON.stringify(msg));\n\t} catch {\n\t\t/* client may have disconnected — swallow transport errors */\n\t}\n}\n\nfunction trySend(send: (msg: ObserveWsMessage) => void, msg: ObserveWsMessage): void {\n\ttry {\n\t\tsend(msg);\n\t} catch {\n\t\t/* transport error — client may have disconnected */\n\t}\n}\n","// ---------------------------------------------------------------------------\n// NestJS Actor bridge — maps NestJS ExecutionContext to GraphReFly Actor.\n// ---------------------------------------------------------------------------\n// Implements the NestJS `CanActivate` interface to extract an `Actor` from the\n// request (JWT payload, session, custom header, etc.) and attach it to the\n// request object for downstream graph operations.\n//\n// The decorator does NOT enforce access control — it merely bridges the NestJS\n// authentication context to GraphReFly's ABAC model. Actual access control\n// flows through node `policy()` guards reactively.\n// ---------------------------------------------------------------------------\n\nimport type { CanActivate, ExecutionContext } from \"@nestjs/common\";\nimport { type Actor, DEFAULT_ACTOR, normalizeActor } from \"../../core/actor.js\";\n\n/**\n * Property name under which the extracted {@link Actor} is stored on the\n * request object. Downstream code (controllers, gateways) reads\n * `req[ACTOR_KEY]` to pass actor context to graph operations.\n */\nexport const ACTOR_KEY = \"graphReflyActor\" as const;\n\n/**\n * Extracts a GraphReFly {@link Actor} from a NestJS {@link ExecutionContext}.\n *\n * Return `undefined` to fall back to {@link DEFAULT_ACTOR}.\n */\nexport type ActorExtractor = (context: ExecutionContext) => Actor | undefined;\n\n/**\n * Creates an {@link ActorExtractor} that reads a JWT payload from `req.user`\n * (the standard Passport.js location) and maps it to a GraphReFly {@link Actor}.\n *\n * @param mapping - Optional transform from the JWT payload to an Actor.\n * When omitted, the payload is used directly (must have `type` and `id`).\n *\n * @example\n * ```ts\n * // Default: req.user is already { type, id, ... }\n * GraphReflyGuard(fromJwtPayload())\n *\n * // Custom mapping from your JWT claims\n * GraphReflyGuard(fromJwtPayload((payload) => ({\n * type: payload.role === \"admin\" ? \"human\" : \"llm\",\n * id: payload.sub,\n * org: payload.org_id,\n * })))\n * ```\n */\nexport function fromJwtPayload(mapping?: (payload: unknown) => Actor): ActorExtractor {\n\treturn (context: ExecutionContext): Actor | undefined => {\n\t\tconst req = context.switchToHttp().getRequest();\n\t\tconst user = req?.user;\n\t\tif (user == null) return undefined;\n\t\tif (mapping) return mapping(user);\n\t\treturn user as Actor;\n\t};\n}\n\n/**\n * Creates an {@link ActorExtractor} that reads an Actor from a request header.\n *\n * The header value is parsed as JSON. Useful for service-to-service calls\n * where the caller embeds actor context in a custom header.\n *\n * @param headerName - HTTP header name (case-insensitive). Default: `\"x-graphrefly-actor\"`.\n *\n * @example\n * ```ts\n * GraphReflyGuard(fromHeader(\"x-actor\"))\n * ```\n */\nexport function fromHeader(headerName = \"x-graphrefly-actor\"): ActorExtractor {\n\treturn (context: ExecutionContext): Actor | undefined => {\n\t\tconst req = context.switchToHttp().getRequest();\n\t\tconst raw = req?.headers?.[headerName.toLowerCase()];\n\t\tif (typeof raw !== \"string\" || raw.length === 0) return undefined;\n\t\ttry {\n\t\t\treturn JSON.parse(raw) as Actor;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t};\n}\n\n/**\n * Reads the extracted {@link Actor} from a request object (set by {@link GraphReflyGuardImpl}).\n *\n * Returns {@link DEFAULT_ACTOR} if no actor was attached.\n *\n * @example\n * ```ts\n * @Get(\"status\")\n * getStatus(@Req() req: Request) {\n * const actor = getActor(req);\n * return this.graph.describe({ actor });\n * }\n * ```\n */\nexport function getActor(req: unknown): Actor {\n\tconst actor = (req as Record<string, unknown>)?.[ACTOR_KEY];\n\treturn actor != null ? normalizeActor(actor as Actor) : DEFAULT_ACTOR;\n}\n\n/**\n * NestJS guard that extracts a GraphReFly {@link Actor} from the execution\n * context and attaches it to the request as `req.graphReflyActor`.\n *\n * This guard always returns `true` (allows the request through). Access\n * control is handled by GraphReFly node guards (`policy()`), not by this\n * NestJS guard. The purpose is purely to **bridge** authentication context.\n *\n * @example\n * ```ts\n * // Global guard — every request gets an Actor\n * app.useGlobalGuards(new GraphReflyGuardImpl(fromJwtPayload()));\n *\n * // Controller-scoped\n * @UseGuards(GraphReflyGuard(fromJwtPayload()))\n * @Controller(\"api\")\n * export class ApiController { ... }\n * ```\n */\nexport class GraphReflyGuardImpl implements CanActivate {\n\tconstructor(private readonly extractor: ActorExtractor) {}\n\n\tcanActivate(context: ExecutionContext): boolean {\n\t\tconst actor = normalizeActor(this.extractor(context));\n\t\tconst req = context.switchToHttp().getRequest();\n\t\tif (req != null) {\n\t\t\t(req as Record<string, unknown>)[ACTOR_KEY] = actor;\n\t\t}\n\t\treturn true;\n\t}\n}\n\n/**\n * Factory that creates a {@link GraphReflyGuardImpl} instance. Use with\n * NestJS `@UseGuards()` or `app.useGlobalGuards()`.\n *\n * @param extractor - How to extract an Actor from the request context.\n * Defaults to {@link fromJwtPayload} (reads `req.user`).\n *\n * @example\n * ```ts\n * import { GraphReflyGuard, fromJwtPayload } from \"@graphrefly/graphrefly-ts/compat/nestjs\";\n *\n * @UseGuards(GraphReflyGuard())\n * @Controller(\"graph\")\n * export class GraphController { ... }\n * ```\n */\nexport function GraphReflyGuard(extractor?: ActorExtractor): GraphReflyGuardImpl {\n\treturn new GraphReflyGuardImpl(extractor ?? fromJwtPayload());\n}\n","// ---------------------------------------------------------------------------\n// GraphReflyModule — NestJS dynamic module for GraphReFly integration.\n// ---------------------------------------------------------------------------\n// Provides `forRoot()` and `forFeature()` following the standard NestJS\n// dynamic-module pattern. Lifecycle hooks wire graph creation on init and\n// `graph.destroy()` on teardown — TEARDOWN propagates through the graph\n// per GRAPHREFLY-SPEC §3.7.\n//\n// No decorator usage in this file — all DI is done via factory providers\n// so the library doesn't require `experimentalDecorators` in consumer's\n// tsconfig (only the consumer's NestJS app needs it).\n// ---------------------------------------------------------------------------\n\nimport {\n\ttype DynamicModule,\n\tModule,\n\ttype OnModuleDestroy,\n\ttype Provider,\n\tScope,\n} from \"@nestjs/common\";\nimport { ModuleRef } from \"@nestjs/core\";\nimport { Graph, type GraphPersistSnapshot } from \"../../graph/graph.js\";\nimport {\n\ttype CqrsGraph,\n\ttype CqrsOptions,\n\tcqrs,\n\ttype EventStoreAdapter,\n} from \"../../patterns/cqrs.js\";\nimport { GraphReflyEventExplorer } from \"./explorer.js\";\nimport {\n\tGRAPHREFLY_REQUEST_GRAPH,\n\tGRAPHREFLY_ROOT_GRAPH,\n\tgetGraphToken,\n\tgetNodeToken,\n} from \"./tokens.js\";\n\n// ---------------------------------------------------------------------------\n// Option types\n// ---------------------------------------------------------------------------\n\nexport interface GraphReflyRootOptions {\n\t/** Root graph name (default: `\"root\"`). */\n\tname?: string;\n\t/** Snapshot to hydrate via `graph.restore()` after build. */\n\tsnapshot?: GraphPersistSnapshot;\n\t/** Build callback — registers nodes/mounts on the graph. */\n\tbuild?: (graph: Graph) => void;\n\t/** Qualified node paths to expose as injectable providers. */\n\tnodes?: readonly string[];\n\t/** Enable a request-scoped graph (injectable via `@InjectGraph(\"request\")`). */\n\trequestScope?: boolean;\n}\n\nexport interface GraphReflyCqrsOptions {\n\t/** Feature name — becomes the mount name in the root graph. */\n\tname: string;\n\t/** CQRS graph options (forwarded to `cqrs()` factory). */\n\tcqrs?: CqrsOptions;\n\t/** Build callback — registers commands, events, projections, sagas on the CqrsGraph. */\n\tbuild?: (graph: CqrsGraph) => void;\n\t/** Event store adapter for persistence (wired via `useEventStore()`). */\n\teventStore?: EventStoreAdapter;\n\t/**\n\t * Node paths (local to this feature) to expose as injectable providers.\n\t * Tokens are auto-qualified as `featureName::path`.\n\t */\n\tnodes?: readonly string[];\n}\n\nexport interface GraphReflyFeatureOptions {\n\t/** Feature name — becomes the mount name in the root graph. */\n\tname: string;\n\t/** Build callback — registers nodes/mounts on the feature graph. */\n\tbuild?: (graph: Graph) => void;\n\t/** Snapshot to hydrate after build. */\n\tsnapshot?: GraphPersistSnapshot;\n\t/**\n\t * Node paths (local to this feature) to expose as injectable providers.\n\t * Tokens are auto-qualified as `featureName::path` to avoid collisions.\n\t */\n\tnodes?: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// Lifecycle classes (no decorators — DI is handled via factory providers)\n// ---------------------------------------------------------------------------\n\nclass GraphReflyRootLifecycle implements OnModuleDestroy {\n\tconstructor(readonly graph: Graph) {}\n\n\tonModuleDestroy(): void {\n\t\tthis.graph.destroy();\n\t}\n}\n\nclass GraphReflyRequestLifecycle implements OnModuleDestroy {\n\treadonly graph = new Graph(\"request\");\n\n\tonModuleDestroy(): void {\n\t\tthis.graph.destroy();\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Module\n// ---------------------------------------------------------------------------\n\n// NestJS dynamic modules convention: static `forRoot` / `forFeature` factories on a `@Module` class.\n@Module({})\n// biome-ignore lint/complexity/noStaticOnlyClass: NestJS `DynamicModule` pattern (`@Module` + static factories)\nexport class GraphReflyModule {\n\t/**\n\t * Register the root `Graph` singleton in the NestJS DI container.\n\t *\n\t * The root graph is `@Global()` — injectable everywhere without importing\n\t * the module again. Use `@InjectGraph()` to inject it.\n\t *\n\t * Lifecycle:\n\t * - **init:** Graph created in factory. If `build` is provided, it runs\n\t * first (registers nodes/mounts). If `snapshot` is provided, values\n\t * are restored via `graph.restore()`.\n\t * - **destroy:** Calls `graph.destroy()` — sends `[[TEARDOWN]]` to all\n\t * nodes, including mounted feature subgraphs (cascading teardown).\n\t */\n\tstatic forRoot(opts?: GraphReflyRootOptions): DynamicModule {\n\t\tconst options = opts ?? {};\n\t\tconst graphName = options.name ?? \"root\";\n\n\t\tconst providers: Provider[] = [\n\t\t\t{\n\t\t\t\tprovide: GRAPHREFLY_ROOT_GRAPH,\n\t\t\t\tuseFactory: () => {\n\t\t\t\t\tconst g = new Graph(graphName);\n\t\t\t\t\tif (options.build) options.build(g);\n\t\t\t\t\tif (options.snapshot) g.restore(options.snapshot);\n\t\t\t\t\treturn g;\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tprovide: Symbol.for(\"graphrefly:root-lifecycle\"),\n\t\t\t\tuseFactory: (graph: Graph) => new GraphReflyRootLifecycle(graph),\n\t\t\t\tinject: [GRAPHREFLY_ROOT_GRAPH],\n\t\t\t},\n\t\t\t{\n\t\t\t\tprovide: GraphReflyEventExplorer,\n\t\t\t\tuseFactory: (graph: Graph, moduleRef: InstanceType<typeof ModuleRef>) =>\n\t\t\t\t\tnew GraphReflyEventExplorer(graph, moduleRef),\n\t\t\t\tinject: [GRAPHREFLY_ROOT_GRAPH, ModuleRef],\n\t\t\t},\n\t\t];\n\n\t\t// Node factory providers — each declared path gets a factory that\n\t\t// resolves the node from the root graph at injection time.\n\t\tif (options.nodes) {\n\t\t\tfor (const path of options.nodes) {\n\t\t\t\tproviders.push({\n\t\t\t\t\tprovide: getNodeToken(path),\n\t\t\t\t\tuseFactory: (graph: Graph) => graph.resolve(path),\n\t\t\t\t\tinject: [GRAPHREFLY_ROOT_GRAPH],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Request-scoped graph provider (opt-in).\n\t\tif (options.requestScope) {\n\t\t\tproviders.push(\n\t\t\t\t{\n\t\t\t\t\tprovide: Symbol.for(\"graphrefly:request-lifecycle\"),\n\t\t\t\t\tuseFactory: () => new GraphReflyRequestLifecycle(),\n\t\t\t\t\tscope: Scope.REQUEST,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tprovide: GRAPHREFLY_REQUEST_GRAPH,\n\t\t\t\t\tuseFactory: (lifecycle: GraphReflyRequestLifecycle) => lifecycle.graph,\n\t\t\t\t\tinject: [Symbol.for(\"graphrefly:request-lifecycle\")],\n\t\t\t\t\tscope: Scope.REQUEST,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tmodule: GraphReflyModule,\n\t\t\tglobal: true,\n\t\t\tproviders,\n\t\t\texports: [\n\t\t\t\tGRAPHREFLY_ROOT_GRAPH,\n\t\t\t\t...(options.nodes ?? []).map(getNodeToken),\n\t\t\t\t...(options.requestScope ? [GRAPHREFLY_REQUEST_GRAPH] : []),\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Register a feature subgraph that auto-mounts into the root graph.\n\t *\n\t * The feature graph is created in the factory, built/restored, then\n\t * mounted into root via `root.mount(name, featureGraph)`. On app\n\t * shutdown, root's `graph.destroy()` cascades TEARDOWN through all\n\t * mounted subgraphs (no explicit remove needed).\n\t *\n\t * Node tokens are auto-qualified as `featureName::path` to prevent\n\t * collisions between features declaring nodes with the same local name.\n\t *\n\t * Injectable via `@InjectGraph(name)`.\n\t */\n\tstatic forFeature(opts: GraphReflyFeatureOptions): DynamicModule {\n\t\tconst providers: Provider[] = [\n\t\t\t{\n\t\t\t\tprovide: getGraphToken(opts.name),\n\t\t\t\tuseFactory: (rootGraph: Graph) => {\n\t\t\t\t\tconst g = new Graph(opts.name);\n\t\t\t\t\tif (opts.build) opts.build(g);\n\t\t\t\t\tif (opts.snapshot) g.restore(opts.snapshot);\n\t\t\t\t\trootGraph.mount(opts.name, g);\n\t\t\t\t\treturn g;\n\t\t\t\t},\n\t\t\t\tinject: [GRAPHREFLY_ROOT_GRAPH],\n\t\t\t},\n\t\t];\n\n\t\t// Node factory providers for feature-scoped nodes.\n\t\t// Tokens are qualified as `featureName::path` to avoid cross-feature collisions.\n\t\tif (opts.nodes) {\n\t\t\tfor (const path of opts.nodes) {\n\t\t\t\tproviders.push({\n\t\t\t\t\tprovide: getNodeToken(`${opts.name}::${path}`),\n\t\t\t\t\tuseFactory: (graph: Graph) => graph.resolve(path),\n\t\t\t\t\tinject: [getGraphToken(opts.name)],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmodule: GraphReflyModule,\n\t\t\tproviders,\n\t\t\texports: [\n\t\t\t\tgetGraphToken(opts.name),\n\t\t\t\t...(opts.nodes ?? []).map((p) => getNodeToken(`${opts.name}::${p}`)),\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Register a CQRS subgraph that auto-mounts into the root graph.\n\t *\n\t * Creates a `CqrsGraph` via the `cqrs()` factory (roadmap §4.5), mounts it\n\t * into the root graph, and exposes it for DI via `@InjectGraph(name)`.\n\t *\n\t * CQRS decorators (`@CommandHandler`, `@EventHandler`, `@QueryHandler`,\n\t * `@SagaHandler`) are discovered by the explorer and wired to this graph\n\t * on module init.\n\t *\n\t * @example\n\t * ```ts\n\t * GraphReflyModule.forCqrs({\n\t * name: \"orders\",\n\t * build: (g) => {\n\t * g.event(\"orderPlaced\");\n\t * g.projection(\"orderCount\", [\"orderPlaced\"], (_s, evts) => evts.length, 0);\n\t * },\n\t * })\n\t * ```\n\t */\n\tstatic forCqrs(opts: GraphReflyCqrsOptions): DynamicModule {\n\t\tconst providers: Provider[] = [\n\t\t\t{\n\t\t\t\tprovide: getGraphToken(opts.name),\n\t\t\t\tuseFactory: (rootGraph: Graph) => {\n\t\t\t\t\tconst g = cqrs(opts.name, opts.cqrs);\n\t\t\t\t\t// `useEventStore` is CqrsGraph API, not a React hook (Biome false positive).\n\t\t\t\t\t// biome-ignore lint/correctness/useHookAtTopLevel: not React; Nest provider factory\n\t\t\t\t\tif (opts.eventStore) g.useEventStore(opts.eventStore);\n\t\t\t\t\tif (opts.build) opts.build(g);\n\t\t\t\t\trootGraph.mount(opts.name, g);\n\t\t\t\t\treturn g;\n\t\t\t\t},\n\t\t\t\tinject: [GRAPHREFLY_ROOT_GRAPH],\n\t\t\t},\n\t\t];\n\n\t\tif (opts.nodes) {\n\t\t\tfor (const path of opts.nodes) {\n\t\t\t\tproviders.push({\n\t\t\t\t\tprovide: getNodeToken(`${opts.name}::${path}`),\n\t\t\t\t\tuseFactory: (graph: Graph) => graph.resolve(path),\n\t\t\t\t\tinject: [getGraphToken(opts.name)],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmodule: GraphReflyModule,\n\t\t\tproviders,\n\t\t\texports: [\n\t\t\t\tgetGraphToken(opts.name),\n\t\t\t\t...(opts.nodes ?? []).map((p) => getNodeToken(`${opts.name}::${p}`)),\n\t\t\t],\n\t\t};\n\t}\n}\n","import { DynamicNodeImpl } from \"./dynamic-node.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { type Node, NodeImpl } from \"./node.js\";\n\n/** JSON-shaped slice of a node for Phase 1 `Graph.describe()` (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type DescribeNodeOutput = {\n\ttype: \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\tstatus: Node[\"status\"];\n\tdeps: string[];\n\tmeta: Record<string, unknown>;\n\tname?: string;\n\tvalue?: unknown;\n\t/** Node versioning info (GRAPHREFLY-SPEC §7). Present only when versioning is enabled. */\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\n};\n\nfunction inferDescribeType(n: NodeImpl): DescribeNodeOutput[\"type\"] {\n\tif (n._describeKind != null) return n._describeKind;\n\tif (!n._hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\tif (n._fn == null) return \"derived\";\n\tif (n._manualEmitUsed) return \"operator\";\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON (GRAPHREFLY-SPEC §2.3, §3.6).\n *\n * @remarks\n * Values come from {@link Node.get}, which returns the **last settled** cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status` when\n * freshness matters. Avoid calling mid-batch for the same reason.\n *\n * Meta nodes are **not** terminated when their parent receives COMPLETE or\n * ERROR — they remain writable so callers can record post-mortem metadata\n * (e.g. `meta.error`). They *are* torn down when the parent receives TEARDOWN.\n *\n * @param node - The node whose meta fields to snapshot.\n * @returns Plain object of `{ key: value }` pairs (empty if no meta defined).\n * Keys whose companion node's {@link Node.get} throws are omitted.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = core.node({ initial: 0, meta: { tag: \"a\" } });\n * core.metaSnapshot(n); // { tag: \"a\" }\n * ```\n */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.get();\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta` snapshot).\n * Parity with graphrefly-py `describe_node`.\n *\n * `type` is inferred from factory configuration, optional `describeKind` in node options,\n * and the last `manualEmitUsed` hint (operator vs derived). {@link effect} sets\n * `describeKind: \"effect\"`. Nodes not created by {@link node} fall back to `type: \"state\"` and empty `deps`.\n *\n * @param node - Any `Node` to introspect.\n * @returns `DescribeNodeOutput` suitable for merging into graph describe maps.\n *\n * @example\n * ```ts\n * import { describeNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * describeNode(state(0));\n * ```\n */\nexport function describeNode(node: Node): DescribeNodeOutput {\n\tconst meta: Record<string, unknown> = { ...metaSnapshot(node) };\n\n\t// Guard-derived access hint (NodeImpl or DynamicNodeImpl)\n\tconst guard =\n\t\t(node instanceof NodeImpl && node._guard) ||\n\t\t(node instanceof DynamicNodeImpl && node._guard) ||\n\t\tundefined;\n\tif (guard != null && meta.access === undefined) {\n\t\tmeta.access = accessHintForGuard(guard);\n\t}\n\n\tlet type: DescribeNodeOutput[\"type\"] = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.name ?? \"\");\n\t} else if (node instanceof DynamicNodeImpl) {\n\t\ttype = node._describeKind ?? \"derived\";\n\t\tdeps = [];\n\t}\n\n\tconst out: DescribeNodeOutput = {\n\t\ttype,\n\t\tstatus: node.status,\n\t\tdeps,\n\t\tmeta,\n\t};\n\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\ttry {\n\t\tout.value = node.get();\n\t} catch {\n\t\t/* omit value */\n\t}\n\n\t// Versioning (GRAPHREFLY-SPEC §7)\n\tif (node.v != null) {\n\t\tconst vInfo: DescribeNodeOutput[\"v\"] = { id: node.v.id, version: node.v.version };\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo!.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo!.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\treturn out;\n}\n","import type { Actor } from \"../core/actor.js\";\nimport { isBatching } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { GuardDenied } from \"../core/guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport { type DescribeNodeOutput, describeNode } from \"../core/meta.js\";\nimport {\n\ttype Node,\n\tNodeImpl,\n\ttype NodeInspectorHookEvent,\n\ttype NodeSink,\n\ttype NodeTransportOptions,\n} from \"../core/node.js\";\nimport { state as stateNode } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\n\n/** The separator used for qualified paths in {@link Graph.resolve} et al. */\nconst PATH_SEP = \"::\";\n\n/**\n * Reserved segment for meta companion paths: `nodeName::__meta__::metaKey` (GRAPHREFLY-SPEC §3.6).\n * Forbidden as a local node or mount name.\n */\nexport const GRAPH_META_SEGMENT = \"__meta__\";\n\n/** Options for {@link Graph} (reserved for future hooks). */\nexport type GraphOptions = Record<string, unknown>;\n\n/** Filter for {@link Graph.describe} — object-style partial match or predicate. */\nexport type DescribeFilter =\n\t| Partial<Pick<DescribeNodeOutput, \"type\" | \"status\">>\n\t| {\n\t\t\ttype?: DescribeNodeOutput[\"type\"];\n\t\t\tstatus?: DescribeNodeOutput[\"status\"];\n\t\t\t/** Keep nodes whose `deps` includes this qualified path. */\n\t\t\tdepsIncludes?: string;\n\t\t\t/** Snake-case alias for `depsIncludes` (Python parity). */\n\t\t\tdeps_includes?: string;\n\t\t\t/** Keep nodes whose `meta` contains this key. */\n\t\t\tmetaHas?: string;\n\t\t\t/** Snake-case alias for `metaHas` (Python parity). */\n\t\t\tmeta_has?: string;\n\t }\n\t| ((node: DescribeNodeOutput) => boolean)\n\t| ((nodePath: string, node: DescribeNodeOutput) => boolean);\n\n/** Options for {@link Graph.signal} and {@link Graph.set} (actor context, internal lifecycle). */\nexport type GraphActorOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips node guards (graph lifecycle TEARDOWN, unmount teardown, etc.).\n\t */\n\tinternal?: boolean;\n};\n\n/** JSON snapshot from {@link Graph.describe} (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type GraphDescribeOutput = {\n\tname: string;\n\tnodes: Record<string, DescribeNodeOutput>;\n\tedges: ReadonlyArray<{ from: string; to: string }>;\n\tsubgraphs: string[];\n};\n\n/**\n * Persisted graph snapshot: {@link GraphDescribeOutput} plus optional format version\n * ({@link Graph.snapshot}, {@link Graph.restore}, {@link Graph.fromSnapshot}, {@link Graph.toJSON},\n * {@link Graph.toJSONString} — §3.8).\n */\nexport type GraphPersistSnapshot = GraphDescribeOutput & {\n\tversion?: number;\n};\n\nexport type GraphFactoryContext = {\n\tpath: string;\n\ttype: DescribeNodeOutput[\"type\"];\n\tvalue: unknown;\n\tmeta: Record<string, unknown>;\n\tdeps: readonly string[];\n\tresolvedDeps: readonly Node[];\n};\n\nexport type GraphNodeFactory = (name: string, context: GraphFactoryContext) => Node;\n\nexport type AutoCheckpointAdapter = {\n\tsave(data: unknown): void;\n};\n\nexport type GraphCheckpointRecord =\n\t| { mode: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { mode: \"diff\"; diff: GraphDiffResult; snapshot: GraphPersistSnapshot; seq: number };\n\nexport type GraphAutoCheckpointOptions = {\n\tdebounceMs?: number;\n\tcompactEvery?: number;\n\tfilter?: (name: string, described: DescribeNodeOutput) => boolean;\n\tonError?: (error: unknown) => void;\n};\n\nexport type GraphAutoCheckpointHandle = {\n\tdispose(): void;\n};\n\n/** Direction options for diagram export helpers. */\nexport type GraphDiagramDirection = \"TD\" | \"LR\" | \"BT\" | \"RL\";\n\n/** Options for {@link Graph.toMermaid} / {@link Graph.toD2}. */\nexport type GraphDiagramOptions = {\n\t/**\n\t * Diagram flow direction.\n\t * - `TD`: top-down\n\t * - `LR`: left-right (default)\n\t * - `BT`: bottom-top\n\t * - `RL`: right-left\n\t */\n\tdirection?: GraphDiagramDirection;\n};\n\n/** Snapshot format version (§3.8). */\nconst SNAPSHOT_VERSION = 1;\n\n/**\n * Validate the snapshot envelope: version, required keys, types. Aligned with\n * Python `_parse_snapshot_envelope`. Throws on invalid data.\n */\nfunction parseSnapshotEnvelope(data: GraphPersistSnapshot): void {\n\tif (data.version !== SNAPSHOT_VERSION) {\n\t\tthrow new Error(\n\t\t\t`unsupported snapshot version ${String(data.version)} (expected ${SNAPSHOT_VERSION})`,\n\t\t);\n\t}\n\tfor (const key of [\"name\", \"nodes\", \"edges\", \"subgraphs\"] as const) {\n\t\tif (!(key in data)) {\n\t\t\tthrow new Error(`snapshot missing required key \"${key}\"`);\n\t\t}\n\t}\n\tif (typeof data.name !== \"string\") {\n\t\tthrow new TypeError(`snapshot 'name' must be a string`);\n\t}\n\tif (typeof data.nodes !== \"object\" || data.nodes === null || Array.isArray(data.nodes)) {\n\t\tthrow new TypeError(`snapshot 'nodes' must be an object`);\n\t}\n\tif (!Array.isArray(data.edges)) {\n\t\tthrow new TypeError(`snapshot 'edges' must be an array`);\n\t}\n\tif (!Array.isArray(data.subgraphs)) {\n\t\tthrow new TypeError(`snapshot 'subgraphs' must be an array`);\n\t}\n}\n\n/** Recursively sort object keys for deterministic JSON (git-diffable). */\nfunction sortJsonValue(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sortJsonValue);\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\tconst out: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tout[k] = sortJsonValue(obj[k]);\n\t}\n\treturn out;\n}\n\nfunction stableJsonStringify(value: unknown): string {\n\treturn `${JSON.stringify(sortJsonValue(value))}\\n`;\n}\n\nfunction escapeMermaidLabel(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction escapeD2Label(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction d2DirectionFromGraphDirection(direction: GraphDiagramDirection): string {\n\tif (direction === \"TD\") return \"down\";\n\tif (direction === \"BT\") return \"up\";\n\tif (direction === \"RL\") return \"left\";\n\treturn \"right\";\n}\n\n/** Collect deduplicated (from, to) arrows from deps + edges. */\nfunction collectDiagramArrows(described: GraphDescribeOutput): [string, string][] {\n\tconst seen = new Set<string>();\n\tconst arrows: [string, string][] = [];\n\tfunction add(from: string, to: string): void {\n\t\tconst key = `${from}\\0${to}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tarrows.push([from, to]);\n\t}\n\tfor (const [path, info] of Object.entries(described.nodes)) {\n\t\tconst deps: string[] | undefined = (info as Record<string, unknown>).deps as\n\t\t\t| string[]\n\t\t\t| undefined;\n\t\tif (deps) {\n\t\t\tfor (const dep of deps) add(dep, path);\n\t\t}\n\t}\n\tfor (const edge of described.edges) add(edge.from, edge.to);\n\treturn arrows;\n}\n\nfunction normalizeDiagramDirection(direction: unknown): GraphDiagramDirection {\n\tif (direction === undefined) return \"LR\";\n\tif (direction === \"TD\" || direction === \"LR\" || direction === \"BT\" || direction === \"RL\") {\n\t\treturn direction;\n\t}\n\tthrow new Error(\n\t\t`invalid diagram direction ${String(direction)}; expected one of: TD, LR, BT, RL`,\n\t);\n}\n\nfunction escapeRegexLiteral(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet re = \"^\";\n\tfor (let i = 0; i < pattern.length; i += 1) {\n\t\tconst ch = pattern[i]!;\n\t\tif (ch === \"*\") {\n\t\t\tre += \".*\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"?\") {\n\t\t\tre += \".\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tconst end = pattern.indexOf(\"]\", i + 1);\n\t\t\tif (end <= i + 1) {\n\t\t\t\tre += \"\\\\[\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet cls = pattern.slice(i + 1, end);\n\t\t\tif (cls.startsWith(\"!\")) cls = `^${cls.slice(1)}`;\n\t\t\tcls = cls.replace(/\\\\/g, \"\\\\\\\\\");\n\t\t\tre += `[${cls}]`;\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tre += escapeRegexLiteral(ch);\n\t}\n\tre += \"$\";\n\treturn new RegExp(re);\n}\n\n/** Fixed-capacity ring buffer — O(1) push and eviction. */\nclass RingBuffer<T> {\n\tprivate buf: (T | undefined)[];\n\tprivate head = 0;\n\tprivate _size = 0;\n\tconstructor(private capacity: number) {\n\t\tthis.buf = new Array(capacity);\n\t}\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\tpush(item: T): void {\n\t\tconst idx = (this.head + this._size) % this.capacity;\n\t\tthis.buf[idx] = item;\n\t\tif (this._size < this.capacity) this._size++;\n\t\telse this.head = (this.head + 1) % this.capacity;\n\t}\n\ttoArray(): T[] {\n\t\tconst result: T[] = [];\n\t\tfor (let i = 0; i < this._size; i++) result.push(this.buf[(this.head + i) % this.capacity]!);\n\t\treturn result;\n\t}\n}\n\nconst SPY_ANSI_THEME: Required<GraphSpyTheme> = {\n\tdata: \"\\u001b[32m\",\n\tdirty: \"\\u001b[33m\",\n\tresolved: \"\\u001b[36m\",\n\tcomplete: \"\\u001b[34m\",\n\terror: \"\\u001b[31m\",\n\tderived: \"\\u001b[35m\",\n\tpath: \"\\u001b[90m\",\n\treset: \"\\u001b[0m\",\n};\n\nconst SPY_NO_COLOR_THEME: Required<GraphSpyTheme> = {\n\tdata: \"\",\n\tdirty: \"\",\n\tresolved: \"\",\n\tcomplete: \"\",\n\terror: \"\",\n\tderived: \"\",\n\tpath: \"\",\n\treset: \"\",\n};\n\nfunction describeData(value: unknown): string {\n\tif (typeof value === \"string\") return JSON.stringify(value);\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || value == null)\n\t\treturn String(value);\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction resolveSpyTheme(theme: GraphSpyOptions[\"theme\"]): Required<GraphSpyTheme> {\n\tif (theme === \"none\") return SPY_NO_COLOR_THEME;\n\tif (theme === \"ansi\" || theme == null) return SPY_ANSI_THEME;\n\treturn {\n\t\tdata: theme.data ?? \"\",\n\t\tdirty: theme.dirty ?? \"\",\n\t\tresolved: theme.resolved ?? \"\",\n\t\tcomplete: theme.complete ?? \"\",\n\t\terror: theme.error ?? \"\",\n\t\tderived: theme.derived ?? \"\",\n\t\tpath: theme.path ?? \"\",\n\t\treset: theme.reset ?? \"\",\n\t};\n}\n\n/** {@link Graph.observe} on a single node or meta path — sink receives plain message batches. */\nexport type GraphObserveOne = {\n\tsubscribe(sink: NodeSink): () => void;\n\t/** Send messages upstream toward the observed node's sources (e.g. PAUSE/RESUME). */\n\tup(messages: Messages): void;\n};\n\n/**\n * {@link Graph.observe} on the whole graph — sink receives each batch with the qualified source path.\n * Subscription order follows code-point sort on paths (mounts-first walk, then sorted locals/meta).\n */\nexport type GraphObserveAll = {\n\tsubscribe(sink: (nodePath: string, messages: Messages) => void): () => void;\n\t/** Send messages upstream toward a specific observed node's sources (e.g. PAUSE/RESUME). */\n\tup(path: string, messages: Messages): void;\n};\n\n/** Options for structured observation modes on {@link Graph.observe}. */\nexport type ObserveOptions = {\n\tactor?: Actor;\n\t/** Return an {@link ObserveResult} accumulator instead of a raw stream. */\n\tstructured?: boolean;\n\t/** Include causal trace info (which dep triggered each recomputation). */\n\tcausal?: boolean;\n\t/** Include timestamps and batch context on each event. */\n\ttimeline?: boolean;\n\t/** Include per-evaluation dep snapshots for compute/derived nodes. */\n\tderived?: boolean;\n};\n\n/** Accumulated observation result (structured mode). */\nexport type ObserveResult<T = unknown> = {\n\t/** Latest DATA value by observed path. */\n\treadonly values: Record<string, T>;\n\t/** Number of DIRTY messages received. */\n\treadonly dirtyCount: number;\n\t/** Number of RESOLVED messages received. */\n\treadonly resolvedCount: number;\n\t/** All events in order. */\n\treadonly events: ObserveEvent[];\n\t/** True if COMPLETE received without prior ERROR. */\n\treadonly completedCleanly: boolean;\n\t/** True if ERROR received. */\n\treadonly errored: boolean;\n\t/** Stop observing. */\n\tdispose(): void;\n};\n\n/** A single event in the structured observation log. */\nexport type ObserveEvent = {\n\ttype: \"data\" | \"dirty\" | \"resolved\" | \"complete\" | \"error\" | \"derived\";\n\tpath?: string;\n\tdata?: unknown;\n\ttimestamp_ns?: number;\n\tin_batch?: boolean;\n\ttrigger_dep_index?: number;\n\ttrigger_dep_name?: string;\n\t/**\n\t * V0 version of the triggering dep at observation time (§6.0b).\n\t * This is the dep's post-emission version (after its own `advanceVersion`),\n\t * not the pre-emission version that caused this node's recomputation.\n\t */\n\ttrigger_version?: { id: string; version: number };\n\tdep_values?: unknown[];\n};\n\n/** Built-in color presets for {@link Graph.spy}. */\nexport type GraphSpyThemeName = \"none\" | \"ansi\";\n\n/** ANSI/style overrides for {@link Graph.spy} event rendering. */\nexport type GraphSpyTheme = Partial<Record<ObserveEvent[\"type\"] | \"path\" | \"reset\", string>>;\n\n/** Options for {@link Graph.spy}. */\nexport type GraphSpyOptions = ObserveOptions & {\n\t/** Observe one path; omit for graph-wide mode. */\n\tpath?: string;\n\t/** Keep only these event types in spy output. */\n\tincludeTypes?: ObserveEvent[\"type\"][];\n\t/** Exclude these event types from spy output. */\n\texcludeTypes?: ObserveEvent[\"type\"][];\n\t/** Built-in color preset (`ansi` default) or explicit color tokens. */\n\ttheme?: GraphSpyThemeName | GraphSpyTheme;\n\t/** One-line `pretty` output (default) or JSON-per-event. */\n\tformat?: \"pretty\" | \"json\";\n\t/** Optional sink for rendered lines (`console.log` by default). */\n\tlogger?: (line: string, event: ObserveEvent) => void;\n};\n\n/** Handle returned by {@link Graph.spy}. */\nexport type GraphSpyHandle = {\n\treadonly result: ObserveResult;\n\tdispose(): void;\n};\n\n/** Options for {@link Graph.dumpGraph}. */\nexport type GraphDumpOptions = {\n\tactor?: Actor;\n\tfilter?: DescribeFilter;\n\tformat?: \"pretty\" | \"json\";\n\tindent?: number;\n\tincludeEdges?: boolean;\n\tincludeSubgraphs?: boolean;\n\tlogger?: (text: string) => void;\n};\n\nfunction assertLocalName(name: string, graphName: string, label: string): void {\n\tif (name === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": ${label} name must be non-empty`);\n\t}\n}\n\nfunction assertNoPathSep(name: string, graphName: string, label: string): void {\n\tif (name.includes(PATH_SEP)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} \"${name}\" must not contain '${PATH_SEP}' (path separator)`,\n\t\t);\n\t}\n}\n\nfunction assertNotReservedMetaSegment(name: string, graphName: string, label: string): void {\n\tif (name === GRAPH_META_SEGMENT) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} name \"${GRAPH_META_SEGMENT}\" is reserved for meta companion paths`,\n\t\t);\n\t}\n}\n\n/** `connect` / `disconnect` endpoints must be registered graph nodes, not meta paths (graphrefly-py parity). */\nfunction assertConnectPathNotMeta(path: string, graphName: string): void {\n\tif (path.split(PATH_SEP).includes(GRAPH_META_SEGMENT)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": connect/disconnect endpoints must be registered graph nodes, not meta paths (got \"${path}\")`,\n\t\t);\n\t}\n}\n\nfunction splitPath(path: string, graphName: string): string[] {\n\tif (path === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": resolve path must be non-empty`);\n\t}\n\tconst segments = path.split(PATH_SEP);\n\tfor (const s of segments) {\n\t\tif (s === \"\") {\n\t\t\tthrow new Error(`Graph \"${graphName}\": resolve path has empty segment`);\n\t\t}\n\t}\n\treturn segments;\n}\n\n/** Canonical string key for an edge pair (deterministic, splittable). */\nfunction edgeKey(from: string, to: string): string {\n\treturn `${from}\\t${to}`;\n}\n\nfunction parseEdgeKey(key: string): [string, string] {\n\tconst i = key.indexOf(\"\\t\");\n\treturn [key.slice(0, i), key.slice(i + 1)];\n}\n\n/**\n * Lifecycle-destructive message types that meta companion nodes ignore\n * during graph-wide signal propagation (spec §2.3 Companion lifecycle).\n * TEARDOWN: parent already cascades explicitly.\n * INVALIDATE/COMPLETE/ERROR: meta stores outlive these lifecycle events.\n * To target a meta node directly, call `meta.down(...)` on it.\n */\nconst META_FILTERED_TYPES = new Set([TEARDOWN, INVALIDATE, COMPLETE, ERROR]);\n\n/** Strip lifecycle-destructive messages; returns empty array when nothing remains. */\nfunction filterMetaMessages(messages: Messages): Messages {\n\tconst kept = messages.filter((m) => !META_FILTERED_TYPES.has(m[0]));\n\treturn kept as unknown as Messages;\n}\n\n/** TEARDOWN every node in a mounted graph tree (depth-first into mounts). */\nfunction teardownMountedGraph(root: Graph): void {\n\tfor (const child of root._mounts.values()) {\n\t\tteardownMountedGraph(child);\n\t}\n\tfor (const n of root._nodes.values()) {\n\t\tn.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n}\n\n/**\n * Named container for nodes and explicit edges (GRAPHREFLY-SPEC §3.1–§3.7).\n *\n * Qualified paths use `::` as the segment separator (for example `parent::child::node`).\n *\n * Edges are pure wires: `connect` only validates wiring — the target must already list the source in\n * its dependency array; no transforms run on the edge.\n *\n * @example\n * ```ts\n * import { Graph, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * g.add(\"counter\", state(0));\n * ```\n *\n * @category graph\n */\nexport class Graph {\n\tprivate static readonly _factories: Array<{\n\t\tpattern: string;\n\t\tre: RegExp;\n\t\tfactory: GraphNodeFactory;\n\t}> = [];\n\n\treadonly name: string;\n\treadonly opts: Readonly<GraphOptions>;\n\t/** @internal — exposed for {@link teardownMountedGraph} and cross-graph helpers. */\n\treadonly _nodes = new Map<string, Node>();\n\tprivate readonly _edges = new Set<string>();\n\t/** @internal — exposed for {@link teardownMountedGraph}. */\n\treadonly _mounts = new Map<string, Graph>();\n\tprivate readonly _autoCheckpointDisposers = new Set<() => void>();\n\tprivate _defaultVersioningLevel: VersioningLevel | undefined;\n\n\tstatic registerFactory(pattern: string, factory: GraphNodeFactory): void {\n\t\tif (!pattern) {\n\t\t\tthrow new Error(\"Graph.registerFactory requires a non-empty pattern\");\n\t\t}\n\t\tGraph.unregisterFactory(pattern);\n\t\tGraph._factories.push({ pattern, re: globToRegex(pattern), factory });\n\t}\n\n\tstatic unregisterFactory(pattern: string): void {\n\t\tconst i = Graph._factories.findIndex((entry) => entry.pattern === pattern);\n\t\tif (i >= 0) Graph._factories.splice(i, 1);\n\t}\n\n\t/**\n\t * @param name - Non-empty graph id (must not contain `::`).\n\t * @param opts - Reserved for future hooks; currently unused.\n\t */\n\tconstructor(name: string, opts?: GraphOptions) {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(\"Graph name must be non-empty\");\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\tthrow new Error(`Graph name must not contain '${PATH_SEP}' (got \"${name}\")`);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.opts = opts ?? {};\n\t}\n\n\tprivate static _factoryForPath(path: string): GraphNodeFactory | undefined {\n\t\tfor (let i = Graph._factories.length - 1; i >= 0; i -= 1) {\n\t\t\tconst entry = Graph._factories[i]!;\n\t\t\tif (entry.re.test(path)) return entry.factory;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate static _ownerForPath(root: Graph, path: string): [Graph, string] {\n\t\tconst segments = path.split(PATH_SEP);\n\t\tconst local = segments.pop();\n\t\tif (local == null || local.length === 0) {\n\t\t\tthrow new Error(`invalid snapshot path \"${path}\"`);\n\t\t}\n\t\tlet owner = root;\n\t\tfor (const seg of segments) {\n\t\t\tconst next = owner._mounts.get(seg);\n\t\t\tif (!next) throw new Error(`unknown mount \"${seg}\" in path \"${path}\"`);\n\t\t\towner = next;\n\t\t}\n\t\treturn [owner, local];\n\t}\n\n\t/**\n\t * Graphs reachable from this instance via nested {@link Graph.mount} (includes `this`).\n\t */\n\tprivate _graphsReachableViaMounts(seen = new Set<Graph>()): Set<Graph> {\n\t\tif (seen.has(this)) return seen;\n\t\tseen.add(this);\n\t\tfor (const child of this._mounts.values()) {\n\t\t\tchild._graphsReachableViaMounts(seen);\n\t\t}\n\t\treturn seen;\n\t}\n\n\t/**\n\t * Resolve an endpoint: returns `[owningGraph, localName, node]`.\n\t * Accepts both local names and `::` qualified paths.\n\t */\n\tprivate _resolveEndpoint(path: string): [Graph, string, Node] {\n\t\tif (!path.includes(PATH_SEP)) {\n\t\t\tconst n = this._nodes.get(path);\n\t\t\tif (!n) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${path}\"`);\n\t\t\t}\n\t\t\treturn [this, path, n];\n\t\t}\n\t\tconst segments = splitPath(path, this.name);\n\t\treturn this._resolveEndpointFromSegments(segments, path);\n\t}\n\n\tprivate _resolveEndpointFromSegments(\n\t\tsegments: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return [this, head, n];\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${head}\" (from path \"${fullPath}\")`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaEndpointKeys(localN, head, rest, fullPath);\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\t\treturn child._resolveEndpointFromSegments(rest, fullPath);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Node registry\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Registers a node under a local name. Fails if the name is already used,\n\t * reserved by a mount, or the same node instance is already registered.\n\t *\n\t * @param name - Local key (no `::`).\n\t * @param node - Node instance to own.\n\t */\n\tadd(name: string, node: Node): void {\n\t\tassertLocalName(name, this.name, \"add\");\n\t\tassertNoPathSep(name, this.name, \"add\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"node\");\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": name \"${name}\" is already a mount point`);\n\t\t}\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node \"${name}\" already exists`);\n\t\t}\n\t\tfor (const [existingName, existing] of this._nodes) {\n\t\t\tif (existing === node) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": node instance already registered as \"${existingName}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._nodes.set(name, node);\n\t\tif (node instanceof NodeImpl) {\n\t\t\tnode._assignRegistryName(name);\n\t\t\tif (this._defaultVersioningLevel != null) {\n\t\t\t\tnode._applyVersioning(this._defaultVersioningLevel);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Set a default versioning level for all nodes added to this graph (roadmap §6.0).\n\t *\n\t * Nodes already registered are retroactively upgraded. Nodes added later via\n\t * {@link add} will inherit this level unless they already have versioning.\n\t *\n\t * **Scope:** Does not propagate to mounted subgraphs. Call `setVersioning`\n\t * on each child graph separately if needed.\n\t *\n\t * @param level - `0` for V0, `1` for V1, or `undefined` to clear.\n\t */\n\tsetVersioning(level: VersioningLevel | undefined): void {\n\t\tthis._defaultVersioningLevel = level;\n\t\tif (level == null) return;\n\t\tfor (const n of this._nodes.values()) {\n\t\t\tif (n instanceof NodeImpl) {\n\t\t\t\tn._applyVersioning(level);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters a node or unmounts a subgraph, drops incident edges, and sends\n\t * `[[TEARDOWN]]` to the removed node or recursively through the mounted subtree (§3.2).\n\t *\n\t * @param name - Local mount or node name.\n\t */\n\tremove(name: string): void {\n\t\tassertLocalName(name, this.name, \"remove\");\n\t\tassertNoPathSep(name, this.name, \"remove\");\n\n\t\t// Case 1: unmount a subgraph\n\t\tconst child = this._mounts.get(name);\n\t\tif (child) {\n\t\t\tthis._mounts.delete(name);\n\t\t\t// Drop edges touching this mount name or qualified paths under it.\n\t\t\tconst prefix = `${name}${PATH_SEP}`;\n\t\t\tfor (const key of [...this._edges]) {\n\t\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\t\tif (from === name || to === name || from.startsWith(prefix) || to.startsWith(prefix)) {\n\t\t\t\t\tthis._edges.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tteardownMountedGraph(child);\n\t\t\treturn;\n\t\t}\n\n\t\t// Case 2: remove a local node\n\t\tconst node = this._nodes.get(name);\n\t\tif (!node) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node or mount \"${name}\"`);\n\t\t}\n\t\tthis._nodes.delete(name);\n\t\tfor (const key of [...this._edges]) {\n\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\tif (from === name || to === name) this._edges.delete(key);\n\t\t}\n\t\tnode.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n\n\t/**\n\t * Returns a node by local name or `::` qualified path.\n\t * Local names are looked up directly; paths with `::` delegate to {@link resolve}.\n\t *\n\t * @param name - Local name or qualified path.\n\t */\n\tnode(name: string): Node {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node name must be non-empty`);\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\treturn this.resolve(name);\n\t\t}\n\t\tconst n = this._nodes.get(name);\n\t\tif (!n) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${name}\"`);\n\t\t}\n\t\treturn n;\n\t}\n\n\t/**\n\t * Reads `graph.node(name).get()` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @returns Cached value or `undefined`.\n\t */\n\tget(name: string): unknown {\n\t\treturn this.node(name).get();\n\t}\n\n\t/**\n\t * Shorthand for `graph.node(name).down([[DATA, value]], { actor })` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @param value - Next `DATA` payload.\n\t * @param options - Optional `actor` and `internal` guard bypass.\n\t */\n\tset(name: string, value: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[DATA, value]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Edges\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Record a wire from `fromPath` → `toPath` (§3.3). Accepts local names or\n\t * `::` qualified paths. The target must be a {@link NodeImpl} whose `_deps`\n\t * includes the source node (same reference). Idempotent.\n\t *\n\t * Same-owner edges are stored on the owning child graph; cross-subgraph edges\n\t * are stored on this (parent) graph's registry.\n\t *\n\t * @param fromPath - Source endpoint (local or qualified).\n\t * @param toPath - Target endpoint whose deps already include the source node.\n\t */\n\tconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": connect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal, fromNode] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal, toNode] = this._resolveEndpoint(toPath);\n\n\t\tif (fromNode === toNode) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot connect a node to itself`);\n\t\t}\n\n\t\tif (!(toNode instanceof NodeImpl)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) requires the target to be a graphrefly NodeImpl so deps can be validated`,\n\t\t\t);\n\t\t}\n\t\tif (!toNode._deps.includes(fromNode)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) — target must include source in its constructor deps (same node reference)`,\n\t\t\t);\n\t\t}\n\n\t\tif (fromGraph === toGraph) {\n\t\t\t// Same-owner: store on the child graph\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tfromGraph._edges.add(key);\n\t\t} else {\n\t\t\t// Cross-subgraph: store on this (parent) graph\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tthis._edges.add(key);\n\t\t}\n\t}\n\n\t/**\n\t * Remove a registered edge (§3.3). Accepts local names or `::` qualified paths.\n\t *\n\t * **Registry-only (§C resolved):** This drops the edge from the graph's edge\n\t * registry only. It does **not** mutate the target node's constructor-time\n\t * dependency list, bitmasks, or upstream subscriptions. Message flow follows\n\t * constructor-time deps, not the edge registry. For runtime dep rewiring, use\n\t * {@link dynamicNode}.\n\t *\n\t * @param fromPath - Registered edge tail.\n\t * @param toPath - Registered edge head.\n\t */\n\tdisconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": disconnect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal] = this._resolveEndpoint(toPath);\n\n\t\tif (fromGraph === toGraph) {\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tif (!fromGraph._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tif (!this._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns registered `[from, to]` edge pairs (read-only snapshot).\n\t *\n\t * @returns Edge pairs recorded on this graph instance’s local `_edges` set.\n\t */\n\tedges(): ReadonlyArray<[string, string]> {\n\t\tconst result: [string, string][] = [];\n\t\tfor (const key of this._edges) {\n\t\t\tresult.push(parseEdgeKey(key));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Composition\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Embed a child graph at a local mount name (§3.4). Child nodes are reachable via\n\t * {@link Graph.resolve} using `::` delimited paths (§3.5). Lifecycle\n\t * {@link Graph.signal} visits mounted subgraphs recursively.\n\t *\n\t * Rejects: same name as existing node or mount, self-mount, mount cycles,\n\t * and the same child graph instance mounted twice on one parent.\n\t *\n\t * @param name - Local mount point.\n\t * @param child - Nested `Graph` instance.\n\t */\n\tmount(name: string, child: Graph): void {\n\t\tassertLocalName(name, this.name, \"mount\");\n\t\tassertNoPathSep(name, this.name, \"mount\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"mount\");\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": cannot mount at \"${name}\" — node with that name exists`,\n\t\t\t);\n\t\t}\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount \"${name}\" already exists`);\n\t\t}\n\t\tif (child === this) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot mount a graph into itself`);\n\t\t}\n\t\t// Reject same child instance mounted twice on this parent.\n\t\tfor (const existing of this._mounts.values()) {\n\t\t\tif (existing === child) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": this child graph is already mounted on this graph`);\n\t\t\t}\n\t\t}\n\t\tif (child._graphsReachableViaMounts().has(this)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount(\"${name}\", …) would create a mount cycle`);\n\t\t}\n\t\tthis._mounts.set(name, child);\n\t}\n\n\t/**\n\t * Look up a node by qualified path (§3.5). Segments are separated by `::`.\n\t *\n\t * If the first segment equals this graph's {@link Graph.name}, it is stripped\n\t * (so `root.resolve(\"app::a\")` works when `root.name === \"app\"`).\n\t *\n\t * @param path - Qualified `::` path or local name.\n\t * @returns The resolved `Node`.\n\t */\n\tresolve(path: string): Node {\n\t\tlet segments = splitPath(path, this.name);\n\t\tif (segments[0] === this.name) {\n\t\t\tsegments = segments.slice(1);\n\t\t\tif (segments.length === 0) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": resolve path ends at graph name only`);\n\t\t\t}\n\t\t}\n\t\treturn this._resolveFromSegments(segments);\n\t}\n\n\tprivate _resolveFromSegments(segments: readonly string[]): Node {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return n;\n\t\t\tif (this._mounts.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": path ends at subgraph \"${head}\" — not a node (GRAPHREFLY-SPEC §3.5)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown name \"${head}\"`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaChainFromNode(localN, rest, segments.join(PATH_SEP));\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\n\t\treturn child.resolve(rest.join(PATH_SEP));\n\t}\n\n\t/**\n\t * Resolve `::__meta__::key` segments from a registered primary node (possibly chained).\n\t */\n\tprivate _resolveMetaChainFromNode(n: Node, parts: readonly string[], fullPath: string): Node {\n\t\tlet current = n;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = p[i + 1] as string;\n\t\t\tconst next = current.meta[key];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown meta \"${key}\" in path \"${fullPath}\"`);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate _resolveMetaEndpointKeys(\n\t\tbaseNode: Node,\n\t\tbaseLocalKey: string,\n\t\tparts: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tlet current = baseNode;\n\t\tlet localKey = baseLocalKey;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst metaKey = p[i + 1] as string;\n\t\t\tconst next = current.meta[metaKey];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": unknown meta \"${metaKey}\" on node (in \"${fullPath}\")`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlocalKey = `${localKey}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${metaKey}`;\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn [this, localKey, current];\n\t}\n\n\t/**\n\t * Deliver a message batch to every registered node in this graph and, recursively,\n\t * in mounted child graphs (§3.7). Recurses into mounts first, then delivers to\n\t * local nodes (sorted by name). Each {@link Node} receives at most one delivery\n\t * per call (deduped by reference).\n\t *\n\t * Companion `meta` nodes receive the same batch for control-plane types (e.g.\n\t * PAUSE) that the primary does not forward. **TEARDOWN-only** batches skip the\n\t * extra meta pass — the primary’s `down()` already cascades TEARDOWN to meta.\n\t *\n\t * @param messages - Batch to deliver to every registered node (and mounts, recursively).\n\t * @param options - Optional `actor` / `internal` for transport.\n\t */\n\tsignal(messages: Messages, options?: GraphActorOptions): void {\n\t\tthis._signalDeliver(messages, options ?? {}, new Set());\n\t}\n\n\tprivate _signalDeliver(messages: Messages, opts: GraphActorOptions, vis: Set<Node>): void {\n\t\tfor (const sub of this._mounts.values()) {\n\t\t\tsub._signalDeliver(messages, opts, vis);\n\t\t}\n\t\tconst internal = opts.internal === true;\n\t\tconst downOpts: NodeTransportOptions = internal\n\t\t\t? { internal: true }\n\t\t\t: { actor: opts.actor, delivery: \"signal\" };\n\t\tconst metaMessages = filterMetaMessages(messages);\n\t\tfor (const localName of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(localName)!;\n\t\t\tif (vis.has(n)) continue;\n\t\t\tvis.add(n);\n\t\t\tn.down(messages, downOpts);\n\t\t\tif (metaMessages.length === 0) continue;\n\t\t\tthis._signalMetaSubtree(n, metaMessages, vis, downOpts);\n\t\t}\n\t}\n\n\tprivate _signalMetaSubtree(\n\t\troot: Node,\n\t\tmessages: Messages,\n\t\tvis: Set<Node>,\n\t\tdownOpts: NodeTransportOptions,\n\t): void {\n\t\tfor (const mk of Object.keys(root.meta).sort()) {\n\t\t\tconst mnode = root.meta[mk];\n\t\t\tif (vis.has(mnode)) continue;\n\t\t\tvis.add(mnode);\n\t\t\tmnode.down(messages, downOpts);\n\t\t\tthis._signalMetaSubtree(mnode, messages, vis, downOpts);\n\t\t}\n\t}\n\n\t/**\n\t * Static structure snapshot: qualified node keys, edges, mount names (GRAPHREFLY-SPEC §3.6, Appendix B).\n\t *\n\t * @param options - Optional `actor` for guard-scoped visibility and/or `filter` for selective output.\n\t * @returns JSON-shaped describe payload for this graph tree.\n\t *\n\t * @example\n\t * ```ts\n\t * graph.describe() // full snapshot\n\t * graph.describe({ actor: llm }) // guard-scoped\n\t * graph.describe({ filter: { status: \"errored\" } }) // only errored nodes\n\t * graph.describe({ filter: (n) => n.type === \"state\" }) // predicate filter\n\t * ```\n\t */\n\tdescribe(options?: { actor?: Actor; filter?: DescribeFilter }): GraphDescribeOutput {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\tconst nodeToPath = new Map<Node, string>();\n\t\tfor (const [p, n] of targets) {\n\t\t\tnodeToPath.set(n, p);\n\t\t}\n\t\tconst nodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const [p, n] of targets) {\n\t\t\tif (actor != null && !n.allowsObserve(actor)) continue;\n\t\t\tconst raw = describeNode(n);\n\t\t\tconst deps =\n\t\t\t\tn instanceof NodeImpl ? n._deps.map((d) => nodeToPath.get(d) ?? d.name ?? \"\") : [];\n\t\t\tconst { name: _name, ...rest } = raw;\n\t\t\tconst entry: DescribeNodeOutput = { ...rest, deps };\n\t\t\tif (filter != null) {\n\t\t\t\tif (typeof filter === \"function\") {\n\t\t\t\t\tconst fn = filter as\n\t\t\t\t\t\t| ((nodePath: string, node: DescribeNodeOutput) => boolean)\n\t\t\t\t\t\t| ((node: DescribeNodeOutput) => boolean);\n\t\t\t\t\tconst pass =\n\t\t\t\t\t\tfn.length >= 2\n\t\t\t\t\t\t\t? (fn as (nodePath: string, node: DescribeNodeOutput) => boolean)(p, entry)\n\t\t\t\t\t\t\t: (fn as (node: DescribeNodeOutput) => boolean)(entry);\n\t\t\t\t\tif (!pass) continue;\n\t\t\t\t} else {\n\t\t\t\t\tlet match = true;\n\t\t\t\t\tfor (const [fk, fv] of Object.entries(filter)) {\n\t\t\t\t\t\tconst normalizedKey =\n\t\t\t\t\t\t\tfk === \"deps_includes\" ? \"depsIncludes\" : fk === \"meta_has\" ? \"metaHas\" : fk;\n\t\t\t\t\t\tif (normalizedKey === \"depsIncludes\") {\n\t\t\t\t\t\t\tif (!entry.deps.includes(String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (normalizedKey === \"metaHas\") {\n\t\t\t\t\t\t\tif (!Object.hasOwn(entry.meta, String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((entry as Record<string, unknown>)[normalizedKey] !== fv) {\n\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) continue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodes[p] = entry;\n\t\t}\n\t\tconst nodeKeys = new Set(Object.keys(nodes));\n\t\tlet edges = this._collectAllEdges(\"\");\n\t\tif (actor != null || filter != null) {\n\t\t\tedges = edges.filter((e) => nodeKeys.has(e.from) && nodeKeys.has(e.to));\n\t\t}\n\t\tedges.sort((a, b) => {\n\t\t\tif (a.from < b.from) return -1;\n\t\t\tif (a.from > b.from) return 1;\n\t\t\tif (a.to < b.to) return -1;\n\t\t\tif (a.to > b.to) return 1;\n\t\t\treturn 0;\n\t\t});\n\t\tconst allSubgraphs = this._collectSubgraphs(\"\");\n\t\tconst subgraphs =\n\t\t\tactor != null || filter != null\n\t\t\t\t? allSubgraphs.filter((sg) => {\n\t\t\t\t\t\tconst prefix = `${sg}${PATH_SEP}`;\n\t\t\t\t\t\treturn [...nodeKeys].some((k) => k === sg || k.startsWith(prefix));\n\t\t\t\t\t})\n\t\t\t\t: allSubgraphs;\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t};\n\t}\n\n\tprivate _collectSubgraphs(prefix: string): string[] {\n\t\tconst out: string[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst q = prefix === \"\" ? m : `${prefix}${m}`;\n\t\t\tout.push(q);\n\t\t\tout.push(...this._mounts.get(m)!._collectSubgraphs(`${q}${PATH_SEP}`));\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _collectAllEdges(prefix: string): { from: string; to: string }[] {\n\t\tconst out: { from: string; to: string }[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tout.push(...this._mounts.get(m)!._collectAllEdges(p2));\n\t\t}\n\t\tfor (const [f, t] of this.edges()) {\n\t\t\tout.push({\n\t\t\t\tfrom: this._qualifyEdgeEndpoint(f, prefix),\n\t\t\t\tto: this._qualifyEdgeEndpoint(t, prefix),\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _qualifyEdgeEndpoint(part: string, prefix: string): string {\n\t\tif (part.includes(PATH_SEP)) return part;\n\t\treturn prefix === \"\" ? part : `${prefix}${PATH_SEP}${part}`;\n\t}\n\n\tprivate _collectObserveTargets(prefix: string, out: [string, Node][]): void {\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tthis._mounts.get(m)!._collectObserveTargets(p2, out);\n\t\t}\n\t\tfor (const loc of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(loc)!;\n\t\t\tconst p = prefix === \"\" ? loc : `${prefix}${PATH_SEP}${loc}`;\n\t\t\tout.push([p, n]);\n\t\t\tthis._appendMetaObserveTargets(p, n, out);\n\t\t}\n\t}\n\n\tprivate _appendMetaObserveTargets(basePath: string, n: Node, out: [string, Node][]): void {\n\t\tfor (const mk of Object.keys(n.meta).sort()) {\n\t\t\tconst m = n.meta[mk];\n\t\t\tconst mp = `${basePath}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${mk}`;\n\t\t\tout.push([mp, m]);\n\t\t\tthis._appendMetaObserveTargets(mp, m, out);\n\t\t}\n\t}\n\n\t/**\n\t * Live message stream from one node (or meta path), or from the whole graph (§3.6).\n\t *\n\t * Overloads: `(path, options?)` for one node; `(options?)` for all nodes. Whole-graph mode\n\t * subscribes in **sorted path order** (code-point order). With structured options\n\t * (`structured`, `timeline`, `causal`, `derived`), returns an {@link ObserveResult}.\n\t * Inspector-gated extras (`causal` / `derived`) require {@link Graph.inspectorEnabled}.\n\t *\n\t * @param pathOrOpts - Qualified `path` string, or omit and pass only `options` for graph-wide observation.\n\t * @param options - Optional `actor`, `structured`, `causal`, `timeline` (inspector-gated).\n\t * @returns `GraphObserveOne`, `GraphObserveAll`, or `ObserveResult` depending on overload/options.\n\t */\n\tobserve(\n\t\tpath: string,\n\t\toptions?: ObserveOptions & {\n\t\t\tstructured?: true;\n\t\t\ttimeline?: true;\n\t\t\tcausal?: true;\n\t\t\tderived?: true;\n\t\t},\n\t): ObserveResult;\n\tobserve(path: string, options?: ObserveOptions): GraphObserveOne;\n\tobserve(\n\t\toptions: ObserveOptions & { structured?: true; timeline?: true; causal?: true; derived?: true },\n\t): ObserveResult;\n\tobserve(options?: ObserveOptions): GraphObserveAll;\n\tobserve(\n\t\tpathOrOpts?: string | ObserveOptions,\n\t\toptions?: ObserveOptions,\n\t): GraphObserveOne | GraphObserveAll | ObserveResult {\n\t\tif (typeof pathOrOpts === \"string\") {\n\t\t\tconst path = pathOrOpts;\n\t\t\tconst actor = options?.actor;\n\t\t\tconst target = this.resolve(path);\n\t\t\tif (actor != null && !target.allowsObserve(actor)) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: path });\n\t\t\t}\n\t\t\tconst wantsStructured =\n\t\t\t\toptions?.structured === true ||\n\t\t\t\toptions?.timeline === true ||\n\t\t\t\toptions?.causal === true ||\n\t\t\t\toptions?.derived === true;\n\t\t\tif (wantsStructured && Graph.inspectorEnabled) {\n\t\t\t\treturn this._createObserveResult(path, target, options);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsubscribe(sink: NodeSink) {\n\t\t\t\t\treturn target.subscribe(sink);\n\t\t\t\t},\n\t\t\t\tup(messages: Messages) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttarget.up?.(messages);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst opts = pathOrOpts as ObserveOptions | undefined;\n\t\tconst actor = opts?.actor;\n\t\tconst wantsStructured =\n\t\t\topts?.structured === true ||\n\t\t\topts?.timeline === true ||\n\t\t\topts?.causal === true ||\n\t\t\topts?.derived === true;\n\t\tif (wantsStructured && Graph.inspectorEnabled) {\n\t\t\treturn this._createObserveResultForAll(opts ?? {});\n\t\t}\n\t\treturn {\n\t\t\tsubscribe: (sink: (nodePath: string, messages: Messages) => void) => {\n\t\t\t\tconst targets: [string, Node][] = [];\n\t\t\t\tthis._collectObserveTargets(\"\", targets);\n\t\t\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\t\t\tconst picked =\n\t\t\t\t\tactor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\t\t\tconst unsubs = picked.map(([p, nd]) =>\n\t\t\t\t\tnd.subscribe((msgs) => {\n\t\t\t\t\t\tsink(p, msgs);\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn () => {\n\t\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\t};\n\t\t\t},\n\t\t\tup: (upPath: string, messages: Messages) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst nd = this.resolve(upPath);\n\t\t\t\t\tnd.up?.(messages);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResult<T>(\n\t\tpath: string,\n\t\ttarget: Node<T>,\n\t\toptions: ObserveOptions,\n\t): ObserveResult<T> {\n\t\tconst timeline = options.timeline === true;\n\t\tconst causal = options.causal === true;\n\t\tconst derived = options.derived === true;\n\t\tconst result: {\n\t\t\tvalues: Record<string, T>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tcompletedCleanly: boolean;\n\t\t\terrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tcompletedCleanly: false,\n\t\t\terrored: false,\n\t\t};\n\n\t\tlet lastTriggerDepIndex: number | undefined;\n\t\tlet lastRunDepValues: unknown[] | undefined;\n\t\tlet detachInspectorHook: (() => void) | undefined;\n\t\tif ((causal || derived) && target instanceof NodeImpl) {\n\t\t\tdetachInspectorHook = target._setInspectorHook((event: NodeInspectorHookEvent) => {\n\t\t\t\tif (event.kind === \"dep_message\") {\n\t\t\t\t\tlastTriggerDepIndex = event.depIndex;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlastRunDepValues = [...event.depValues];\n\t\t\t\tif (derived) {\n\t\t\t\t\tresult.events.push({\n\t\t\t\t\t\ttype: \"derived\",\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tdep_values: [...event.depValues],\n\t\t\t\t\t\t...(timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {}),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst unsub = target.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst t = m[0];\n\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\tconst withCausal =\n\t\t\t\t\tcausal && lastRunDepValues != null\n\t\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\t\tconst triggerDep =\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex != null &&\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex >= 0 &&\n\t\t\t\t\t\t\t\t\ttarget instanceof NodeImpl\n\t\t\t\t\t\t\t\t\t\t? target._deps[lastTriggerDepIndex]\n\t\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\t\tconst tv = triggerDep?.v;\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\ttrigger_dep_index: lastTriggerDepIndex,\n\t\t\t\t\t\t\t\t\ttrigger_dep_name: triggerDep?.name,\n\t\t\t\t\t\t\t\t\t...(tv != null ? { trigger_version: { id: tv.id, version: tv.version } } : {}),\n\t\t\t\t\t\t\t\t\tdep_values: [...lastRunDepValues],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t})()\n\t\t\t\t\t\t: {};\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tresult.values[path] = m[1] as T;\n\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base, ...withCausal });\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base, ...withCausal });\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!result.errored) result.completedCleanly = true;\n\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tresult.errored = true;\n\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget completedCleanly() {\n\t\t\t\treturn result.completedCleanly;\n\t\t\t},\n\t\t\tget errored() {\n\t\t\t\treturn result.errored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tunsub();\n\t\t\t\tdetachInspectorHook?.();\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResultForAll(options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline === true;\n\t\tconst result: {\n\t\t\tvalues: Record<string, unknown>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tcompletedCleanly: boolean;\n\t\t\terrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tcompletedCleanly: false,\n\t\t\terrored: false,\n\t\t};\n\t\tconst actor = options.actor;\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst picked = actor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\tconst unsubs = picked.map(([path, nd]) =>\n\t\t\tnd.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tconst t = m[0];\n\t\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tresult.values[path] = m[1];\n\t\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base });\n\t\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\tif (!result.errored) result.completedCleanly = true;\n\t\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tresult.errored = true;\n\t\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget completedCleanly() {\n\t\t\t\treturn result.completedCleanly;\n\t\t\t},\n\t\t\tget errored() {\n\t\t\t\treturn result.errored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Convenience live debugger over {@link Graph.observe}. Logs protocol events as they flow.\n\t *\n\t * Supports one-node (`path`) and graph-wide modes, event filtering, and JSON/pretty rendering.\n\t * Color themes are built in (`ansi` / `none`) to avoid external dependencies.\n\t *\n\t * @param options - Spy configuration.\n\t * @returns Disposable handle plus a structured observation accumulator.\n\t */\n\tspy(options: GraphSpyOptions = {}): GraphSpyHandle {\n\t\tconst include = options.includeTypes ? new Set(options.includeTypes) : null;\n\t\tconst exclude = options.excludeTypes ? new Set(options.excludeTypes) : null;\n\t\tconst theme = resolveSpyTheme(options.theme);\n\t\tconst format = options.format ?? \"pretty\";\n\t\tconst logger = options.logger ?? ((line: string) => console.log(line));\n\n\t\tconst shouldLog = (type: ObserveEvent[\"type\"]): boolean => {\n\t\t\tif (include?.has(type) === false) return false;\n\t\t\tif (exclude?.has(type) === true) return false;\n\t\t\treturn true;\n\t\t};\n\n\t\tconst renderEvent = (event: ObserveEvent): string => {\n\t\t\tif (format === \"json\") {\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.stringify(event);\n\t\t\t\t} catch {\n\t\t\t\t\treturn JSON.stringify({\n\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\tpath: event.path,\n\t\t\t\t\t\tdata: \"[unserializable]\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst color = theme[event.type] ?? \"\";\n\t\t\tconst pathPart = event.path ? `${theme.path}${event.path}${theme.reset} ` : \"\";\n\t\t\tconst dataPart = event.data !== undefined ? ` ${describeData(event.data)}` : \"\";\n\t\t\tconst triggerPart =\n\t\t\t\tevent.trigger_dep_name != null\n\t\t\t\t\t? ` <- ${event.trigger_dep_name}`\n\t\t\t\t\t: event.trigger_dep_index != null\n\t\t\t\t\t\t? ` <- #${event.trigger_dep_index}`\n\t\t\t\t\t\t: \"\";\n\t\t\tconst batchPart = event.in_batch ? \" [batch]\" : \"\";\n\t\t\treturn `${pathPart}${color}${event.type.toUpperCase()}${theme.reset}${dataPart}${triggerPart}${batchPart}`;\n\t\t};\n\n\t\tif (!Graph.inspectorEnabled) {\n\t\t\tconst timeline = options.timeline ?? true;\n\t\t\tconst acc: {\n\t\t\t\tvalues: Record<string, unknown>;\n\t\t\t\tdirtyCount: number;\n\t\t\t\tresolvedCount: number;\n\t\t\t\tevents: ObserveEvent[];\n\t\t\t\tcompletedCleanly: boolean;\n\t\t\t\terrored: boolean;\n\t\t\t} = {\n\t\t\t\tvalues: {},\n\t\t\t\tdirtyCount: 0,\n\t\t\t\tresolvedCount: 0,\n\t\t\t\tevents: [],\n\t\t\t\tcompletedCleanly: false,\n\t\t\t\terrored: false,\n\t\t\t};\n\t\t\tlet stop: () => void = () => {};\n\t\t\tconst result: ObserveResult = {\n\t\t\t\tget values() {\n\t\t\t\t\treturn acc.values;\n\t\t\t\t},\n\t\t\t\tget dirtyCount() {\n\t\t\t\t\treturn acc.dirtyCount;\n\t\t\t\t},\n\t\t\t\tget resolvedCount() {\n\t\t\t\t\treturn acc.resolvedCount;\n\t\t\t\t},\n\t\t\t\tget events() {\n\t\t\t\t\treturn acc.events;\n\t\t\t\t},\n\t\t\t\tget completedCleanly() {\n\t\t\t\t\treturn acc.completedCleanly;\n\t\t\t\t},\n\t\t\t\tget errored() {\n\t\t\t\t\treturn acc.errored;\n\t\t\t\t},\n\t\t\t\tdispose() {\n\t\t\t\t\tstop();\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tconst pushEvent = (path: string | undefined, message: Messages[number]) => {\n\t\t\t\tconst t = message[0];\n\t\t\t\tconst base = timeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching() } : {};\n\t\t\t\tlet event: ObserveEvent | undefined;\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tif (path != null) acc.values[path] = message[1];\n\t\t\t\t\tevent = { type: \"data\", ...(path != null ? { path } : {}), data: message[1], ...base };\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tacc.dirtyCount += 1;\n\t\t\t\t\tevent = { type: \"dirty\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tacc.resolvedCount += 1;\n\t\t\t\t\tevent = { type: \"resolved\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!acc.errored) acc.completedCleanly = true;\n\t\t\t\t\tevent = { type: \"complete\", ...(path != null ? { path } : {}), ...base };\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tacc.errored = true;\n\t\t\t\t\tevent = {\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t...(path != null ? { path } : {}),\n\t\t\t\t\t\tdata: message[1],\n\t\t\t\t\t\t...base,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!event) return;\n\t\t\t\tacc.events.push(event);\n\t\t\t\tif (!shouldLog(event.type)) return;\n\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t};\n\n\t\t\tif (options.path != null) {\n\t\t\t\tconst stream = this.observe(options.path, {\n\t\t\t\t\tactor: options.actor,\n\t\t\t\t\tstructured: false,\n\t\t\t\t});\n\t\t\t\tstop = stream.subscribe((messages) => {\n\t\t\t\t\tfor (const m of messages) {\n\t\t\t\t\t\tpushEvent(options.path, m);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst stream = this.observe({ actor: options.actor, structured: false });\n\t\t\t\tstop = stream.subscribe((path, messages) => {\n\t\t\t\t\tfor (const m of messages) {\n\t\t\t\t\t\tpushEvent(path, m);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresult,\n\t\t\t\tdispose() {\n\t\t\t\t\tresult.dispose();\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst structuredObserveOptions = {\n\t\t\tactor: options.actor,\n\t\t\tstructured: true as const,\n\t\t\t...(options.timeline !== false ? { timeline: true as const } : {}),\n\t\t\t...(options.causal ? { causal: true as const } : {}),\n\t\t\t...(options.derived ? { derived: true as const } : {}),\n\t\t};\n\t\tconst result: ObserveResult =\n\t\t\toptions.path != null\n\t\t\t\t? this.observe(options.path, structuredObserveOptions)\n\t\t\t\t: this.observe(structuredObserveOptions);\n\n\t\tlet cursor = 0;\n\t\tconst flushNewEvents = () => {\n\t\t\tconst nextEvents = result.events.slice(cursor);\n\t\t\tcursor = result.events.length;\n\t\t\tfor (const event of nextEvents) {\n\t\t\t\tif (!shouldLog(event.type)) continue;\n\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t}\n\t\t};\n\n\t\tconst stream =\n\t\t\toptions.path != null\n\t\t\t\t? this.observe(options.path, { actor: options.actor, structured: false })\n\t\t\t\t: this.observe({ actor: options.actor, structured: false });\n\n\t\tconst stop =\n\t\t\toptions.path != null\n\t\t\t\t? (stream as GraphObserveOne).subscribe((messages) => {\n\t\t\t\t\t\tif (messages.length > 0) {\n\t\t\t\t\t\t\tflushNewEvents();\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t: (stream as GraphObserveAll).subscribe((_path, messages) => {\n\t\t\t\t\t\tif (messages.length > 0) {\n\t\t\t\t\t\t\tflushNewEvents();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\treturn {\n\t\t\tresult,\n\t\t\tdispose() {\n\t\t\t\tstop();\n\t\t\t\tflushNewEvents();\n\t\t\t\tresult.dispose();\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * CLI/debug-friendly graph dump built on {@link Graph.describe}.\n\t *\n\t * @param options - Optional actor/filter/format toggles.\n\t * @returns Rendered graph text.\n\t */\n\tdumpGraph(options: GraphDumpOptions = {}): string {\n\t\tconst described = this.describe({\n\t\t\tactor: options.actor,\n\t\t\tfilter: options.filter,\n\t\t});\n\t\tconst includeEdges = options.includeEdges ?? true;\n\t\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\t\tif (options.format === \"json\") {\n\t\t\tconst payload: GraphDescribeOutput = {\n\t\t\t\tname: described.name,\n\t\t\t\tnodes: described.nodes,\n\t\t\t\tedges: includeEdges ? described.edges : [],\n\t\t\t\tsubgraphs: includeSubgraphs ? described.subgraphs : [],\n\t\t\t};\n\t\t\tconst text = JSON.stringify(sortJsonValue(payload), null, options.indent ?? 2);\n\t\t\toptions.logger?.(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tconst lines: string[] = [];\n\t\tlines.push(`Graph ${described.name}`);\n\t\tlines.push(\"Nodes:\");\n\t\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\t\tconst n = described.nodes[path]!;\n\t\t\tlines.push(`- ${path} (${n.type}/${n.status}): ${describeData(n.value)}`);\n\t\t}\n\t\tif (includeEdges) {\n\t\t\tlines.push(\"Edges:\");\n\t\t\tfor (const edge of described.edges) {\n\t\t\t\tlines.push(`- ${edge.from} -> ${edge.to}`);\n\t\t\t}\n\t\t}\n\t\tif (includeSubgraphs) {\n\t\t\tlines.push(\"Subgraphs:\");\n\t\t\tfor (const sg of described.subgraphs) {\n\t\t\t\tlines.push(`- ${sg}`);\n\t\t\t}\n\t\t}\n\t\tconst text = lines.join(\"\\n\");\n\t\toptions.logger?.(text);\n\t\treturn text;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Lifecycle & persistence (§3.7–§3.8)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Sends `[[TEARDOWN]]` to all nodes, then clears registries on this graph and every\n\t * mounted subgraph (§3.7). The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\tthis.signal([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tfor (const dispose of [...this._autoCheckpointDisposers]) {\n\t\t\ttry {\n\t\t\t\tdispose();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t\tthis._autoCheckpointDisposers.clear();\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/** Clear structure after parent already signaled TEARDOWN through this subtree. */\n\tprivate _destroyClearOnly(): void {\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/**\n\t * Serializes structure and current values to JSON-shaped data (§3.8). Same information\n\t * as {@link Graph.describe} plus a `version` field for format evolution.\n\t *\n\t * @returns Persistable snapshot with sorted keys.\n\t */\n\tsnapshot(): GraphPersistSnapshot {\n\t\tconst d = this.describe();\n\t\t// Explicit key sorting for deterministic output — don't rely on\n\t\t// describe() iteration order (audit batch-3, §3.8).\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tsortedNodes[key] = d.nodes[key]!;\n\t\t}\n\t\tconst sortedSubgraphs = [...d.subgraphs].sort();\n\t\treturn { ...d, version: 1, nodes: sortedNodes, subgraphs: sortedSubgraphs };\n\t}\n\n\t/**\n\t * Apply persisted values onto an existing graph whose topology matches the snapshot\n\t * (§3.8). Only {@link DescribeNodeOutput.type} `state` and `producer` entries with a\n\t * `value` field are written; `derived` / `operator` / `effect` are skipped so deps\n\t * drive recomputation. Unknown paths are ignored.\n\t *\n\t * @param data - Snapshot envelope with matching `name` and node slices.\n\t * @throws If `data.name` does not equal {@link Graph.name}.\n\t */\n\trestore(data: GraphPersistSnapshot, options?: { only?: string | readonly string[] }): void {\n\t\tparseSnapshotEnvelope(data);\n\t\tif (data.name !== this.name) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": restore snapshot name \"${data.name}\" does not match this graph`,\n\t\t\t);\n\t\t}\n\t\tconst onlyPatterns =\n\t\t\toptions?.only == null\n\t\t\t\t? null\n\t\t\t\t: (Array.isArray(options.only) ? options.only : [options.only]).map((p) => globToRegex(p));\n\t\tfor (const path of Object.keys(data.nodes).sort()) {\n\t\t\tif (onlyPatterns !== null && !onlyPatterns.some((re) => re.test(path))) continue;\n\t\t\tconst slice = data.nodes[path];\n\t\t\tif (slice === undefined || slice.value === undefined) continue;\n\t\t\tif (slice.type === \"derived\" || slice.type === \"operator\" || slice.type === \"effect\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.set(path, slice.value);\n\t\t\t} catch {\n\t\t\t\t/* missing path or set not applicable */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a graph named from the snapshot, optionally runs `build` to register nodes\n\t * and mounts, then {@link Graph.restore} values (§3.8).\n\t *\n\t * @param data - Snapshot envelope (`version` checked).\n\t * @param build - Optional callback to construct topology before values are applied.\n\t * @returns Hydrated `Graph` instance.\n\t */\n\tstatic fromSnapshot(data: GraphPersistSnapshot, build?: (g: Graph) => void): Graph {\n\t\tparseSnapshotEnvelope(data);\n\t\tconst g = new Graph(data.name);\n\t\tif (build) {\n\t\t\tbuild(g);\n\t\t\tg.restore(data);\n\t\t\treturn g;\n\t\t}\n\t\t// Auto-create mount hierarchy from subgraphs.\n\t\tfor (const mount of [...data.subgraphs].sort((a, b) => {\n\t\t\tconst da = a.split(PATH_SEP).length;\n\t\t\tconst db = b.split(PATH_SEP).length;\n\t\t\tif (da !== db) return da - db;\n\t\t\tif (a < b) return -1;\n\t\t\tif (a > b) return 1;\n\t\t\treturn 0;\n\t\t})) {\n\t\t\tconst parts = mount.split(PATH_SEP);\n\t\t\tlet target: Graph = g;\n\t\t\tfor (const seg of parts) {\n\t\t\t\tif (!target._mounts.has(seg)) {\n\t\t\t\t\ttarget.mount(seg, new Graph(seg));\n\t\t\t\t}\n\t\t\t\ttarget = target._mounts.get(seg)!;\n\t\t\t}\n\t\t}\n\n\t\tconst primaryEntries = Object.entries(data.nodes)\n\t\t\t.filter(([path]) => !path.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`))\n\t\t\t.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst pending = new Map(primaryEntries);\n\t\tconst created = new Map<string, Node>();\n\n\t\tlet progressed = true;\n\t\twhile (pending.size > 0 && progressed) {\n\t\t\tprogressed = false;\n\t\t\tfor (const [path, slice] of [...pending.entries()]) {\n\t\t\t\tconst deps = slice?.deps ?? [];\n\t\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\t\t\t\tconst [owner, localName] = Graph._ownerForPath(g, path);\n\t\t\t\tconst meta: Record<string, unknown> = { ...(slice?.meta ?? {}) };\n\t\t\t\tconst factory = Graph._factoryForPath(path);\n\t\t\t\tlet node: Node;\n\t\t\t\tif (slice?.type === \"state\") {\n\t\t\t\t\tnode = stateNode(slice.value, { meta });\n\t\t\t\t} else {\n\t\t\t\t\tif (factory == null) continue;\n\t\t\t\t\tnode = factory(localName, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\ttype: slice.type,\n\t\t\t\t\t\tvalue: slice.value,\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tresolvedDeps: deps.map((dep) => created.get(dep)!),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\towner.add(localName, node);\n\t\t\t\tcreated.set(path, node);\n\t\t\t\tpending.delete(path);\n\t\t\t\tprogressed = true;\n\t\t\t}\n\t\t}\n\t\tif (pending.size > 0) {\n\t\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`Graph.fromSnapshot could not reconstruct nodes without build callback: ${unresolved}. ` +\n\t\t\t\t\t`Register matching factories with Graph.registerFactory(pattern, factory).`,\n\t\t\t);\n\t\t}\n\t\tfor (const edge of data.edges) {\n\t\t\ttry {\n\t\t\t\tg.connect(edge.from, edge.to);\n\t\t\t} catch {\n\t\t\t\t/* ignore malformed or non-reconstructable edge */\n\t\t\t}\n\t\t}\n\t\tg.restore(data);\n\t\treturn g;\n\t}\n\n\t/**\n\t * Plain snapshot with **recursively sorted object keys** for deterministic serialization (§3.8).\n\t *\n\t * @remarks\n\t * ECMAScript `JSON.stringify(graph)` invokes this method; it must return a plain object, not an\n\t * already-stringified JSON string (otherwise the graph would be double-encoded).\n\t * For a single UTF-8 string with a trailing newline (convenient for git), use {@link Graph.toJSONString}.\n\t *\n\t * @returns Same object as {@link Graph.snapshot}.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * Deterministic JSON **text**: `JSON.stringify` of {@link Graph.toJSON} plus a trailing newline (§3.8).\n\t *\n\t * @returns Stable string suitable for diffs.\n\t */\n\ttoJSONString(): string {\n\t\treturn stableJsonStringify(this.snapshot());\n\t}\n\n\t/**\n\t * Debounced persistence wired to graph-wide observe stream (spec §3.8 auto-checkpoint).\n\t *\n\t * Checkpoint trigger uses {@link messageTier}: only batches containing tier >= 2 messages\n\t * schedule a save (`DATA`/`RESOLVED`/terminal/destruction), never pure tier-0/1 control waves.\n\t */\n\tautoCheckpoint(\n\t\tadapter: AutoCheckpointAdapter,\n\t\toptions: GraphAutoCheckpointOptions = {},\n\t): GraphAutoCheckpointHandle {\n\t\tconst debounceMs = Math.max(0, options.debounceMs ?? 500);\n\t\tconst compactEvery = Math.max(1, options.compactEvery ?? 10);\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet seq = 0;\n\t\tlet pending = false;\n\t\tlet lastDescribe: GraphDescribeOutput | undefined;\n\n\t\tconst flush = () => {\n\t\t\ttimer = undefined;\n\t\t\tif (!pending) return;\n\t\t\tpending = false;\n\t\t\ttry {\n\t\t\t\tconst described = this.describe();\n\t\t\t\tconst snapshot = { ...described, version: SNAPSHOT_VERSION };\n\t\t\t\tseq += 1;\n\t\t\t\tconst shouldCompact = lastDescribe == null || seq % compactEvery === 0;\n\t\t\t\tif (shouldCompact) {\n\t\t\t\t\tadapter.save({ mode: \"full\", snapshot, seq } satisfies GraphCheckpointRecord);\n\t\t\t\t} else {\n\t\t\t\t\tconst previous = lastDescribe;\n\t\t\t\t\tif (previous == null) return;\n\t\t\t\t\tadapter.save({\n\t\t\t\t\t\tmode: \"diff\",\n\t\t\t\t\t\tdiff: Graph.diff(previous, described),\n\t\t\t\t\t\tsnapshot,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t} satisfies GraphCheckpointRecord);\n\t\t\t\t}\n\t\t\t\tlastDescribe = described;\n\t\t\t} catch (error) {\n\t\t\t\toptions.onError?.(error);\n\t\t\t}\n\t\t};\n\n\t\tconst schedule = () => {\n\t\t\tpending = true;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = setTimeout(flush, debounceMs);\n\t\t};\n\n\t\tconst off = this.observe().subscribe((path, messages) => {\n\t\t\tconst triggeredByTier = messages.some((m) => messageTier(m[0]) >= 2);\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst described = this.describe().nodes[path];\n\t\t\t\tif (described == null || !options.filter(path, described)) return;\n\t\t\t}\n\t\t\tschedule();\n\t\t});\n\n\t\tconst dispose = () => {\n\t\t\toff();\n\t\t\tif (timer !== undefined) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = undefined;\n\t\t\t}\n\t\t\tthis._autoCheckpointDisposers.delete(dispose);\n\t\t};\n\t\tthis._autoCheckpointDisposers.add(dispose);\n\t\treturn { dispose };\n\t}\n\n\t/**\n\t * Export the current graph topology as Mermaid flowchart text.\n\t *\n\t * Renders qualified node paths and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns Mermaid flowchart source.\n\t */\n\ttoMermaid(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`flowchart ${direction}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(` ${id}[\"${escapeMermaidLabel(path)}\"]`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(` ${fromId} --> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t/**\n\t * Export the current graph topology as D2 diagram text.\n\t *\n\t * Renders qualified node paths, constructor deps, and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns D2 source text.\n\t */\n\ttoD2(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`direction: ${d2DirectionFromGraphDirection(direction)}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(`${id}: \"${escapeD2Label(path)}\"`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(`${fromId} -> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Inspector (roadmap 3.3) — reasoning trace, overhead gating\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * When `false`, structured observation options (`causal`, `timeline`),\n\t * `annotate()`, and `traceLog()` are no-ops. Raw `observe()` always works.\n\t *\n\t * Default: `true` outside production (`process.env.NODE_ENV !== \"production\"`).\n\t */\n\tstatic inspectorEnabled = !(\n\t\ttypeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n\t);\n\n\tprivate _annotations = new Map<string, string>();\n\tprivate _traceRing = new RingBuffer<TraceEntry>(1000);\n\n\t/**\n\t * Attaches a reasoning annotation to a node — captures *why* an AI agent set a value.\n\t *\n\t * No-op when {@link Graph.inspectorEnabled} is `false`.\n\t *\n\t * @param path - Qualified node path.\n\t * @param reason - Free-text note stored in the trace ring buffer.\n\t */\n\tannotate(path: string, reason: string): void {\n\t\tif (!Graph.inspectorEnabled) return;\n\t\tthis.resolve(path); // validate path exists\n\t\tthis._annotations.set(path, reason);\n\t\tthis._traceRing.push({ path, reason, timestamp_ns: monotonicNs() });\n\t}\n\n\t/**\n\t * Returns a chronological log of all reasoning annotations (ring buffer).\n\t *\n\t * @returns `[]` when {@link Graph.inspectorEnabled} is `false`.\n\t */\n\ttraceLog(): readonly TraceEntry[] {\n\t\tif (!Graph.inspectorEnabled) return [];\n\t\treturn this._traceRing.toArray();\n\t}\n\n\t/**\n\t * Computes structural + value diff between two {@link Graph.describe} snapshots.\n\t *\n\t * @param a - Earlier describe output.\n\t * @param b - Later describe output.\n\t * @returns Added/removed nodes, changed fields, and edge deltas.\n\t */\n\tstatic diff(a: GraphDescribeOutput, b: GraphDescribeOutput): GraphDiffResult {\n\t\tconst aKeys = new Set(Object.keys(a.nodes));\n\t\tconst bKeys = new Set(Object.keys(b.nodes));\n\n\t\tconst nodesAdded = [...bKeys].filter((k) => !aKeys.has(k)).sort();\n\t\tconst nodesRemoved = [...aKeys].filter((k) => !bKeys.has(k)).sort();\n\t\tconst nodesChanged: GraphDiffChange[] = [];\n\n\t\tfor (const key of aKeys) {\n\t\t\tif (!bKeys.has(key)) continue;\n\t\t\tconst na = a.nodes[key];\n\t\t\tconst nb = b.nodes[key];\n\t\t\t// V0 optimization: skip value comparison when both nodes have matching versions.\n\t\t\tconst av = na.v;\n\t\t\tconst bv = nb.v;\n\t\t\tif (av != null && bv != null && av.id === bv.id && av.version === bv.version) {\n\t\t\t\t// Version unchanged — only check type/status (cheap string compare).\n\t\t\t\tfor (const field of [\"type\", \"status\"] as const) {\n\t\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\t\tif (va !== vb) {\n\t\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const field of [\"type\", \"status\", \"value\"] as const) {\n\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\tif (!Object.is(va, vb) && JSON.stringify(va) !== JSON.stringify(vb)) {\n\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst edgeKey = (e: { from: string; to: string }) => `${e.from}\\t${e.to}`;\n\t\tconst aEdges = new Set(a.edges.map(edgeKey));\n\t\tconst bEdges = new Set(b.edges.map(edgeKey));\n\n\t\tconst edgesAdded = b.edges.filter((e) => !aEdges.has(edgeKey(e)));\n\t\tconst edgesRemoved = a.edges.filter((e) => !bEdges.has(edgeKey(e)));\n\t\tconst aSubgraphs = new Set(a.subgraphs);\n\t\tconst bSubgraphs = new Set(b.subgraphs);\n\t\tconst subgraphsAdded = [...bSubgraphs].filter((s) => !aSubgraphs.has(s)).sort();\n\t\tconst subgraphsRemoved = [...aSubgraphs].filter((s) => !bSubgraphs.has(s)).sort();\n\n\t\treturn {\n\t\t\tnodesAdded,\n\t\t\tnodesRemoved,\n\t\t\tnodesChanged,\n\t\t\tedgesAdded,\n\t\t\tedgesRemoved,\n\t\t\tsubgraphsAdded,\n\t\t\tsubgraphsRemoved,\n\t\t};\n\t}\n}\n\n/** Entry in the reasoning trace ring buffer (roadmap 3.3). */\nexport type TraceEntry = {\n\tpath: string;\n\treason: string;\n\ttimestamp_ns: number;\n};\n\n/** Result of {@link Graph.diff}. */\nexport type GraphDiffResult = {\n\tnodesAdded: string[];\n\tnodesRemoved: string[];\n\tnodesChanged: GraphDiffChange[];\n\tedgesAdded: Array<{ from: string; to: string }>;\n\tedgesRemoved: Array<{ from: string; to: string }>;\n\tsubgraphsAdded: string[];\n\tsubgraphsRemoved: string[];\n};\n\n/** A single field change within a diff. */\nexport type GraphDiffChange = {\n\tpath: string;\n\tfield: string;\n\tfrom: unknown;\n\tto: unknown;\n};\n\n/** Direction for {@link reachable} graph traversal. */\nexport type ReachableDirection = \"upstream\" | \"downstream\";\n\n/** Options for {@link reachable}. */\nexport type ReachableOptions = {\n\t/** Maximum hop depth from `from` (0 returns `[]`). Omit for unbounded traversal. */\n\tmaxDepth?: number;\n};\n\n/**\n * Reachability query over a {@link Graph.describe} snapshot.\n *\n * Traversal combines dependency links (`deps`) and explicit graph edges (`edges`):\n * - `upstream`: follows `deps` plus incoming edges.\n * - `downstream`: follows reverse-`deps` plus outgoing edges.\n *\n * @param described - `graph.describe()` output to traverse.\n * @param from - Start path (qualified node path).\n * @param direction - Traversal direction.\n * @param options - Optional max depth bound.\n * @returns Sorted list of reachable paths (excluding `from`).\n *\n * @example\n * ```ts\n * import { Graph, reachable } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const a = g.register(\"a\");\n * const b = g.register(\"b\", [a]);\n * const described = g.describe();\n *\n * reachable(described, \"app.a\", \"downstream\"); // [\"app.b\"]\n * reachable(described, \"app.b\", \"upstream\"); // [\"app.a\"]\n * ```\n */\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions: ReachableOptions = {},\n): string[] {\n\tif (!from) return [];\n\tif (direction !== \"upstream\" && direction !== \"downstream\") {\n\t\tthrow new Error(`reachable: direction must be \"upstream\" or \"downstream\"`);\n\t}\n\tconst maxDepth = options.maxDepth;\n\tif (maxDepth != null && (!Number.isInteger(maxDepth) || maxDepth < 0)) {\n\t\tthrow new Error(`reachable: maxDepth must be an integer >= 0`);\n\t}\n\tif (maxDepth === 0) return [];\n\n\tconst depsByPath = new Map<string, string[]>();\n\tconst reverseDeps = new Map<string, Set<string>>();\n\tconst incomingEdges = new Map<string, Set<string>>();\n\tconst outgoingEdges = new Map<string, Set<string>>();\n\tconst universe = new Set<string>();\n\n\tconst nodesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"nodes\" in described &&\n\t\ttypeof (described as Record<string, unknown>).nodes === \"object\" &&\n\t\t(described as Record<string, unknown>).nodes !== null &&\n\t\t!Array.isArray((described as Record<string, unknown>).nodes)\n\t\t\t? ((described as Record<string, unknown>).nodes as Record<string, unknown>)\n\t\t\t: {};\n\tconst edgesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"edges\" in described &&\n\t\tArray.isArray((described as Record<string, unknown>).edges)\n\t\t\t? ((described as Record<string, unknown>).edges as unknown[])\n\t\t\t: [];\n\n\tfor (const [path, node] of Object.entries(nodesRaw)) {\n\t\tif (!path) continue;\n\t\tuniverse.add(path);\n\t\tconst deps =\n\t\t\tnode != null && typeof node === \"object\" && Array.isArray((node as { deps?: unknown[] }).deps)\n\t\t\t\t? (node as { deps: unknown[] }).deps\n\t\t\t\t: [];\n\t\tconst cleanDeps = deps.filter((d): d is string => typeof d === \"string\" && d.length > 0);\n\t\tdepsByPath.set(path, cleanDeps);\n\t\tfor (const dep of cleanDeps) {\n\t\t\tuniverse.add(dep);\n\t\t\tif (!reverseDeps.has(dep)) reverseDeps.set(dep, new Set());\n\t\t\treverseDeps.get(dep)!.add(path);\n\t\t}\n\t}\n\tfor (const edge of edgesRaw) {\n\t\tif (edge == null || typeof edge !== \"object\") continue;\n\t\tconst edgeFrom =\n\t\t\t\"from\" in edge && typeof (edge as { from?: unknown }).from === \"string\"\n\t\t\t\t? ((edge as { from: string }).from as string)\n\t\t\t\t: \"\";\n\t\tconst edgeTo =\n\t\t\t\"to\" in edge && typeof (edge as { to?: unknown }).to === \"string\"\n\t\t\t\t? ((edge as { to: string }).to as string)\n\t\t\t\t: \"\";\n\t\tif (!edgeFrom || !edgeTo) continue;\n\t\tuniverse.add(edgeFrom);\n\t\tuniverse.add(edgeTo);\n\t\tif (!outgoingEdges.has(edgeFrom)) outgoingEdges.set(edgeFrom, new Set());\n\t\toutgoingEdges.get(edgeFrom)!.add(edgeTo);\n\t\tif (!incomingEdges.has(edgeTo)) incomingEdges.set(edgeTo, new Set());\n\t\tincomingEdges.get(edgeTo)!.add(edgeFrom);\n\t}\n\n\tif (!universe.has(from)) return [];\n\n\tconst neighbors = (path: string): string[] => {\n\t\tif (direction === \"upstream\") {\n\t\t\tconst depNeighbors = depsByPath.get(path) ?? [];\n\t\t\tconst edgeNeighbors = [...(incomingEdges.get(path) ?? [])];\n\t\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t\t}\n\t\tconst depNeighbors = [...(reverseDeps.get(path) ?? [])];\n\t\tconst edgeNeighbors = [...(outgoingEdges.get(path) ?? [])];\n\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t};\n\n\tconst visited = new Set<string>([from]);\n\tconst out = new Set<string>();\n\tconst queue: Array<{ path: string; depth: number }> = [{ path: from, depth: 0 }];\n\twhile (queue.length > 0) {\n\t\tconst next = queue.shift()!;\n\t\tif (maxDepth != null && next.depth >= maxDepth) continue;\n\t\tfor (const nb of neighbors(next.path)) {\n\t\t\tif (!nb || visited.has(nb)) continue;\n\t\t\tvisited.add(nb);\n\t\t\tout.add(nb);\n\t\t\tqueue.push({ path: nb, depth: next.depth + 1 });\n\t\t}\n\t}\n\n\treturn [...out].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n","/**\n * CQRS patterns (roadmap §4.5).\n *\n * Composition layer over reactiveLog (3.2), pipeline/sagas (4.1), event bus (4.2),\n * projections (4.3). Guards (1.5) enforce command/query boundary.\n *\n * - `cqrs(name, opts?)` → `CqrsGraph` — top-level factory\n * - `CqrsGraph.command(name, handler)` — write-only node; guard rejects `observe`\n * - `CqrsGraph.event(name)` — backed by `reactiveLog`; append-only\n * - `CqrsGraph.projection(name, events, reducer, initial)` — read-only derived; guard rejects `write`\n * - `CqrsGraph.saga(name, events, handler)` — event-driven side effects\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { wallClockNs } from \"../core/clock.js\";\nimport { policy } from \"../core/guard.js\";\nimport { DATA, derived, type Node, node, state } from \"../core/index.js\";\nimport { type ReactiveLogSnapshot, reactiveLog } from \"../extra/reactive-log.js\";\nimport { Graph, type GraphOptions } from \"../graph/index.js\";\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Commands: write + signal allowed, observe denied. */\nconst COMMAND_GUARD = policy((allow, deny) => {\n\tallow(\"write\");\n\tallow(\"signal\");\n\tdeny(\"observe\");\n});\n\n/** Projections: observe + signal allowed, write denied. */\nconst PROJECTION_GUARD = policy((allow, deny) => {\n\tallow(\"observe\");\n\tallow(\"signal\");\n\tdeny(\"write\");\n});\n\n/** Events: observe + signal allowed, write denied (appended internally). */\nconst EVENT_GUARD = policy((allow, deny) => {\n\tallow(\"observe\");\n\tallow(\"signal\");\n\tdeny(\"write\");\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction cqrsMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn { cqrs: true, cqrs_type: kind, ...(extra ?? {}) };\n}\n\n/**\n * Keep a derived node's dep wiring alive for `get()` without a user sink.\n * Returns the unsubscribe handle so callers can clean up.\n */\nfunction keepalive(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => {});\n}\n\n// ---------------------------------------------------------------------------\n// Event envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Immutable envelope for events emitted by command handlers.\n *\n * `seq` is a per-graph monotonic counter that provides stable ordering when\n * multiple events share the same `timestampNs` (same wall-clock tick).\n */\nexport type CqrsEvent<T = unknown> = {\n\ttype: string;\n\tpayload: T;\n\t/** Wall-clock nanoseconds (via `wallClockNs()`). */\n\ttimestampNs: number;\n\t/** Monotonic sequence within this CqrsGraph instance. */\n\tseq: number;\n\t/** V0 identity of the event log node at append time (§6.0b). */\n\tv0?: { id: string; version: number };\n};\n\n// ---------------------------------------------------------------------------\n// Event store adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Opaque replay cursor returned by `loadEvents`. Pass it back to\n * `loadEvents` to resume from the last position.\n */\nexport type EventStoreCursor = {\n\treadonly __brand?: \"EventStoreCursor\";\n\t[key: string]: unknown;\n};\n\n/**\n * Result of `loadEvents` — events plus an opaque cursor for resumption.\n */\nexport type LoadEventsResult = {\n\tevents: CqrsEvent[];\n\tcursor: EventStoreCursor | undefined;\n};\n\n/**\n * Pluggable persistence for CQRS events.\n *\n * **`persist`:** Must be synchronous. Called from the dispatch path inside\n * `batch()`. Adapters that need async I/O should buffer internally and\n * expose a `flush()` method for explicit drain.\n */\nexport interface EventStoreAdapter {\n\tpersist(event: CqrsEvent): void;\n\t/**\n\t * Load persisted events. When `cursor` is provided, returns only events\n\t * after that position. The returned `cursor` should be passed to the next\n\t * `loadEvents` call for incremental replay.\n\t */\n\tloadEvents(\n\t\teventType: string,\n\t\tcursor?: EventStoreCursor,\n\t): LoadEventsResult | Promise<LoadEventsResult>;\n\t/** Optional explicit flush for adapters with async I/O. */\n\tflush?(): Promise<void>;\n}\n\nexport class MemoryEventStore implements EventStoreAdapter {\n\tprivate readonly _store = new Map<string, CqrsEvent[]>();\n\n\tpersist(event: CqrsEvent): void {\n\t\tlet list = this._store.get(event.type);\n\t\tif (!list) {\n\t\t\tlist = [];\n\t\t\tthis._store.set(event.type, list);\n\t\t}\n\t\tlist.push(event);\n\t}\n\n\tloadEvents(eventType: string, cursor?: EventStoreCursor): LoadEventsResult {\n\t\tconst list = this._store.get(eventType) ?? [];\n\t\tconst sinceTs = (cursor as { timestampNs?: number } | undefined)?.timestampNs;\n\t\tconst sinceSeq = (cursor as { seq?: number } | undefined)?.seq;\n\t\tconst events =\n\t\t\tsinceTs == null\n\t\t\t\t? [...list]\n\t\t\t\t: list.filter(\n\t\t\t\t\t\t(e) =>\n\t\t\t\t\t\t\te.timestampNs > sinceTs || (e.timestampNs === sinceTs && e.seq > (sinceSeq ?? -1)),\n\t\t\t\t\t);\n\t\tconst lastEvent = events.length > 0 ? events[events.length - 1] : undefined;\n\t\treturn {\n\t\t\tevents,\n\t\t\tcursor: lastEvent ? { timestampNs: lastEvent.timestampNs, seq: lastEvent.seq } : cursor,\n\t\t};\n\t}\n\n\tclear(): void {\n\t\tthis._store.clear();\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Handler types\n// ---------------------------------------------------------------------------\n\nexport type CommandActions = {\n\t/** Append an event to a named event log (bypasses event guard). */\n\temit: (eventName: string, payload: unknown) => void;\n};\n\n/**\n * Command handler receives the dispatch payload and actions to emit events.\n *\n * **Purity:** Handlers should not mutate the payload. Event emission via\n * `actions.emit()` is the only sanctioned side effect.\n */\nexport type CommandHandler<T = unknown> = (payload: T, actions: CommandActions) => void;\n\n/**\n * Projection reducer folds events into a read model.\n *\n * **Purity contract:** Reducers MUST be pure — return a new state value\n * without mutating `state` or any event. The `state` parameter is the\n * original `initial` value on every invocation (full event-sourcing replay),\n * so mutation would corrupt future recomputations.\n */\nexport type ProjectionReducer<TState = unknown, TEvent = unknown> = (\n\tstate: TState,\n\tevents: readonly CqrsEvent<TEvent>[],\n) => TState;\n\nexport type SagaHandler<T = unknown> = (event: CqrsEvent<T>) => void;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport type CqrsOptions = {\n\tgraph?: GraphOptions;\n};\n\n// ---------------------------------------------------------------------------\n// CqrsGraph\n// ---------------------------------------------------------------------------\n\ntype EventEntry = {\n\tlog: ReturnType<typeof reactiveLog<CqrsEvent>>;\n\tnode: Node<ReactiveLogSnapshot<CqrsEvent>>;\n};\n\nexport class CqrsGraph extends Graph {\n\tprivate readonly _eventLogs = new Map<string, EventEntry>();\n\tprivate readonly _commandHandlers = new Map<string, CommandHandler<any>>();\n\tprivate readonly _projections = new Set<string>();\n\tprivate readonly _sagas = new Set<string>();\n\tprivate readonly _keepaliveDisposers: Array<() => void> = [];\n\tprivate _eventStore: EventStoreAdapter | undefined;\n\tprivate _seq = 0;\n\n\tconstructor(name: string, opts: CqrsOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const dispose of this._keepaliveDisposers) dispose();\n\t\tthis._keepaliveDisposers.length = 0;\n\t\tsuper.destroy();\n\t}\n\n\t// -- Events ---------------------------------------------------------------\n\n\t/**\n\t * Register a named event stream backed by `reactiveLog`.\n\t * Guard denies external `write` — only commands append internally.\n\t */\n\tevent(name: string): Node<ReactiveLogSnapshot<CqrsEvent>> {\n\t\tconst existing = this._eventLogs.get(name);\n\t\tif (existing) return existing.node;\n\n\t\tconst log = reactiveLog<CqrsEvent>([], { name });\n\t\tconst entries = log.entries;\n\t\tconst guarded = derived<ReactiveLogSnapshot<CqrsEvent>>(\n\t\t\t[entries],\n\t\t\t([snapshot]) => snapshot as ReactiveLogSnapshot<CqrsEvent>,\n\t\t\t{\n\t\t\t\tname,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\tmeta: cqrsMeta(\"event\", { event_name: name }),\n\t\t\t\tguard: EVENT_GUARD,\n\t\t\t\tinitial: entries.get() as ReactiveLogSnapshot<CqrsEvent>,\n\t\t\t},\n\t\t);\n\t\tthis.add(name, guarded);\n\t\tthis._keepaliveDisposers.push(keepalive(guarded));\n\t\tthis._eventLogs.set(name, { log, node: guarded });\n\t\treturn guarded;\n\t}\n\n\t/** Internal: append to an event log, auto-registering if needed. */\n\tprivate _appendEvent(eventName: string, payload: unknown): void {\n\t\tlet entry = this._eventLogs.get(eventName);\n\t\tif (!entry) {\n\t\t\tthis.event(eventName);\n\t\t\tentry = this._eventLogs.get(eventName)!;\n\t\t}\n\t\t// Guard: reject dispatch to terminated event streams\n\t\tif (entry.node.status === \"completed\" || entry.node.status === \"errored\") {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot dispatch to terminated event stream \"${eventName}\" (status: ${entry.node.status}).`,\n\t\t\t);\n\t\t}\n\t\tconst nv = entry.log.entries.v;\n\t\tconst evt: CqrsEvent = {\n\t\t\ttype: eventName,\n\t\t\tpayload,\n\t\t\ttimestampNs: wallClockNs(),\n\t\t\tseq: ++this._seq,\n\t\t\t...(nv != null ? { v0: { id: nv.id, version: nv.version } } : {}),\n\t\t};\n\t\tentry.log.append(evt);\n\t\tif (this._eventStore) {\n\t\t\tthis._eventStore.persist(evt);\n\t\t}\n\t}\n\n\t// -- Commands -------------------------------------------------------------\n\n\t/**\n\t * Register a command with its handler. Guard denies `observe` (write-only).\n\t * Use `dispatch(name, payload)` to execute.\n\t *\n\t * The command node carries dynamic `meta.error` — a reactive companion\n\t * that holds the last handler error (or `null` on success).\n\t */\n\tcommand<T = unknown>(name: string, handler: CommandHandler<T>): Node<T> {\n\t\tconst cmdNode = state<T>(undefined as T, {\n\t\t\tname,\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: {\n\t\t\t\t...cqrsMeta(\"command\", { command_name: name }),\n\t\t\t\terror: null,\n\t\t\t},\n\t\t\tguard: COMMAND_GUARD,\n\t\t});\n\t\tthis.add(name, cmdNode);\n\t\tthis._commandHandlers.set(name, handler as CommandHandler<any>);\n\t\treturn cmdNode;\n\t}\n\n\t/**\n\t * Execute a registered command. Wraps the entire dispatch in `batch()` so\n\t * the command node DATA and all emitted events settle atomically.\n\t *\n\t * If the handler throws, `meta.error` on the command node is set to the\n\t * error and the exception is re-thrown.\n\t */\n\tdispatch<T = unknown>(commandName: string, payload: T): void {\n\t\tconst handler = this._commandHandlers.get(commandName);\n\t\tif (!handler) {\n\t\t\tthrow new Error(`Unknown command: \"${commandName}\". Register with .command() first.`);\n\t\t}\n\t\tconst cmdNode = this.resolve(commandName);\n\t\tbatch(() => {\n\t\t\tcmdNode.down([[DATA, payload]], { internal: true });\n\t\t\ttry {\n\t\t\t\thandler(payload, { emit: (eName, data) => this._appendEvent(eName, data) });\n\t\t\t\tcmdNode.meta.error.down([[DATA, null]], { internal: true });\n\t\t\t} catch (err) {\n\t\t\t\tcmdNode.meta.error.down([[DATA, err]], { internal: true });\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t});\n\t}\n\n\t// -- Projections ----------------------------------------------------------\n\n\t/**\n\t * Register a read-only projection derived from event streams.\n\t * Guard denies `write` — value is computed from events only.\n\t *\n\t * **Purity contract:** The `reducer` must be a pure function — it receives\n\t * the original `initial` on every invocation (full event-sourcing replay).\n\t * Never mutate `initial`; always return a new value.\n\t */\n\tprojection<TState>(\n\t\tname: string,\n\t\teventNames: readonly string[],\n\t\treducer: ProjectionReducer<TState>,\n\t\tinitial: TState,\n\t): Node<TState> {\n\t\tconst eventNodes = eventNames.map((eName) => {\n\t\t\tif (!this._eventLogs.has(eName)) this.event(eName);\n\t\t\treturn this._eventLogs.get(eName)!.node;\n\t\t});\n\n\t\tconst projNode = derived<TState>(\n\t\t\teventNodes,\n\t\t\t(snapshots) => {\n\t\t\t\tconst allEvents: CqrsEvent[] = [];\n\t\t\t\tfor (const snapshot of snapshots) {\n\t\t\t\t\tconst snap = snapshot as ReactiveLogSnapshot<CqrsEvent>;\n\t\t\t\t\tallEvents.push(...snap.value.entries);\n\t\t\t\t}\n\t\t\t\tallEvents.sort((a, b) => a.timestampNs - b.timestampNs || a.seq - b.seq);\n\t\t\t\treturn reducer(initial, allEvents);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname,\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: cqrsMeta(\"projection\", { projection_name: name, source_events: eventNames }),\n\t\t\t\tguard: PROJECTION_GUARD,\n\t\t\t\tinitial,\n\t\t\t},\n\t\t);\n\n\t\tthis.add(name, projNode);\n\t\tfor (const eName of eventNames) this.connect(eName, name);\n\t\tthis._keepaliveDisposers.push(keepalive(projNode));\n\t\tthis._projections.add(name);\n\t\treturn projNode;\n\t}\n\n\t// -- Sagas ----------------------------------------------------------------\n\n\t/**\n\t * Register an event-driven side effect. Runs handler for each **new** event\n\t * from the specified streams (tracks last-processed entry count per stream).\n\t *\n\t * The saga node carries dynamic `meta.error` — a reactive companion that\n\t * holds the last handler error (or `null` on success). Handler errors do\n\t * not propagate out of the saga run (the event cursor still advances so\n\t * the same entry is not delivered twice).\n\t */\n\tsaga<T = unknown>(\n\t\tname: string,\n\t\teventNames: readonly string[],\n\t\thandler: SagaHandler<T>,\n\t): Node<unknown> {\n\t\tconst eventNodes = eventNames.map((eName) => {\n\t\t\tif (!this._eventLogs.has(eName)) this.event(eName);\n\t\t\treturn this._eventLogs.get(eName)!.node;\n\t\t});\n\n\t\t// Track last-processed entry count per event to only process new entries\n\t\tconst lastCounts = new Map<string, number>();\n\n\t\tconst sagaRef: { n?: Node<unknown> } = {};\n\t\tconst sagaNode = node(\n\t\t\teventNodes,\n\t\t\t(snapshots) => {\n\t\t\t\tconst errNode = sagaRef.n!.meta.error as Node<unknown>;\n\t\t\t\tfor (let i = 0; i < snapshots.length; i++) {\n\t\t\t\t\tconst snap = snapshots[i] as ReactiveLogSnapshot<CqrsEvent<T>>;\n\t\t\t\t\tconst eName = eventNames[i];\n\t\t\t\t\tconst entries = snap.value.entries;\n\t\t\t\t\tconst lastCount = lastCounts.get(eName) ?? 0;\n\t\t\t\t\tif (entries.length > lastCount) {\n\t\t\t\t\t\tconst newEntries = entries.slice(lastCount);\n\t\t\t\t\t\tfor (const entry of newEntries) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\thandler(entry as CqrsEvent<T>);\n\t\t\t\t\t\t\t\terrNode.down([[DATA, null]], { internal: true });\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\terrNode.down([[DATA, err]], { internal: true });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastCounts.set(eName, entries.length);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname,\n\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\tmeta: {\n\t\t\t\t\t...cqrsMeta(\"saga\", { saga_name: name, source_events: eventNames }),\n\t\t\t\t\terror: null,\n\t\t\t\t},\n\t\t\t},\n\t\t) as Node<unknown>;\n\t\tsagaRef.n = sagaNode;\n\n\t\tthis.add(name, sagaNode);\n\t\tfor (const eName of eventNames) this.connect(eName, name);\n\t\tthis._keepaliveDisposers.push(keepalive(sagaNode));\n\t\tthis._sagas.add(name);\n\t\treturn sagaNode;\n\t}\n\n\t// -- Event store ----------------------------------------------------------\n\n\tuseEventStore(adapter: EventStoreAdapter): void {\n\t\tthis._eventStore = adapter;\n\t}\n\n\t/**\n\t * Replay persisted events through a reducer to rebuild a read model.\n\t * Requires an event store adapter wired via `useEventStore()`.\n\t */\n\tasync rebuildProjection<TState>(\n\t\teventNames: readonly string[],\n\t\treducer: ProjectionReducer<TState>,\n\t\tinitial: TState,\n\t): Promise<TState> {\n\t\tif (!this._eventStore) {\n\t\t\tthrow new Error(\"No event store wired. Call useEventStore() first.\");\n\t\t}\n\t\tconst allEvents: CqrsEvent[] = [];\n\t\tfor (const eName of eventNames) {\n\t\t\tconst result = await this._eventStore.loadEvents(eName);\n\t\t\tallEvents.push(...result.events);\n\t\t}\n\t\tallEvents.sort((a, b) => a.timestampNs - b.timestampNs || a.seq - b.seq);\n\t\treturn reducer(initial, allEvents);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a CQRS graph container.\n *\n * @example\n * ```ts\n * const app = cqrs(\"orders\");\n * app.event(\"orderPlaced\");\n * app.command(\"placeOrder\", (payload, { emit }) => {\n * emit(\"orderPlaced\", { orderId: payload.id, amount: payload.amount });\n * });\n * app.projection(\"orderCount\", [\"orderPlaced\"], (_s, events) => events.length, 0);\n * app.dispatch(\"placeOrder\", { id: \"1\", amount: 100 });\n * ```\n */\nexport function cqrs(name: string, opts?: CqrsOptions): CqrsGraph {\n\treturn new CqrsGraph(name, opts);\n}\n","/**\n * Core layer: message protocol, node primitive, lifecycle (Phase 0).\n */\nexport * from \"./actor.js\";\nexport * from \"./batch.js\";\nexport { monotonicNs, wallClockNs } from \"./clock.js\";\nexport * from \"./dynamic-node.js\";\nexport * from \"./guard.js\";\nexport * from \"./messages.js\";\nexport * from \"./meta.js\";\nexport {\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeFn,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\tnode,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node.js\";\nexport * from \"./sugar.js\";\nexport {\n\tadvanceVersion,\n\tcreateVersioning,\n\tdefaultHash,\n\ttype HashFn,\n\tisV1,\n\ttype NodeVersionInfo,\n\ttype V0,\n\ttype V1,\n\ttype VersioningLevel,\n\ttype VersioningOptions,\n} from \"./versioning.js\";\n","/**\n * Shared internals for roadmap §3.2 data structures (option B — versioned snapshots).\n *\n * @remarks\n * Not re-exported from the package barrel; consumers use concrete factories\n * (`reactiveMap`, …). Keeps `equals` / snapshot wiring consistent across\n * collections without exposing a second public protocol.\n *\n * @packageDocumentation\n * @internal\n */\n\n/**\n * Immutable value paired with a monotonic version for {@link NodeOptions.equals}.\n * Downstream nodes can treat unchanged versions as `RESOLVED`-eligible via `equals`.\n *\n * When the backing node has V0 versioning (GRAPHREFLY-SPEC §7), `v0` carries\n * the node's identity (`id`) and version counter for diff-friendly observation\n * and cross-snapshot dedup (roadmap §6.0b).\n */\nexport type Versioned<T> = {\n\treadonly version: number;\n\treadonly value: T;\n\t/** V0 identity from the backing node, when versioning is enabled. */\n\treadonly v0?: { readonly id: string; readonly version: number };\n};\n\n/**\n * `NodeOptions.equals` helper: compares only `version` on {@link Versioned} snapshots.\n */\nexport function snapshotEqualsVersion(a: unknown, b: unknown): boolean {\n\tif (typeof a !== \"object\" || a == null || typeof b !== \"object\" || b == null) {\n\t\treturn Object.is(a, b);\n\t}\n\tif (!(\"version\" in a) || !(\"version\" in b)) return Object.is(a, b);\n\treturn (a as Versioned<unknown>).version === (b as Versioned<unknown>).version;\n}\n\n/**\n * Returns the next snapshot with an incremented version (pure).\n * When `v0` is provided, it is included in the snapshot for V0-aware consumers.\n *\n * **Note:** `v0` is captured before the backing node's DATA emission (which\n * advances the node's version counter). The embedded `v0.version` is therefore\n * one behind the node's post-emission `node.v.version`. This is intentional —\n * `v0` records the node's version at snapshot construction time.\n */\nexport function bumpVersion<T>(\n\tcurrent: Versioned<T>,\n\tnextValue: T,\n\tv0?: { id: string; version: number },\n): Versioned<T> {\n\tif (v0 != null) {\n\t\treturn { version: current.version + 1, value: nextValue, v0 };\n\t}\n\treturn { version: current.version + 1, value: nextValue };\n}\n","/**\n * Reactive append-only log (roadmap §3.2) — versioned snapshots and derived tail / slice views.\n */\nimport { batch } from \"../core/batch.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { bumpVersion, snapshotEqualsVersion, type Versioned } from \"./reactive-base.js\";\n\nexport type ReactiveLogSnapshot<T> = Versioned<{ entries: readonly T[] }>;\n\nexport type ReactiveLogOptions = {\n\tname?: string;\n\tmaxSize?: number;\n};\n\nexport type ReactiveLogBundle<T> = {\n\t/** Emits {@link ReactiveLogSnapshot} on each append/clear (two-phase). */\n\treadonly entries: Node<ReactiveLogSnapshot<T>>;\n\tappend: (value: T) => void;\n\t/** Push all values, trim once, emit one snapshot. */\n\tappendMany: (values: readonly T[]) => void;\n\tclear: () => void;\n\t/** Remove the first `n` entries; emits snapshot. */\n\ttrimHead: (n: number) => void;\n\t/** Last `n` entries (or fewer); updates when the log changes. */\n\ttail: (n: number) => Node<readonly T[]>;\n};\n\nfunction emptySnapshot<T>(): ReactiveLogSnapshot<T> {\n\treturn { version: 0, value: { entries: [] } };\n}\n\n/**\n * Keep a derived node's dep wiring alive for `get()` without a user sink.\n * Returns the unsubscribe handle so callers can clean up.\n *\n * @remarks Derived views (`tail`, `logSlice`) install this so `get()` stays\n * wired without an external sink. The returned disposer is currently not\n * exposed on the bundle — subscriptions are released when the log bundle\n * becomes unreachable and the GC collects the closure.\n */\nfunction keepaliveDerived(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => {});\n}\n\n/**\n * Creates an append-only reactive log with versioned tuple snapshots.\n *\n * @param initial - Optional seed entries (copied).\n * @param options - Optional `name` for `describe()` / debugging.\n * @returns Bundle with `entries` (state node), `append`, `clear`, and {@link ReactiveLogBundle.tail}.\n *\n * @remarks\n * **Derived views:** {@link tail} and {@link logSlice} install an internal noop subscription so\n * `get()` stays wired without an external sink; creating very many disposable derived nodes can\n * retain subscriptions until the log bundle is unreachable.\n *\n * @example\n * ```ts\n * import { reactiveLog } from \"@graphrefly/graphrefly-ts\";\n *\n * const lg = reactiveLog<number>([1, 2], { name: \"audit\" });\n * lg.append(3);\n * lg.entries.subscribe((msgs) => console.log(msgs));\n * ```\n *\n * @category extra\n */\nexport function reactiveLog<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveLogOptions = {},\n): ReactiveLogBundle<T> {\n\tconst { name, maxSize } = options;\n\tif (maxSize !== undefined && maxSize < 1) {\n\t\tthrow new RangeError(\"maxSize must be >= 1\");\n\t}\n\tconst buf: T[] = initial ? [...initial] : [];\n\tif (maxSize !== undefined && buf.length > maxSize) {\n\t\tbuf.splice(0, buf.length - maxSize);\n\t}\n\tlet current: ReactiveLogSnapshot<T> =\n\t\tbuf.length > 0 ? { version: 1, value: { entries: [...buf] } } : emptySnapshot();\n\n\tconst entries = state<ReactiveLogSnapshot<T>>(current, {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: snapshotEqualsVersion,\n\t});\n\n\tfunction pushSnapshot(): void {\n\t\tconst ev = entries.v;\n\t\tcurrent = bumpVersion(\n\t\t\tcurrent,\n\t\t\t{ entries: [...buf] },\n\t\t\tev ? { id: ev.id, version: ev.version } : undefined,\n\t\t);\n\t\tbatch(() => {\n\t\t\tentries.down([[DIRTY]]);\n\t\t\tentries.down([[DATA, current]]);\n\t\t});\n\t}\n\n\tfunction trimBuf(): void {\n\t\tif (maxSize !== undefined && buf.length > maxSize) {\n\t\t\tbuf.splice(0, buf.length - maxSize);\n\t\t}\n\t}\n\n\tconst bundle: ReactiveLogBundle<T> = {\n\t\tentries,\n\n\t\tappend(value: T): void {\n\t\t\tbuf.push(value);\n\t\t\ttrimBuf();\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\tbuf.push(...values);\n\t\t\ttrimBuf();\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tclear(): void {\n\t\t\tif (buf.length === 0) return;\n\t\t\tbuf.length = 0;\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\ttrimHead(n: number): void {\n\t\t\tif (n < 0) {\n\t\t\t\tthrow new RangeError(\"n must be >= 0\");\n\t\t\t}\n\t\t\tif (n === 0) return;\n\t\t\tif (n >= buf.length) {\n\t\t\t\tif (buf.length === 0) return;\n\t\t\t\tbuf.length = 0;\n\t\t\t} else {\n\t\t\t\tbuf.splice(0, n);\n\t\t\t}\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\ttail(n: number): Node<readonly T[]> {\n\t\t\tif (n < 0) {\n\t\t\t\tthrow new RangeError(\"n must be >= 0\");\n\t\t\t}\n\t\t\tconst snap = entries.get() as ReactiveLogSnapshot<T>;\n\t\t\tconst e = snap.value.entries;\n\t\t\tconst init = n === 0 ? [] : e.slice(Math.max(0, e.length - n));\n\t\t\tconst out = derived(\n\t\t\t\t[entries],\n\t\t\t\t([s]) => {\n\t\t\t\t\tconst list = (s as ReactiveLogSnapshot<T>).value.entries;\n\t\t\t\t\treturn n === 0 ? [] : list.slice(Math.max(0, list.length - n));\n\t\t\t\t},\n\t\t\t\t{ initial: init, describeKind: \"derived\" },\n\t\t\t);\n\t\t\tkeepaliveDerived(out);\n\t\t\treturn out;\n\t\t},\n\t};\n\n\treturn bundle;\n}\n\n/**\n * Builds a derived node for `entries.slice(start, stop)` (same semantics as `Array.prototype.slice`; `stop` exclusive).\n *\n * @param log - Log from {@link reactiveLog}.\n * @param start - Start index (must be `>= 0`).\n * @param stop - End index (exclusive); omit to slice to the end.\n * @returns Derived node emitting the sliced readonly array.\n *\n * @example\n * ```ts\n * import { reactiveLog, logSlice } from \"@graphrefly/graphrefly-ts\";\n *\n * const lg = reactiveLog<number>([10, 20, 30, 40, 50]);\n * const slice$ = logSlice(lg, 1, 4); // reactive view of [20, 30, 40]\n * slice$.subscribe((msgs) => console.log(msgs));\n *\n * lg.append(60); // slice$ now reflects [20, 30, 40] (indices 1–3 of updated log)\n * ```\n *\n * @category extra\n */\nexport function logSlice<T>(\n\tlog: ReactiveLogBundle<T>,\n\tstart: number,\n\tstop?: number,\n): Node<readonly T[]> {\n\tif (start < 0) {\n\t\tthrow new RangeError(\"start must be >= 0\");\n\t}\n\tconst snap = log.entries.get() as ReactiveLogSnapshot<T>;\n\tconst e = snap.value.entries;\n\tconst init = stop === undefined ? e.slice(start) : e.slice(start, stop);\n\tconst out = derived(\n\t\t[log.entries],\n\t\t([s]) => {\n\t\t\tconst list = (s as ReactiveLogSnapshot<T>).value.entries;\n\t\t\treturn stop === undefined ? list.slice(start) : list.slice(start, stop);\n\t\t},\n\t\t{ initial: init, describeKind: \"derived\" },\n\t);\n\tkeepaliveDerived(out);\n\treturn out;\n}\n","/**\n * Graph container: registry, wiring, introspection (Phase 1).\n */\n\nexport {\n\tcreateDagCborCodec,\n\tcreateDagCborZstdCodec,\n\ttype DeltaCheckpoint,\n\ttype EvictedSubgraphInfo,\n\ttype EvictionPolicy,\n\ttype GraphCodec,\n\tJsonCodec,\n\ttype LazyGraphCodec,\n\tnegotiateCodec,\n\treplayWAL,\n\ttype WALEntry,\n} from \"./codec.js\";\nexport {\n\ttype AutoCheckpointAdapter,\n\ttype DescribeFilter,\n\tGRAPH_META_SEGMENT,\n\tGraph,\n\ttype GraphActorOptions,\n\ttype GraphAutoCheckpointHandle,\n\ttype GraphAutoCheckpointOptions,\n\ttype GraphCheckpointRecord,\n\ttype GraphDescribeOutput,\n\ttype GraphDiagramDirection,\n\ttype GraphDiagramOptions,\n\ttype GraphDiffChange,\n\ttype GraphDiffResult,\n\ttype GraphDumpOptions,\n\ttype GraphFactoryContext,\n\ttype GraphNodeFactory,\n\ttype GraphObserveAll,\n\ttype GraphObserveOne,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n\ttype GraphSpyHandle,\n\ttype GraphSpyOptions,\n\ttype GraphSpyTheme,\n\ttype GraphSpyThemeName,\n\ttype ObserveEvent,\n\ttype ObserveOptions,\n\ttype ObserveResult,\n\ttype ReachableDirection,\n\ttype ReachableOptions,\n\treachable,\n\ttype TraceEntry,\n} from \"./graph.js\";\n","/**\n * GraphCodec — pluggable serialization for graph snapshots (Phase 8.6).\n *\n * Design reference: `archive/docs/SESSION-serialization-memory-footprint.md`\n *\n * The codec interface decouples snapshot format from graph internals.\n * Default is JSON (current behavior). DAG-CBOR and compressed variants\n * ship as optional codecs. FlatBuffers/Arrow for advanced tiers.\n *\n * Tiered representation:\n * HOT — JS objects (live propagation, no codec involved)\n * WARM — DAG-CBOR in-memory buffer (lazy hydration, delta checkpoints)\n * COLD — Arrow/Parquet (bulk storage, ML pipelines, archival)\n * PEEK — FlatBuffers (zero-copy read from dormant graph)\n */\n\nimport type { GraphPersistSnapshot } from \"./graph.js\";\n\n// ---------------------------------------------------------------------------\n// Core codec interface\n// ---------------------------------------------------------------------------\n\n/**\n * Encode/decode graph snapshots to/from binary.\n *\n * Implementations must be deterministic: `encode(x)` always produces the\n * same bytes for the same input. This is critical for CID computation (V1)\n * and snapshot hash-comparison.\n */\nexport interface GraphCodec {\n\t/** MIME-like content type identifier (e.g. \"application/dag-cbor+zstd\"). */\n\treadonly contentType: string;\n\n\t/** Human-readable name for diagnostics. */\n\treadonly name: string;\n\n\t/** Encode a snapshot to binary. */\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array;\n\n\t/**\n\t * Decode binary back to a snapshot.\n\t *\n\t * For lazy codecs, this may return a proxy that decodes nodes on access\n\t * (see {@link LazyGraphCodec}).\n\t */\n\tdecode(buffer: Uint8Array): GraphPersistSnapshot;\n}\n\n/**\n * Extended codec that supports lazy (on-demand) node decoding.\n *\n * `decodeLazy` returns a snapshot where `nodes` is a Proxy — individual\n * nodes are decoded only when accessed. This enables near-zero cold-start\n * for large graphs (decode envelope + topology, skip node values until read).\n */\nexport interface LazyGraphCodec extends GraphCodec {\n\t/** Decode envelope and topology; defer node value decoding to access time. */\n\tdecodeLazy(buffer: Uint8Array): GraphPersistSnapshot;\n}\n\n// ---------------------------------------------------------------------------\n// Delta checkpoint types (requires V0 — Phase 6.0)\n// ---------------------------------------------------------------------------\n\n/**\n * A delta checkpoint: only the nodes that changed since last checkpoint.\n *\n * Append-only: each delta is identified by `seq` (monotonic). A full\n * snapshot is taken every `compactEvery` deltas for WAL compaction.\n */\nexport interface DeltaCheckpoint {\n\t/** Monotonic sequence number. */\n\tseq: number;\n\t/** Graph name. */\n\tname: string;\n\t/** Base snapshot seq this delta applies to (0 = initial full snapshot). */\n\tbaseSec: number;\n\t/** Only nodes with version > lastCheckpoint. Keyed by node name. */\n\tnodes: Record<\n\t\tstring,\n\t\t{\n\t\t\t/** V0 version at time of checkpoint. */\n\t\t\tversion: number;\n\t\t\t/** Serialized node value (codec-dependent). */\n\t\t\tvalue: unknown;\n\t\t\t/** Meta snapshot (only if materialized). */\n\t\t\tmeta?: Record<string, unknown>;\n\t\t}\n\t>;\n\t/** Nodes removed since last checkpoint. */\n\tremoved: string[];\n\t/** Edges added since last checkpoint. */\n\tedgesAdded: ReadonlyArray<{ from: string; to: string }>;\n\t/** Edges removed since last checkpoint. */\n\tedgesRemoved: ReadonlyArray<{ from: string; to: string }>;\n\t/** Timestamp (wall-clock ns) of this checkpoint. */\n\ttimestampNs: bigint;\n}\n\n/**\n * WAL entry: either a full snapshot or a delta.\n */\nexport type WALEntry =\n\t| { type: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { type: \"delta\"; delta: DeltaCheckpoint };\n\n// ---------------------------------------------------------------------------\n// Eviction policy (dormant subgraph management)\n// ---------------------------------------------------------------------------\n\n/**\n * Policy for evicting dormant subgraphs to reduce memory.\n *\n * When a subgraph hasn't propagated for `idleTimeoutMs`, it is serialized\n * using the graph's codec and JS objects are released. Re-hydrated on next\n * access (read, propagation, describe).\n */\nexport interface EvictionPolicy {\n\t/** Milliseconds of inactivity before eviction. */\n\tidleTimeoutMs: number;\n\t/** Codec to use for serializing evicted subgraphs (default: graph's codec). */\n\tcodec?: GraphCodec;\n}\n\n/** Metadata about an evicted subgraph, exposed via describe(). */\nexport interface EvictedSubgraphInfo {\n\t/** True if currently evicted (serialized, JS objects released). */\n\tevicted: true;\n\t/** Wall-clock ns of last propagation before eviction. */\n\tlastActiveNs: bigint;\n\t/** Size of serialized buffer in bytes. */\n\tserializedBytes: number;\n\t/** Codec used for serialization. */\n\tcodecName: string;\n}\n\n// ---------------------------------------------------------------------------\n// JSON codec (default — wraps current behavior)\n// ---------------------------------------------------------------------------\n\n/**\n * Default JSON codec. Wraps `JSON.stringify`/`JSON.parse` with deterministic\n * key ordering (matching current `snapshot()` behavior).\n */\nexport const JsonCodec: GraphCodec = {\n\tcontentType: \"application/json\",\n\tname: \"json\",\n\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array {\n\t\t// Deterministic: snapshot() already sorts keys.\n\t\tconst json = JSON.stringify(snapshot);\n\t\treturn new TextEncoder().encode(json);\n\t},\n\n\tdecode(buffer: Uint8Array): GraphPersistSnapshot {\n\t\tconst json = new TextDecoder().decode(buffer);\n\t\treturn JSON.parse(json) as GraphPersistSnapshot;\n\t},\n};\n\n// ---------------------------------------------------------------------------\n// DAG-CBOR codec (stub — requires @ipld/dag-cbor)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a DAG-CBOR codec.\n *\n * Requires `@ipld/dag-cbor` as a peer dependency. ~40-50% smaller than JSON,\n * deterministic encoding (required for V1 CID), CID links as native type.\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * const codec = createDagCborCodec(dagCbor);\n * const bytes = codec.encode(graph.snapshot());\n * ```\n */\nexport function createDagCborCodec(dagCbor: {\n\tencode: (value: unknown) => Uint8Array;\n\tdecode: (bytes: Uint8Array) => unknown;\n}): GraphCodec {\n\treturn {\n\t\tcontentType: \"application/dag-cbor\",\n\t\tname: \"dag-cbor\",\n\t\tencode: (snapshot) => dagCbor.encode(snapshot),\n\t\tdecode: (buffer) => dagCbor.decode(buffer) as GraphPersistSnapshot,\n\t};\n}\n\n/**\n * Create a DAG-CBOR + zstd codec. ~80-90% smaller than JSON.\n *\n * Requires `@ipld/dag-cbor` and a zstd implementation (e.g. `fzstd` for\n * browser, `node:zlib` for Node.js).\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * import { compressSync, decompressSync } from \"fzstd\";\n * const codec = createDagCborZstdCodec(dagCbor, { compressSync, decompressSync });\n * ```\n */\nexport function createDagCborZstdCodec(\n\tdagCbor: {\n\t\tencode: (value: unknown) => Uint8Array;\n\t\tdecode: (bytes: Uint8Array) => unknown;\n\t},\n\tzstd: {\n\t\tcompressSync: (data: Uint8Array) => Uint8Array;\n\t\tdecompressSync: (data: Uint8Array) => Uint8Array;\n\t},\n): GraphCodec {\n\treturn {\n\t\tcontentType: \"application/dag-cbor+zstd\",\n\t\tname: \"dag-cbor-zstd\",\n\t\tencode: (snapshot) => zstd.compressSync(dagCbor.encode(snapshot)),\n\t\tdecode: (buffer) => dagCbor.decode(zstd.decompressSync(buffer)) as GraphPersistSnapshot,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Codec negotiation (for peerGraph)\n// ---------------------------------------------------------------------------\n\n/**\n * Negotiate a common codec between two peers.\n *\n * Each peer advertises its supported codecs (ordered by preference).\n * Returns the first codec supported by both, or null if none.\n */\nexport function negotiateCodec(\n\tlocalPreference: readonly GraphCodec[],\n\tremoteContentTypes: readonly string[],\n): GraphCodec | null {\n\tconst remoteSet = new Set(remoteContentTypes);\n\tfor (const codec of localPreference) {\n\t\tif (remoteSet.has(codec.contentType)) return codec;\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// WAL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Reconstruct a snapshot from a WAL (full snapshot + sequence of deltas).\n *\n * Applies deltas in order on top of the base snapshot. Validates that\n * delta `baseSec` chains correctly.\n */\nexport function replayWAL(entries: readonly WALEntry[]): GraphPersistSnapshot {\n\tif (entries.length === 0) {\n\t\tthrow new Error(\"WAL is empty — need at least one full snapshot\");\n\t}\n\n\tconst first = entries[0]!;\n\tif (first.type !== \"full\") {\n\t\tthrow new Error(\"WAL must start with a full snapshot\");\n\t}\n\n\t// Deep clone the base snapshot so we can mutate it.\n\tconst result: GraphPersistSnapshot = JSON.parse(JSON.stringify(first.snapshot));\n\n\tfor (let i = 1; i < entries.length; i++) {\n\t\tconst entry = entries[i]!;\n\t\tif (entry.type === \"full\") {\n\t\t\t// A compaction point — replace the entire result.\n\t\t\tObject.assign(result, JSON.parse(JSON.stringify(entry.snapshot)));\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst delta = entry.delta;\n\n\t\t// Apply node changes.\n\t\tfor (const [name, patch] of Object.entries(delta.nodes)) {\n\t\t\tif (result.nodes[name]) {\n\t\t\t\tresult.nodes[name]!.value = patch.value;\n\t\t\t\tif (patch.meta) {\n\t\t\t\t\tresult.nodes[name]!.meta = patch.meta;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Apply removals.\n\t\tfor (const name of delta.removed) {\n\t\t\tdelete result.nodes[name];\n\t\t}\n\n\t\t// Apply edge changes.\n\t\tconst edges = [...result.edges];\n\t\tfor (const edge of delta.edgesRemoved) {\n\t\t\tconst idx = edges.findIndex((e) => e.from === edge.from && e.to === edge.to);\n\t\t\tif (idx !== -1) edges.splice(idx, 1);\n\t\t}\n\t\tfor (const edge of delta.edgesAdded) {\n\t\t\tedges.push(edge);\n\t\t}\n\t\t(result as unknown as { edges: typeof edges }).edges = edges;\n\t}\n\n\treturn result;\n}\n","// ---------------------------------------------------------------------------\n// React bindings — useStore / useSubscribe\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into React via useSyncExternalStore.\n// Works with any Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useStore, useSubscribe } from '@graphrefly/graphrefly-ts/compat/react';\n// // Optional peer install (only for this adapter): pnpm add react react-dom\n// const value = useSubscribe(myNode); // T | undefined (read-only)\n// const [count, setCount] = useStore(counter); // [T | undefined, setter]\n// ---------------------------------------------------------------------------\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { DATA, DIRTY, type Messages, messageTier } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/**\n * Subscribe to a read-only `Node<T>` as a React value. Re-renders on node value settlement.\n * Subscription lifecycle is tied to React mount/unmount (not node terminal messages).\n *\n * @param node - Any `Node<T>`.\n * @returns `T | undefined` — the current node value, kept in sync via `useSyncExternalStore`.\n */\nexport function useSubscribe<T>(node: Node<T>): T | undefined {\n\treturn useSyncExternalStore(\n\t\t(onStoreChange) => {\n\t\t\tlet disposed = false;\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tdisposed = true;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t},\n\t\t() => node.get(),\n\t\t() => node.get(), // Server snapshot\n\t);\n}\n\n/**\n * Bind a writable `Node<T>` as a React `[value, setter]` tuple.\n * Setting the value always pushes `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to React mount/unmount (not node terminal messages).\n *\n * @param node - A `Node<T>` (e.g. state node).\n * @returns `[T | undefined, (value: T) => void]` — current value and setter function.\n */\nexport function useStore<T>(node: Node<T>): [T | undefined, (value: T) => void] {\n\tconst value = useSubscribe(node);\n\tconst setter = useCallback(\n\t\t(v: T) => {\n\t\t\tnode.down([[DIRTY], [DATA, v]]);\n\t\t},\n\t\t[node],\n\t);\n\treturn [value, setter];\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records.\n * Re-subscribes all per-key fields whenever `keysNode` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 2`) to avoid DIRTY-phase churn.\n * Guaranteed to clean up strictly with React hook lifecycle, utilizing no global mappings.\n *\n * @param keysNode - Node of current keys (e.g. node IDs)\n * @param factory - Function returning `{ [field]: Node<V> }` for each key.\n * @returns `Record<K, R>` — snapshot of resolved values for all keys.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): Record<K, R> {\n\tconst factoryRef = useRef(factory);\n\tfactoryRef.current = factory;\n\n\tconst store = useMemo(() => {\n\t\tconst computeSnap = () => {\n\t\t\tconst snap = {} as Record<K, R>;\n\t\t\tconst keys = keysNode.get() ?? [];\n\t\t\tfor (const key of keys) {\n\t\t\t\tconst nodes = factoryRef.current(key);\n\t\t\t\tconst values = {} as R;\n\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\tvalues[field] = nodes[field].get() as R[keyof R];\n\t\t\t\t}\n\t\t\t\tsnap[key] = values;\n\t\t\t}\n\t\t\treturn snap;\n\t\t};\n\n\t\tlet currentSnapshot = computeSnap();\n\n\t\treturn {\n\t\t\tsubscribe: (onStoreChange: () => void) => {\n\t\t\t\tlet disposed = false;\n\t\t\t\tlet entrySubs: Array<() => void> = [];\n\n\t\t\t\tconst cleanupEntries = () => {\n\t\t\t\t\tfor (const unsub of entrySubs) unsub();\n\t\t\t\t\tentrySubs = [];\n\t\t\t\t};\n\n\t\t\t\tconst sync = (nextKeys: K[]) => {\n\t\t\t\t\tcleanupEntries();\n\t\t\t\t\tfor (const key of nextKeys) {\n\t\t\t\t\t\tconst nodes = factoryRef.current(key);\n\t\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\t\t\t\tcurrentSnapshot = computeSnap();\n\t\t\t\t\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tentrySubs.push(unsub);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcurrentSnapshot = computeSnap();\n\t\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t\t};\n\n\t\t\t\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\t\t\t\tconst hasSettled = msgs.some((m) => messageTier(m[0]) >= 2);\n\t\t\t\t\tif (!disposed && hasSettled) sync(keysNode.get() ?? []);\n\t\t\t\t});\n\t\t\t\tsync(keysNode.get() ?? []);\n\n\t\t\t\treturn () => {\n\t\t\t\t\tdisposed = true;\n\t\t\t\t\tkeysUnsub();\n\t\t\t\t\tcleanupEntries();\n\t\t\t\t};\n\t\t\t},\n\t\t\tgetSnapshot: () => currentSnapshot,\n\t\t};\n\t}, [keysNode]);\n\n\treturn useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n","import { batch } from \"../../core/batch.js\";\nimport { type DynGet, dynamicNode } from \"../../core/dynamic-node.js\";\nimport { COMPLETE, DATA, DIRTY, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { state } from \"../../core/sugar.js\";\n\n/**\n * Options for creating signals.\n *\n * @category compat\n */\nexport interface SignalOptions {\n\t/** Optional identifier for the underlying node. */\n\tname?: string;\n\t/** Custom equality function for change detection. */\n\tequals?: (a: any, b: any) => boolean;\n}\n\n/**\n * Common interface for all reactive signals.\n *\n * @category compat\n */\nexport interface AnySignal<T> {\n\t/** Returns the current value of the signal. */\n\tget(): T;\n\t/** @internal The underlying GraphReFly node. */\n\t_node: Node<T>;\n}\n\n/**\n * Global stack of active tracking contexts.\n * Since computation evaluation is fully synchronous, we push the tracking `get`\n * function before execution and pop it after. This prevents memory leaks without\n * needing WeakRefs, as the stack is always empty when idle.\n */\nconst trackingStack: DynGet[] = [];\n\n/**\n * Helper to pull a disconnected node, forcing a synchronous resolution\n * cycle so that `get()` returns a fresh value even if the signal is unmounted.\n */\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined = n.get();\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t}\n\t});\n\tunsub();\n\treturn val as T;\n}\n\n/**\n * TC39 `Signal.State` — a writable signal backed by a GraphReFly `state` node.\n * Automatically registers itself as a dependency if read inside a `Computed`.\n *\n * @example\n * ```ts\n * const count = new Signal.State(0);\n * count.get(); // 0\n * count.set(1);\n * count.get(); // 1\n * ```\n */\nclass SignalState<T> implements AnySignal<T> {\n\t/** @internal */\n\t_node: Node<T>;\n\tprivate readonly _equals: (a: T, b: T) => boolean;\n\n\tconstructor(initial: T, opts?: SignalOptions) {\n\t\tthis._equals = (opts?.equals ?? Object.is) as (a: T, b: T) => boolean;\n\t\tthis._node = state<T>(initial, {\n\t\t\t...opts,\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t});\n\t}\n\n\tget(): T {\n\t\t// If we are evaluating inside a computed node, track this read!\n\t\tconst tracker = trackingStack[trackingStack.length - 1];\n\t\tif (tracker) {\n\t\t\tif (this._node.status === \"disconnected\") {\n\t\t\t\tpull(this._node);\n\t\t\t}\n\t\t\treturn tracker(this._node) as T;\n\t\t}\n\n\t\tif (this._node.status === \"disconnected\") {\n\t\t\treturn pull(this._node);\n\t\t}\n\t\treturn this._node.get() as T;\n\t}\n\n\tset(value: T): void {\n\t\tif (this._equals(this.get(), value)) return;\n\t\tbatch(() => {\n\t\t\tthis._node.down([[DIRTY], [DATA, value]]);\n\t\t});\n\t}\n}\n\n/**\n * TC39 `Signal.Computed` — a read-only signal backed by `dynamicNode`.\n * Automatically tracks dependencies when `get()` is called on other signals\n * during its computation.\n *\n * @example\n * ```ts\n * const count = new Signal.State(0);\n * const doubled = new Signal.Computed(() => count.get() * 2);\n * ```\n */\nclass SignalComputed<T> implements AnySignal<T> {\n\t/** @internal */\n\t_node: Node<T>;\n\n\tconstructor(computation: () => T, opts?: SignalOptions) {\n\t\tthis._node = dynamicNode<T>(\n\t\t\t(get) => {\n\t\t\t\ttrackingStack.push(get);\n\t\t\t\ttry {\n\t\t\t\t\treturn computation();\n\t\t\t\t} finally {\n\t\t\t\t\ttrackingStack.pop();\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\t...opts,\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tresubscribable: true,\n\t\t\t\tresetOnTeardown: true,\n\t\t\t},\n\t\t);\n\t}\n\n\tget(): T {\n\t\t// Computed nodes can themselves be dependencies of other Computed nodes.\n\t\tconst tracker = trackingStack[trackingStack.length - 1];\n\t\tif (tracker) {\n\t\t\tif (this._node.status === \"disconnected\") {\n\t\t\t\tpull(this._node);\n\t\t\t}\n\t\t\treturn tracker(this._node) as T;\n\t\t}\n\n\t\tif (this._node.status === \"disconnected\") {\n\t\t\treturn pull(this._node);\n\t\t}\n\t\treturn this._node.get() as T;\n\t}\n}\n\n/**\n * TC39 Signals-compatible namespace. Wraps GraphReFly primitives.\n * Provides auto-tracking conforming to the TS39 signals proposal.\n *\n * @category compat\n */\nexport const Signal = {\n\tState: SignalState,\n\tComputed: SignalComputed,\n\n\t/**\n\t * Subscribes to changes on a signal.\n\t * Returns an unsubscribe callback.\n\t *\n\t * @example\n\t * ```ts\n\t * const count = new Signal.State(0);\n\t * const unsub = Signal.sub(count, v => console.log(v));\n\t * ```\n\t */\n\tsub: <T>(\n\t\tsignal: AnySignal<T>,\n\t\tcallback:\n\t\t\t| ((value: T) => void)\n\t\t\t| {\n\t\t\t\t\tdata?: (value: T) => void;\n\t\t\t\t\terror?: (err: unknown) => void;\n\t\t\t\t\tcomplete?: () => void;\n\t\t\t },\n\t): (() => void) => {\n\t\tconst handlers =\n\t\t\ttypeof callback === \"function\"\n\t\t\t\t? { data: callback as (value: T) => void, error: undefined, complete: undefined }\n\t\t\t\t: callback;\n\t\treturn signal._node.subscribe((msgs) => {\n\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\tif (t === DATA) handlers.data?.(v as T);\n\t\t\t\tif (t === ERROR) handlers.error?.(v);\n\t\t\t\tif (t === COMPLETE) handlers.complete?.();\n\t\t\t}\n\t\t});\n\t},\n} as const;\n\nexport type { SignalComputed, SignalState };\n","// ---------------------------------------------------------------------------\n// Solid bindings — useSubscribe / useStore\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Solid reactivity via createSignal.\n// Works with any Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useSubscribe, useStore } from '@graphrefly/graphrefly-ts/compat/solid';\n// // Optional peer install (only for this adapter): pnpm add solid-js\n// const status = useSubscribe(wsStatusNode); // Accessor<string | undefined>\n// const [count, setCount] = useStore(countNode); // [Accessor<number | undefined>, Setter]\n// ---------------------------------------------------------------------------\n\nimport { createSignal, getOwner, onCleanup } from \"solid-js\";\nimport { DATA, DIRTY, type Messages, messageTier } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/** Solid accessor function — returns current value when called. */\nexport type Accessor<T> = () => T;\n\n/**\n * Subscribe to a `Node<T>` as a Solid signal. Auto-cleans up with the owning scope.\n * Subscription lifecycle is tied to Solid scope cleanup (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): Accessor<T | undefined> {\n\tconst [value, setValue] = createSignal(node.get(), { equals: false });\n\n\tconst unsub = node.subscribe(() => {\n\t\tsetValue(() => node.get());\n\t});\n\n\tif (getOwner()) {\n\t\tonCleanup(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribe called outside a Solid reactive owner — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn value;\n}\n\n/**\n * Bind a writable `Node<T>` as a Solid resource tuple `[accessor, setter]`.\n * Setter always forwards `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Solid scope cleanup (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): [Accessor<T | undefined>, (v: T) => void] {\n\tconst value = useSubscribe(node);\n\tconst setter = (v: T) => {\n\t\tnode.down([[DIRTY], [DATA, v]]);\n\t};\n\treturn [value, setter];\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records as a Solid accessor.\n * Re-subscribes all per-key fields whenever `keys` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 2`) to avoid DIRTY-phase churn.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): Accessor<Record<K, R>> {\n\tconst [value, setValue] = createSignal({} as Record<K, R>, { equals: false });\n\tlet entrySubs: Array<() => void> = [];\n\n\tconst cleanupEntries = () => {\n\t\tfor (const unsub of entrySubs) unsub();\n\t\tentrySubs = [];\n\t};\n\n\tconst buildSnapshot = (): Record<K, R> => {\n\t\tconst snap = {} as Record<K, R>;\n\t\tfor (const key of keysNode.get() ?? []) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst values = {} as R;\n\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\tvalues[field] = nodes[field].get() as R[keyof R];\n\t\t\t}\n\t\t\tsnap[key] = values;\n\t\t}\n\t\treturn snap;\n\t};\n\n\tconst sync = (nextKeys: K[]) => {\n\t\tcleanupEntries();\n\t\tfor (const key of nextKeys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\tsetValue(() => buildSnapshot());\n\t\t\t\t});\n\t\t\t\tentrySubs.push(unsub);\n\t\t\t}\n\t\t}\n\t\tsetValue(() => buildSnapshot());\n\t};\n\n\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\tif (msgs.some((m) => messageTier(m[0]) >= 2)) {\n\t\t\tsync(keysNode.get() ?? []);\n\t\t}\n\t});\n\tsync(keysNode.get() ?? []);\n\n\tif (getOwner()) {\n\t\tonCleanup(() => {\n\t\t\tkeysUnsub();\n\t\t\tcleanupEntries();\n\t\t});\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn value;\n}\n","// ---------------------------------------------------------------------------\n// Svelte bindings — useSubscribe / useStore\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Svelte's store contract. Works with any\n// Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useSubscribe, useStore } from '@graphrefly/graphrefly-ts/compat/svelte';\n// // Optional peer install (only for this adapter): pnpm add svelte\n// const status = useSubscribe(wsStatusNode); // Svelte readable store\n// const count = useStore(countNode); // Svelte writable store\n// // In template: $status, $count\n// // $count = 42\n// ---------------------------------------------------------------------------\n\nimport { DATA, DIRTY, type Messages, messageTier } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/** Svelte store contract — implements the minimal `subscribe` method. */\nexport interface SvelteReadable<T> {\n\tsubscribe(run: (value: T) => void): () => void;\n}\n\n/** Svelte writable store contract. */\nexport interface SvelteWritable<T> extends SvelteReadable<T> {\n\tset(value: T): void;\n\tupdate(updater: (value: T) => T): void;\n}\n\n/**\n * Subscribe to a `Node<T>` as a Svelte readable store (implements Svelte store contract).\n * Subscription lifecycle is tied to Svelte store unsubscription (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): SvelteReadable<T | undefined> {\n\treturn {\n\t\tsubscribe(run: (value: T | undefined) => void): () => void {\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\trun(node.get());\n\t\t\t});\n\t\t\trun(node.get());\n\t\t\treturn unsub;\n\t\t},\n\t};\n}\n\n/**\n * Bind a writable `Node<T>` as a Svelte writable store.\n * Reads and writes adapt seamlessly.\n * Setter/update always forward `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Svelte store unsubscription (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): SvelteWritable<T | undefined> {\n\treturn {\n\t\tsubscribe(run: (value: T | undefined) => void): () => void {\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\trun(node.get());\n\t\t\t});\n\t\t\trun(node.get());\n\t\t\treturn unsub;\n\t\t},\n\t\tset(value: T | undefined) {\n\t\t\tnode.down([[DIRTY], [DATA, value]]);\n\t\t},\n\t\tupdate(updater: (value: T | undefined) => T | undefined) {\n\t\t\tconst next = updater(node.get());\n\t\t\tnode.down([[DIRTY], [DATA, next]]);\n\t\t},\n\t};\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic keyed record of nodes as a Svelte readable store.\n * Re-subscribes all per-key fields whenever `keysNode` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 2`) to avoid DIRTY-phase churn.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): SvelteReadable<Record<K, R>> {\n\treturn {\n\t\tsubscribe(run: (value: Record<K, R>) => void): () => void {\n\t\t\tlet entrySubs: Array<() => void> = [];\n\n\t\t\tconst cleanupEntries = () => {\n\t\t\t\tfor (const unsub of entrySubs) unsub();\n\t\t\t\tentrySubs = [];\n\t\t\t};\n\n\t\t\tconst buildSnapshot = (): Record<K, R> => {\n\t\t\t\tconst snap = {} as Record<K, R>;\n\t\t\t\tfor (const key of keysNode.get() ?? []) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tconst values = {} as R;\n\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\tvalues[field] = nodes[field].get() as R[keyof R];\n\t\t\t\t\t}\n\t\t\t\t\tsnap[key] = values;\n\t\t\t\t}\n\t\t\t\treturn snap;\n\t\t\t};\n\n\t\t\tconst sync = (nextKeys: K[]) => {\n\t\t\t\tcleanupEntries();\n\t\t\t\tfor (const key of nextKeys) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\t\t\trun(buildSnapshot());\n\t\t\t\t\t\t});\n\t\t\t\t\t\tentrySubs.push(unsub);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trun(buildSnapshot());\n\t\t\t};\n\n\t\t\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\t\t\tif (msgs.some((m) => messageTier(m[0]) >= 2)) {\n\t\t\t\t\tsync(keysNode.get() ?? []);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsync(keysNode.get() ?? []);\n\n\t\t\treturn () => {\n\t\t\t\tkeysUnsub();\n\t\t\t\tcleanupEntries();\n\t\t\t};\n\t\t},\n\t};\n}\n","// ---------------------------------------------------------------------------\n// Vue bindings — useStore / useSubscribe\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Vue reactivity. Works with any\n// Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useStore, useSubscribe } from '@graphrefly/graphrefly-ts/compat/vue';\n// // Optional peer install (only for this adapter): pnpm add vue\n// const count = useStore(counterNode); // Ref<number | undefined> (read + write)\n// const status = useSubscribe(wsStatusNode); // Readonly<Ref<string | undefined>>\n// ---------------------------------------------------------------------------\n\nimport {\n\tcomputed,\n\tgetCurrentScope,\n\tisRef,\n\tonScopeDispose,\n\ttype Ref,\n\treadonly,\n\tshallowRef,\n\ttype WatchSource,\n\twatch,\n} from \"vue\";\nimport { DATA, DIRTY } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/**\n * Subscribe to a read-only `Node<T>` as a Vue `Ref<T>`. Auto-unsubscribes on scope disposal.\n * Subscription lifecycle is tied to Vue scope disposal (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): Readonly<Ref<T | undefined>> {\n\tconst ref = shallowRef(node.get()) as Ref<T | undefined>;\n\n\tconst unsub = node.subscribe(() => {\n\t\tref.value = node.get();\n\t});\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribe called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn readonly(ref) as Readonly<Ref<T | undefined>>;\n}\n\n/**\n * Bind a writable `Node<T>` as a Vue `Ref<T>`. Reads and writes are bidirectional.\n * Value sets always dispatch `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Vue scope disposal (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): Ref<T | undefined> {\n\tconst inner = shallowRef(node.get()) as Ref<T | undefined>;\n\n\tconst unsub = node.subscribe(() => {\n\t\tinner.value = node.get();\n\t});\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useStore called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn computed({\n\t\tget: () => inner.value,\n\t\tset: (v: T | undefined) => {\n\t\t\tnode.down([[DIRTY], [DATA, v]]);\n\t\t},\n\t});\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord` factory. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records. When keys change,\n * old subscriptions are torn down and new ones created automatically.\n * Must be called during Vue `setup()`.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeys: WatchSource<K[] | undefined>,\n\tfactory: NodeFactory<K, R>,\n): Readonly<Ref<Record<K, R>>> {\n\tconst result = shallowRef<Record<K, R>>({} as Record<K, R>);\n\n\t// Track active subscriptions per key (strictly enclosed memory mapping)\n\tconst activeSubs = new Map<K, { subs: Array<() => void>; values: R }>();\n\tlet disposed = false;\n\n\tlet batchPending = false;\n\tfunction scheduleBatch() {\n\t\tif (batchPending) return;\n\t\tbatchPending = true;\n\t\tqueueMicrotask(() => {\n\t\t\tif (disposed) return;\n\t\t\tbatchPending = false;\n\t\t\tconst snap = {} as Record<K, R>;\n\t\t\tfor (const [key, entry] of activeSubs) {\n\t\t\t\tsnap[key] = { ...entry.values };\n\t\t\t}\n\t\t\tresult.value = snap;\n\t\t});\n\t}\n\n\tfunction sync(newKeys: K[]) {\n\t\tfor (const entry of activeSubs.values()) {\n\t\t\tfor (const unsub of entry.subs) unsub();\n\t\t}\n\t\tactiveSubs.clear();\n\n\t\tfor (const key of newKeys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst fields = Object.keys(nodes) as (keyof R)[];\n\t\t\tconst values = {} as R;\n\t\t\tconst subs: Array<() => void> = [];\n\n\t\t\tfor (const field of fields) {\n\t\t\t\tconst node = nodes[field];\n\t\t\t\tvalues[field] = node.get() as R[keyof R];\n\t\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\t\tvalues[field] = node.get() as R[keyof R];\n\t\t\t\t\tscheduleBatch();\n\t\t\t\t});\n\t\t\t\tsubs.push(unsub);\n\t\t\t}\n\n\t\t\tactiveSubs.set(key, { subs, values });\n\t\t}\n\n\t\tconst snap = {} as Record<K, R>;\n\t\tfor (const [key, entry] of activeSubs) {\n\t\t\tsnap[key] = { ...entry.values };\n\t\t}\n\t\tresult.value = snap;\n\t}\n\n\tconst readKeys = (): K[] => {\n\t\tconst current = typeof keys === \"function\" ? keys() : isRef(keys) ? keys.value : keys;\n\t\treturn [...(current ?? [])];\n\t};\n\n\twatch(readKeys, (newKeys) => sync(newKeys ?? []), { immediate: true });\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => {\n\t\t\tdisposed = true;\n\t\t\tfor (const entry of activeSubs.values()) {\n\t\t\t\tfor (const unsub of entry.subs) unsub();\n\t\t\t}\n\t\t\tactiveSubs.clear();\n\t\t});\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribeRecord called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn readonly(result) as Readonly<Ref<Record<K, R>>>;\n}\n","import { DATA } from \"../../core/messages.js\";\nimport { state as stateNode } from \"../../core/sugar.js\";\nimport { Graph } from \"../../graph/graph.js\";\n\n/** Zustand-compatible Store API. */\nexport interface StoreApi<T> {\n\tgetState: () => T;\n\tsetState: (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean) => void;\n\tgetInitialState: () => T;\n\tsubscribe: (listener: (state: T, prevState: T) => void) => () => void;\n\tdestroy: () => void;\n}\n\n/** Function type for initializing the store. */\nexport type StateCreator<T> = (\n\tset: StoreApi<T>[\"setState\"],\n\tget: StoreApi<T>[\"getState\"],\n\tapi: StoreApi<T>,\n) => T;\n\n/**\n * Creates a Zustand-compatible store backed by a GraphReFly state node.\n * returns an object that is both a Graph and a StoreApi.\n *\n * @example\n * ```ts\n * const store = create((set) => ({\n * count: 0,\n * inc: () => set((s) => ({ count: s.count + 1 }))\n * }));\n * store.getState().inc();\n * ```\n *\n * @category compat\n */\nexport function create<T extends object>(initializer: StateCreator<T>): Graph & StoreApi<T> {\n\tconst g = new Graph(\"zustand\");\n\tconst s = stateNode<T>(undefined as unknown as T, { name: \"state\" });\n\tg.add(\"state\", s);\n\n\tconst getState = () => s.get() as T;\n\tconst setState = (partial: any, replace?: boolean): void => {\n\t\tconst prev = getState();\n\t\tconst next = typeof partial === \"function\" ? partial(prev) : partial;\n\t\tconst nextState = replace ? next : { ...prev, ...next };\n\t\ts.down([[DATA, nextState]]);\n\t};\n\n\tconst api: StoreApi<T> = {\n\t\tgetState,\n\t\tsetState,\n\t\tgetInitialState: () => initialValue,\n\t\tsubscribe: (listener) => {\n\t\t\tlet prev = getState();\n\t\t\treturn s.subscribe((msgs) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tlistener(v as T, prev);\n\t\t\t\t\t\tprev = v as T;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tdestroy: g.destroy.bind(g),\n\t};\n\n\tconst initialValue = initializer(setState, getState, api);\n\ts.down([[DATA, initialValue]]);\n\n\treturn Object.assign(g, api);\n}\n","/**\n * Extra layer: operators, sources, sinks (Phase 2+).\n */\n\nexport * from \"./adapters.js\";\nexport * from \"./backoff.js\";\nexport * from \"./backpressure.js\";\nexport * from \"./checkpoint.js\";\nexport * from \"./composite.js\";\nexport * from \"./cron.js\";\nexport * from \"./observable.js\";\nexport * from \"./operators.js\";\nexport * from \"./pubsub.js\";\nexport * from \"./reactive-index.js\";\nexport * from \"./reactive-list.js\";\nexport * from \"./reactive-log.js\";\nexport * from \"./reactive-map.js\";\nexport * from \"./resilience.js\";\nexport * from \"./sources.js\";\nexport * from \"./worker/index.js\";\n","/**\n * Backoff strategies for {@link retry} (roadmap §3.1). Delays are in **nanoseconds**.\n *\n * Convention: all graphrefly-ts timestamps and durations use nanoseconds (`_ns` suffix).\n * 1 second = 1_000_000_000 ns, 1 ms = 1_000_000 ns.\n */\n\nexport const NS_PER_MS = 1_000_000;\nexport const NS_PER_SEC = 1_000_000_000;\n\nexport type JitterMode = \"none\" | \"full\" | \"equal\";\n\nexport type BackoffPreset =\n\t| \"constant\"\n\t| \"linear\"\n\t| \"exponential\"\n\t| \"fibonacci\"\n\t| \"decorrelatedJitter\";\n\n/** `(attempt, error?, previousDelayNs?) => delayNs | null` — `null` means zero delay. */\nexport type BackoffStrategy = (\n\tattempt: number,\n\terror?: unknown,\n\tprevDelayNs?: number | null,\n) => number | null;\n\nfunction clampNonNegative(value: number): number {\n\treturn value < 0 ? 0 : value;\n}\n\nfunction applyJitter(delay: number, jitter: JitterMode): number {\n\tif (jitter === \"none\") return delay;\n\tif (jitter === \"full\") return Math.random() * delay;\n\treturn delay / 2 + Math.random() * (delay / 2);\n}\n\nfunction randomBetween(min: number, max: number): number {\n\treturn min + Math.random() * (max - min);\n}\n\n/**\n * Builds a strategy that always returns the same delay in nanoseconds.\n *\n * @param delayNs - Non-negative delay in nanoseconds; values below zero are clamped to zero.\n * @returns `BackoffStrategy` for use with {@link retry} or custom timers.\n *\n * @example\n * ```ts\n * import { constant, retry, NS_PER_SEC } from \"@graphrefly/graphrefly-ts\";\n *\n * const out = retry(source, { count: 3, backoff: constant(0.25 * NS_PER_SEC) });\n * ```\n *\n * @category extra\n */\nexport function constant(delayNs: number): BackoffStrategy {\n\tconst safe = clampNonNegative(delayNs);\n\treturn () => safe;\n}\n\n/**\n * Builds linear backoff: `baseNs + stepNs * attempt` (`stepNs` defaults to `baseNs`).\n *\n * @param baseNs - Base delay in nanoseconds (clamped non-negative).\n * @param stepNs - Added per retry attempt in nanoseconds (clamped non-negative).\n * @returns `BackoffStrategy` for {@link retry}.\n *\n * @example\n * ```ts\n * import { linear, retry, NS_PER_SEC } from \"@graphrefly/graphrefly-ts\";\n *\n * // Attempt 0 → 1 s, attempt 1 → 2 s, attempt 2 → 3 s …\n * const out = retry(source, { count: 4, backoff: linear(NS_PER_SEC) });\n * ```\n *\n * @category extra\n */\nexport function linear(baseNs: number, stepNs?: number): BackoffStrategy {\n\tconst safeBase = clampNonNegative(baseNs);\n\tconst safeStep = stepNs === undefined ? safeBase : clampNonNegative(stepNs);\n\treturn (attempt: number) => safeBase + safeStep * Math.max(0, attempt);\n}\n\nexport type ExponentialBackoffOptions = {\n\tbaseNs?: number;\n\tfactor?: number;\n\tmaxDelayNs?: number;\n\tjitter?: JitterMode;\n};\n\n/**\n * Builds exponential backoff in nanoseconds, capped by `maxDelayNs`, with optional jitter.\n *\n * @param options - Base, factor, cap, and jitter mode.\n * @returns `BackoffStrategy` for {@link retry}.\n *\n * @remarks\n * **Jitter:** `\"full\"` spreads delay across `[0, delay]`; `\"equal\"` uses `[delay/2, delay]`.\n *\n * @example\n * ```ts\n * import { exponential, retry, NS_PER_SEC } from \"@graphrefly/graphrefly-ts\";\n *\n * // 100 ms → 200 ms → 400 ms … capped at 30 s, with full jitter\n * const out = retry(source, {\n * count: 5,\n * backoff: exponential({ baseNs: 100 * NS_PER_SEC / 1000, jitter: \"full\" }),\n * });\n * ```\n *\n * @category extra\n */\nexport function exponential(options?: ExponentialBackoffOptions): BackoffStrategy {\n\tconst baseNs = clampNonNegative(options?.baseNs ?? 100 * NS_PER_MS);\n\tconst factor = options?.factor !== undefined && options.factor < 1 ? 1 : (options?.factor ?? 2);\n\tconst maxDelayNs = clampNonNegative(options?.maxDelayNs ?? 30 * NS_PER_SEC);\n\tconst jitter = options?.jitter ?? \"none\";\n\n\treturn (attempt: number) => {\n\t\tlet delay: number;\n\t\tif (baseNs === 0) {\n\t\t\tdelay = 0;\n\t\t} else if (factor === 1) {\n\t\t\tdelay = baseNs;\n\t\t} else {\n\t\t\tconst capRatio = maxDelayNs / baseNs;\n\t\t\tlet growth = 1;\n\t\t\tfor (let i = 0; i < Math.max(0, attempt); i++) {\n\t\t\t\tif (growth >= capRatio) {\n\t\t\t\t\tgrowth = capRatio;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tgrowth *= factor;\n\t\t\t}\n\t\t\tdelay = baseNs * growth;\n\t\t\tif (delay > maxDelayNs) delay = maxDelayNs;\n\t\t}\n\t\treturn applyJitter(delay, jitter);\n\t};\n}\n\n/**\n * Builds Fibonacci-scaled delays: `1, 2, 3, 5, … × baseNs`, capped at `maxDelayNs`.\n *\n * @param baseNs - Multiplier applied to the Fibonacci unit (default `100ms` in nanoseconds).\n * @param maxDelayNs - Upper bound in nanoseconds (default `30s`).\n * @returns `BackoffStrategy` for {@link retry}.\n *\n * @example\n * ```ts\n * import { fibonacci, retry, NS_PER_MS } from \"@graphrefly/graphrefly-ts\";\n *\n * // Delays: 100 ms, 200 ms, 300 ms, 500 ms, 800 ms … (× 100 ms base)\n * const out = retry(source, { count: 5, backoff: fibonacci(100 * NS_PER_MS) });\n * ```\n *\n * @category extra\n */\nexport function fibonacci(baseNs = 100 * NS_PER_MS, maxDelayNs = 30 * NS_PER_SEC): BackoffStrategy {\n\tconst safeBase = clampNonNegative(baseNs);\n\tconst safeMax = clampNonNegative(maxDelayNs);\n\n\tfunction fibUnit(attempt: number): number {\n\t\tif (attempt <= 0) return 1;\n\t\tlet prev = 1;\n\t\tlet cur = 2;\n\t\tfor (let i = 1; i < attempt; i++) {\n\t\t\tconst next = prev + cur;\n\t\t\tprev = cur;\n\t\t\tcur = next;\n\t\t}\n\t\treturn cur;\n\t}\n\n\treturn (attempt: number) => {\n\t\tconst raw = fibUnit(attempt) * safeBase;\n\t\treturn raw <= safeMax ? raw : safeMax;\n\t};\n}\n\n/**\n * Decorrelated jitter (AWS-recommended): `random(baseNs, min(maxNs, lastDelay * 3))`.\n *\n * Stateless — uses `prevDelayNs` (passed by the consumer) instead of closure state.\n * Safe to share across concurrent retry sequences.\n *\n * @param baseNs - Floor of the random range (default `100ms` in nanoseconds).\n * @param maxNs - Ceiling cap (default `30s` in nanoseconds).\n * @returns `BackoffStrategy` for {@link retry}.\n *\n * @example\n * ```ts\n * import { decorrelatedJitter, retry, NS_PER_MS, NS_PER_SEC } from \"@graphrefly/graphrefly-ts\";\n *\n * const out = retry(source, {\n * count: 6,\n * backoff: decorrelatedJitter(100 * NS_PER_MS, 10 * NS_PER_SEC),\n * });\n * ```\n *\n * @category extra\n */\nexport function decorrelatedJitter(\n\tbaseNs = 100 * NS_PER_MS,\n\tmaxNs = 30 * NS_PER_SEC,\n): BackoffStrategy {\n\treturn (_attempt, _error, prevDelayNs) => {\n\t\tconst last = prevDelayNs ?? baseNs;\n\t\tconst ceiling = Math.min(maxNs, last * 3);\n\t\treturn randomBetween(baseNs, ceiling);\n\t};\n}\n\n/**\n * Decorator that caps any strategy at `maxAttempts`. Returns `null` (stop retrying) after the cap.\n *\n * @param strategy - Inner strategy to wrap.\n * @param maxAttempts - Maximum number of attempts (inclusive).\n * @returns Wrapped `BackoffStrategy`.\n *\n * @example\n * ```ts\n * import { withMaxAttempts, exponential } from \"@graphrefly/graphrefly-ts\";\n *\n * const capped = withMaxAttempts(exponential(), 3);\n * capped(3); // null — no more retries beyond attempt 3\n * ```\n *\n * @category extra\n */\nexport function withMaxAttempts(strategy: BackoffStrategy, maxAttempts: number): BackoffStrategy {\n\treturn (attempt, error, prevDelayNs) => {\n\t\tif (attempt >= maxAttempts) return null;\n\t\treturn strategy(attempt, error, prevDelayNs);\n\t};\n}\n\n/**\n * Maps a preset name to a concrete {@link BackoffStrategy} with library-default parameters.\n *\n * @param name - One of `constant`, `linear`, `exponential`, `fibonacci`, or `decorrelatedJitter`.\n * @returns Configured strategy with default parameters.\n * @throws Error when `name` is not a known preset.\n *\n * @example\n * ```ts\n * import { resolveBackoffPreset, retry } from \"@graphrefly/graphrefly-ts\";\n *\n * const out = retry(source, { count: 3, backoff: resolveBackoffPreset(\"exponential\") });\n * // Equivalent to retry(source, { count: 3, backoff: exponential() })\n * ```\n *\n * @category extra\n */\nexport function resolveBackoffPreset(name: BackoffPreset): BackoffStrategy {\n\tif (name === \"constant\") return constant(1 * NS_PER_SEC);\n\tif (name === \"linear\") return linear(1 * NS_PER_SEC);\n\tif (name === \"exponential\") return exponential();\n\tif (name === \"fibonacci\") return fibonacci();\n\tif (name === \"decorrelatedJitter\") return decorrelatedJitter();\n\tthrow new Error(\n\t\t`Unknown backoff preset: \"${String(name)}\". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`,\n\t);\n}\n","/**\n * Resilience utilities — roadmap §3.1 (retry, breaker, rate limit, status companions).\n */\nimport { batch } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, DIRTY, ERROR, type Message, RESOLVED } from \"../core/messages.js\";\nimport { type Node, type NodeOptions, node } from \"../core/node.js\";\nimport { producer } from \"../core/sugar.js\";\nimport {\n\ttype BackoffPreset,\n\ttype BackoffStrategy,\n\tNS_PER_MS,\n\tNS_PER_SEC,\n\tresolveBackoffPreset,\n} from \"./backoff.js\";\n\ntype ExtraOpts = Omit<NodeOptions, \"describeKind\">;\n\nfunction operatorOpts(opts?: ExtraOpts): NodeOptions {\n\treturn { describeKind: \"operator\", ...opts };\n}\n\nfunction clampNonNegative(value: number): number {\n\treturn value < 0 ? 0 : value;\n}\n\nfunction msgVal(m: Message): unknown {\n\treturn m[1];\n}\n\nfunction coerceDelayNs(raw: number | null): number {\n\tif (raw === null) return 0;\n\tif (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n\t\tthrow new TypeError(\"backoff strategy must return a finite number or null\");\n\t}\n\treturn raw < 0 ? 0 : raw;\n}\n\nexport type RetryOptions = {\n\t/** Max retry attempts after each terminal `ERROR` (not counting the first failure). */\n\tcount?: number;\n\t/** Delay between attempts; strategies use **nanoseconds**. */\n\tbackoff?: BackoffStrategy | BackoffPreset;\n};\n\n/**\n * Resubscribes to the upstream node after each terminal `ERROR`, after an optional delay.\n *\n * @param source - Upstream node (should use `resubscribable: true`).\n * @param opts - `count` caps attempts; `backoff` supplies delay in **nanoseconds** (or a preset name).\n * @returns Node that retries on error.\n *\n * @remarks\n * **Resubscribable sources:** The upstream should use `resubscribable: true` if it must emit again after `ERROR`.\n * **Protocol:** Forwards unknown message tuples unchanged; handles `DIRTY`, `DATA`, `RESOLVED`, `COMPLETE`, `ERROR`.\n *\n * @example\n * ```ts\n * import { ERROR, NS_PER_SEC, pipe, producer, retry, constant } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = producer(\n * (_d, a) => {\n * a.down([[ERROR, new Error(\"x\")]]);\n * },\n * { resubscribable: true },\n * );\n * const out = retry(src, { count: 2, backoff: constant(0.25 * NS_PER_SEC) });\n * ```\n *\n * @category extra\n */\nexport function retry<T>(source: Node<T>, opts?: RetryOptions): Node<T> {\n\tconst count = opts?.count;\n\tconst backoffOpt = opts?.backoff;\n\tconst maxRetries = count !== undefined ? count : backoffOpt === undefined ? 0 : 0x7fffffff;\n\tif (maxRetries < 0) throw new RangeError(\"retry count must be >= 0\");\n\n\tconst strategy: BackoffStrategy | null =\n\t\tbackoffOpt === undefined\n\t\t\t? null\n\t\t\t: typeof backoffOpt === \"string\"\n\t\t\t\t? resolveBackoffPreset(backoffOpt)\n\t\t\t\t: backoffOpt;\n\n\treturn producer<T>(\n\t\t(_d, a) => {\n\t\t\tlet attempt = 0;\n\t\t\tlet stopped = false;\n\t\t\tlet prevDelay: number | null = null;\n\t\t\tlet unsub: (() => void) | undefined;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet timerGen = 0;\n\n\t\t\tfunction cancelTimer(): void {\n\t\t\t\tif (timer !== undefined) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\ttimer = undefined;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction disconnectUpstream(): void {\n\t\t\t\tunsub?.();\n\t\t\t\tunsub = undefined;\n\t\t\t}\n\n\t\t\tfunction scheduleRetryOrFinish(err: unknown): void {\n\t\t\t\tif (stopped) return;\n\t\t\t\tif (attempt >= maxRetries) {\n\t\t\t\t\tdisconnectUpstream();\n\t\t\t\t\ta.down([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst raw = strategy === null ? 0 : strategy(attempt, err, prevDelay);\n\t\t\t\tconst delayNs = coerceDelayNs(raw === undefined ? null : raw);\n\t\t\t\tprevDelay = delayNs;\n\t\t\t\tattempt += 1;\n\t\t\t\ttimerGen += 1;\n\t\t\t\tconst gen = timerGen;\n\t\t\t\tdisconnectUpstream();\n\t\t\t\tconst delayMs = delayNs > 0 ? delayNs / NS_PER_MS : 1;\n\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\ttimer = undefined;\n\t\t\t\t\tif (stopped || gen !== timerGen) return;\n\t\t\t\t\tconnect();\n\t\t\t\t}, delayMs);\n\t\t\t}\n\n\t\t\tfunction connect(): void {\n\t\t\t\tcancelTimer();\n\t\t\t\tdisconnectUpstream();\n\t\t\t\tunsub = source.subscribe((msgs) => {\n\t\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\t\tconst t = m[0];\n\t\t\t\t\t\tif (t === DIRTY) a.down([[DIRTY]]);\n\t\t\t\t\t\telse if (t === DATA) {\n\t\t\t\t\t\t\tattempt = 0;\n\t\t\t\t\t\t\tprevDelay = null;\n\t\t\t\t\t\t\ta.emit(m[1] as T);\n\t\t\t\t\t\t} else if (t === RESOLVED) a.down([[RESOLVED]]);\n\t\t\t\t\t\telse if (t === COMPLETE) {\n\t\t\t\t\t\t\tdisconnectUpstream();\n\t\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\t\tscheduleRetryOrFinish(msgVal(m));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else a.down([m]);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconnect();\n\n\t\t\treturn () => {\n\t\t\t\tstopped = true;\n\t\t\t\ttimerGen += 1;\n\t\t\t\tcancelTimer();\n\t\t\t\tdisconnectUpstream();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(),\n\t\t\tinitial: source.get(),\n\t\t},\n\t);\n}\n\nexport type CircuitState = \"closed\" | \"open\" | \"half-open\";\n\n/**\n * Thrown when {@link withBreaker} is configured with `onOpen: \"error\"` and the breaker rejects work.\n *\n * @category extra\n */\nexport class CircuitOpenError extends Error {\n\toverride name = \"CircuitOpenError\";\n\tconstructor() {\n\t\tsuper(\"Circuit breaker is open\");\n\t}\n}\n\nexport interface CircuitBreakerOptions {\n\t/** Number of consecutive failures before opening. Default: 5. */\n\tfailureThreshold?: number;\n\t/** Base cooldown in nanoseconds before transitioning to half-open. Default: 30s. */\n\tcooldownNs?: number;\n\t/** Backoff strategy for cooldown escalation across consecutive open cycles. Overrides `cooldownNs` when provided. */\n\tcooldown?: BackoffStrategy;\n\t/** Max trial requests allowed in half-open state. Default: 1. */\n\thalfOpenMax?: number;\n\t/** Clock function returning nanoseconds (for testability). Default: `monotonicNs`. */\n\tnow?: () => number;\n}\n\nexport interface CircuitBreaker {\n\t/** Whether a request should be allowed through. Triggers open→half-open transition when cooldown expires. */\n\tcanExecute(): boolean;\n\t/** Record a successful execution. Resets to closed. */\n\trecordSuccess(): void;\n\t/** Record a failed execution. May transition to open. */\n\trecordFailure(error?: unknown): void;\n\t/** Current circuit state (read-only, does not trigger transitions). */\n\treadonly state: CircuitState;\n\t/** Number of consecutive failures in the current closed period. */\n\treadonly failureCount: number;\n\t/** Manually reset to closed state, clearing all counters. */\n\treset(): void;\n}\n\n/**\n * Factory for a synchronous circuit breaker with `closed`, `open`, and `half-open` states.\n *\n * Supports escalating cooldown via an optional {@link BackoffStrategy} — each consecutive\n * open→half-open→open cycle increments the backoff attempt.\n *\n * @param options - Threshold, cooldown, half-open limit, and optional clock override.\n * @returns {@link CircuitBreaker} instance.\n *\n * @remarks\n * **Timing:** Uses `monotonicNs()` by default (nanoseconds). Override `now` for tests.\n *\n * @example\n * ```ts\n * import { circuitBreaker, exponential, NS_PER_SEC } from \"@graphrefly/graphrefly-ts\";\n *\n * const b = circuitBreaker({\n * failureThreshold: 3,\n * cooldown: exponential({ baseNs: 1 * NS_PER_SEC }),\n * });\n * ```\n *\n * @category extra\n */\nexport function circuitBreaker(options?: CircuitBreakerOptions): CircuitBreaker {\n\tconst threshold = Math.max(1, options?.failureThreshold ?? 5);\n\tconst baseCooldownNs = clampNonNegative(options?.cooldownNs ?? 30 * NS_PER_SEC);\n\tconst cooldownStrategy = options?.cooldown ?? null;\n\tconst halfOpenMax = Math.max(1, options?.halfOpenMax ?? 1);\n\tconst now = options?.now ?? monotonicNs;\n\n\tlet _state: CircuitState = \"closed\";\n\tlet _failureCount = 0;\n\tlet _openCycle = 0;\n\tlet _lastOpenedAt = 0;\n\tlet _lastCooldownNs = baseCooldownNs;\n\tlet _halfOpenAttempts = 0;\n\n\tfunction getCooldownNs(): number {\n\t\tif (!cooldownStrategy) return baseCooldownNs;\n\t\tconst delayNs = cooldownStrategy(_openCycle);\n\t\treturn delayNs !== null ? delayNs : baseCooldownNs;\n\t}\n\n\tfunction transitionToOpen(): void {\n\t\t_state = \"open\";\n\t\t_lastCooldownNs = getCooldownNs();\n\t\t_lastOpenedAt = now();\n\t\t_halfOpenAttempts = 0;\n\t}\n\n\tconst breaker: CircuitBreaker = {\n\t\tcanExecute(): boolean {\n\t\t\tif (_state === \"closed\") return true;\n\n\t\t\tif (_state === \"open\") {\n\t\t\t\tconst elapsed = now() - _lastOpenedAt;\n\t\t\t\tif (elapsed >= _lastCooldownNs) {\n\t\t\t\t\t_state = \"half-open\";\n\t\t\t\t\t_halfOpenAttempts = 1;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (_halfOpenAttempts < halfOpenMax) {\n\t\t\t\t_halfOpenAttempts++;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\n\t\trecordSuccess(): void {\n\t\t\tif (_state === \"half-open\") {\n\t\t\t\t_state = \"closed\";\n\t\t\t\t_failureCount = 0;\n\t\t\t\t_openCycle = 0;\n\t\t\t} else if (_state === \"closed\") {\n\t\t\t\t_failureCount = 0;\n\t\t\t}\n\t\t},\n\n\t\trecordFailure(_error?: unknown): void {\n\t\t\tif (_state === \"half-open\") {\n\t\t\t\t_openCycle++;\n\t\t\t\ttransitionToOpen();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_state === \"closed\") {\n\t\t\t\t_failureCount++;\n\t\t\t\tif (_failureCount >= threshold) {\n\t\t\t\t\ttransitionToOpen();\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\tget state(): CircuitState {\n\t\t\treturn _state;\n\t\t},\n\n\t\tget failureCount(): number {\n\t\t\treturn _failureCount;\n\t\t},\n\n\t\treset(): void {\n\t\t\t_state = \"closed\";\n\t\t\t_failureCount = 0;\n\t\t\t_openCycle = 0;\n\t\t\t_halfOpenAttempts = 0;\n\t\t},\n\t};\n\n\treturn breaker;\n}\n\nexport type WithBreakerBundle<T> = {\n\tnode: Node<T>;\n\tbreakerState: Node<CircuitState>;\n};\n\n/**\n * Returns a unary wrapper that gates upstream `DATA` through a {@link CircuitBreaker}.\n *\n * @param breaker - Shared breaker instance (typically one per resource).\n * @param options - `onOpen: \"skip\"` emits `RESOLVED` when open; `\"error\"` emits {@link CircuitOpenError}.\n * @returns Function mapping `Node<T>` to `{ node, breakerState }` companion nodes.\n *\n * @remarks\n * **Success path:** `COMPLETE` calls {@link CircuitBreaker.recordSuccess}. **Failure path:** upstream `ERROR` calls {@link CircuitBreaker.recordFailure} and is forwarded.\n *\n * @example\n * ```ts\n * import { state, withBreaker, circuitBreaker } from \"@graphrefly/graphrefly-ts\";\n *\n * const b = circuitBreaker({ failureThreshold: 2 });\n * const s = state(1);\n * const { node, breakerState } = withBreaker(b)(s);\n * ```\n *\n * @category extra\n */\nexport function withBreaker<T>(\n\tbreaker: CircuitBreaker,\n\toptions?: { onOpen?: \"skip\" | \"error\" },\n): (source: Node<T>) => WithBreakerBundle<T> {\n\tconst onOpen = options?.onOpen ?? \"skip\";\n\n\treturn (source: Node<T>): WithBreakerBundle<T> => {\n\t\tconst wrapped = node<T>(\n\t\t\t[],\n\t\t\t(_deps, a) => {\n\t\t\t\tfunction syncState(): void {\n\t\t\t\t\twrapped.meta.breakerState.down([[DATA, breaker.state]]);\n\t\t\t\t}\n\n\t\t\t\tconst unsub = source.subscribe((msgs) => {\n\t\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\t\tconst t = m[0];\n\t\t\t\t\t\tif (t === DIRTY) a.down([[DIRTY]]);\n\t\t\t\t\t\telse if (t === DATA) {\n\t\t\t\t\t\t\tif (breaker.canExecute()) {\n\t\t\t\t\t\t\t\tsyncState();\n\t\t\t\t\t\t\t\ta.emit(m[1] as T);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsyncState();\n\t\t\t\t\t\t\t\tif (onOpen === \"error\") a.down([[ERROR, new CircuitOpenError()]]);\n\t\t\t\t\t\t\t\telse a.down([[RESOLVED]]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (t === RESOLVED) a.down([[RESOLVED]]);\n\t\t\t\t\t\telse if (t === COMPLETE) {\n\t\t\t\t\t\t\tbreaker.recordSuccess();\n\t\t\t\t\t\t\tsyncState();\n\t\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\t\tbreaker.recordFailure(msgVal(m));\n\t\t\t\t\t\t\tsyncState();\n\t\t\t\t\t\t\ta.down([m]);\n\t\t\t\t\t\t} else a.down([m]);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tsyncState();\n\t\t\t\treturn unsub;\n\t\t\t},\n\t\t\t{\n\t\t\t\t...operatorOpts(),\n\t\t\t\tmeta: { breakerState: breaker.state },\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\tinitial: source.get(),\n\t\t\t},\n\t\t);\n\n\t\treturn { node: wrapped, breakerState: wrapped.meta.breakerState as Node<CircuitState> };\n\t};\n}\n\nexport interface TokenBucket {\n\t/** Number of tokens currently available (after refill). */\n\tavailable(): number;\n\t/** Try to consume `cost` tokens. Returns `true` if successful. */\n\ttryConsume(cost?: number): boolean;\n}\n\n/**\n * Token-bucket meter (capacity + refill rate per second). Use with {@link rateLimiter} or custom gates.\n *\n * @param capacity - Maximum tokens (must be positive).\n * @param refillPerSecond - Tokens added per elapsed second (non-negative).\n * @returns {@link TokenBucket} instance.\n *\n * @example\n * ```ts\n * import { tokenBucket } from \"@graphrefly/graphrefly-ts\";\n *\n * const bucket = tokenBucket(10, 2); // capacity 10, refill 2 tokens/sec\n * bucket.tryConsume(3); // true — 7 tokens remaining\n * bucket.available(); // ~7 (plus any elapsed refill)\n * ```\n *\n * @category extra\n */\nexport function tokenBucket(capacity: number, refillPerSecond: number): TokenBucket {\n\tif (capacity <= 0) throw new RangeError(\"capacity must be > 0\");\n\tif (refillPerSecond < 0) throw new RangeError(\"refillPerSecond must be >= 0\");\n\n\tlet tokens = capacity;\n\tlet updatedAt = monotonicNs();\n\n\tfunction refill(now: number): void {\n\t\tif (refillPerSecond > 0) {\n\t\t\tconst elapsedNs = now - updatedAt;\n\t\t\ttokens = Math.min(capacity, tokens + (elapsedNs / NS_PER_SEC) * refillPerSecond);\n\t\t}\n\t\tupdatedAt = now;\n\t}\n\n\treturn {\n\t\tavailable(): number {\n\t\t\trefill(monotonicNs());\n\t\t\treturn tokens;\n\t\t},\n\t\ttryConsume(cost = 1): boolean {\n\t\t\tif (cost <= 0) return true;\n\t\t\tconst now = monotonicNs();\n\t\t\trefill(now);\n\t\t\tif (tokens >= cost) {\n\t\t\t\ttokens -= cost;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t};\n}\n\n/**\n * Same behavior as {@link tokenBucket}. Exposed for naming parity with graphrefly-py (`token_tracker`).\n *\n * @param capacity - Maximum tokens (must be positive).\n * @param refillPerSecond - Tokens added per elapsed second (non-negative).\n * @returns A {@link TokenBucket} instance.\n *\n * @example\n * ```ts\n * import { tokenTracker } from \"@graphrefly/graphrefly-ts\";\n *\n * const tracker = tokenTracker(100, 10); // 100-token capacity, 10/sec refill\n * tracker.tryConsume(5); // true\n * ```\n *\n * @category extra\n */\nexport function tokenTracker(capacity: number, refillPerSecond: number): TokenBucket {\n\treturn tokenBucket(capacity, refillPerSecond);\n}\n\n/**\n * Enforces a sliding window: at most `maxEvents` `DATA` values per `windowNs`.\n *\n * @param source - Upstream node.\n * @param maxEvents - Maximum `DATA` emissions per window (must be positive).\n * @param windowNs - Window length in nanoseconds (must be positive).\n * @returns Node that queues excess values FIFO until a slot frees.\n *\n * @remarks\n * **Terminal:** `COMPLETE` / `ERROR` cancel timers, drop pending queue, and clear window state.\n *\n * @example\n * ```ts\n * import { rateLimiter, state, NS_PER_SEC } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state(0);\n * // Allow at most 5 DATA values per second\n * const limited = rateLimiter(src, 5, NS_PER_SEC);\n * limited.subscribe((msgs) => console.log(msgs));\n * ```\n *\n * @category extra\n */\nexport function rateLimiter<T>(source: Node<T>, maxEvents: number, windowNs: number): Node<T> {\n\tif (maxEvents <= 0) throw new RangeError(\"maxEvents must be > 0\");\n\tif (windowNs <= 0) throw new RangeError(\"windowNs must be > 0\");\n\treturn producer<T>(\n\t\t(_d, a) => {\n\t\t\tconst times: number[] = [];\n\t\t\tconst pending: T[] = [];\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet timerGen = 0;\n\n\t\t\tfunction cancelTimer(): void {\n\t\t\t\tif (timer !== undefined) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\ttimer = undefined;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfunction prune(now: number): void {\n\t\t\t\tconst boundary = now - windowNs;\n\t\t\t\twhile (times.length > 0 && times[0] <= boundary) times.shift();\n\t\t\t}\n\n\t\t\tfunction tryEmit(): void {\n\t\t\t\twhile (pending.length > 0) {\n\t\t\t\t\tconst now = monotonicNs();\n\t\t\t\t\tprune(now);\n\t\t\t\t\tif (times.length < maxEvents) {\n\t\t\t\t\t\ttimes.push(now);\n\t\t\t\t\t\ta.emit(pending.shift() as T);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst oldest = times[0];\n\t\t\t\t\t\tcancelTimer();\n\t\t\t\t\t\ttimerGen += 1;\n\t\t\t\t\t\tconst gen = timerGen;\n\t\t\t\t\t\tconst delayNs = Math.max(0, oldest + windowNs - monotonicNs());\n\t\t\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\t\t\ttimer = undefined;\n\t\t\t\t\t\t\tif (gen !== timerGen) return;\n\t\t\t\t\t\t\ttryEmit();\n\t\t\t\t\t\t}, delayNs / NS_PER_MS);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst unsub = source.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tconst t = m[0];\n\t\t\t\t\tif (t === DIRTY) a.down([[DIRTY]]);\n\t\t\t\t\telse if (t === DATA) {\n\t\t\t\t\t\tpending.push(m[1] as T);\n\t\t\t\t\t\ttryEmit();\n\t\t\t\t\t} else if (t === RESOLVED) a.down([[RESOLVED]]);\n\t\t\t\t\telse if (t === COMPLETE) {\n\t\t\t\t\t\ttimerGen += 1;\n\t\t\t\t\t\tcancelTimer();\n\t\t\t\t\t\tpending.length = 0;\n\t\t\t\t\t\ttimes.length = 0;\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\ttimerGen += 1;\n\t\t\t\t\t\tcancelTimer();\n\t\t\t\t\t\tpending.length = 0;\n\t\t\t\t\t\ttimes.length = 0;\n\t\t\t\t\t\ta.down([m]);\n\t\t\t\t\t} else a.down([m]);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn () => {\n\t\t\t\ttimerGen += 1;\n\t\t\t\tcancelTimer();\n\t\t\t\tunsub();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(),\n\t\t\tinitial: source.get(),\n\t\t},\n\t);\n}\n\nexport type StatusValue = \"pending\" | \"active\" | \"completed\" | \"errored\";\n\nexport type WithStatusBundle<T> = {\n\tnode: Node<T>;\n\tstatus: Node<StatusValue>;\n\terror: Node<unknown | null>;\n};\n\n/**\n * Wraps `src` with `status` and `error` {@link state} companions for UI or meta snapshots.\n *\n * @param src - Upstream node to mirror.\n * @param options - `initialStatus` defaults to `\"pending\"`.\n * @returns `{ node, status, error }` where `error` holds the last `ERROR` payload.\n *\n * @remarks\n * **Recovery:** After `errored`, the next `DATA` clears `error` and sets `active` inside {@link batch} (matches graphrefly-py).\n *\n * @example\n * ```ts\n * import { withStatus, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state<number>(0);\n * const { node, status, error } = withStatus(src);\n *\n * status.subscribe((msgs) => console.log(\"status:\", msgs));\n * src.down([[DATA, 42]]); // status → \"active\"\n * ```\n *\n * @category extra\n */\nexport function withStatus<T>(\n\tsrc: Node<T>,\n\toptions?: { initialStatus?: StatusValue },\n): WithStatusBundle<T> {\n\tconst initialStatus = options?.initialStatus ?? \"pending\";\n\n\tconst out = node<T>(\n\t\t[],\n\t\t(_deps, a) => {\n\t\t\tout.meta.status.down([[DATA, initialStatus]]);\n\t\t\tout.meta.error.down([[DATA, null]]);\n\n\t\t\tconst unsub = src.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tconst t = m[0];\n\t\t\t\t\tif (t === DIRTY) a.down([[DIRTY]]);\n\t\t\t\t\telse if (t === DATA) {\n\t\t\t\t\t\tif (out.meta.status.get() === \"errored\") {\n\t\t\t\t\t\t\tbatch(() => {\n\t\t\t\t\t\t\t\tout.meta.error.down([[DATA, null]]);\n\t\t\t\t\t\t\t\tout.meta.status.down([[DATA, \"active\"]]);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tout.meta.status.down([[DATA, \"active\"]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ta.emit(m[1] as T);\n\t\t\t\t\t} else if (t === RESOLVED) a.down([[RESOLVED]]);\n\t\t\t\t\telse if (t === COMPLETE) {\n\t\t\t\t\t\tout.meta.status.down([[DATA, \"completed\"]]);\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tconst err = msgVal(m);\n\t\t\t\t\t\tbatch(() => {\n\t\t\t\t\t\t\tout.meta.error.down([[DATA, err]]);\n\t\t\t\t\t\t\tout.meta.status.down([[DATA, \"errored\"]]);\n\t\t\t\t\t\t});\n\t\t\t\t\t\ta.down([m]);\n\t\t\t\t\t} else a.down([m]);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn unsub;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(),\n\t\t\tmeta: { status: initialStatus, error: null },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tresubscribable: true,\n\t\t\tinitial: src.get(),\n\t\t},\n\t);\n\n\treturn {\n\t\tnode: out,\n\t\tstatus: out.meta.status as Node<StatusValue>,\n\t\terror: out.meta.error as Node<unknown | null>,\n\t};\n}\n","/**\n * Protocol, system, and ingest adapters (roadmap §5.2, §5.2c).\n *\n * Each adapter wraps an external protocol or system as a reactive {@link Node}\n * built on {@link producer} / {@link node} — no second protocol.\n *\n * **Moved from sources.ts:** fromHTTP, fromWebSocket/toWebSocket, fromWebhook,\n * toSSE, fromMCP, fromGitHook.\n *\n * **New (5.2c):** fromOTel, fromSyslog, fromStatsD, fromPrometheus,\n * fromKafka/toKafka, fromRedisStream/toRedisStream, fromCSV, fromNDJSON,\n * fromClickHouseWatch.\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { wallClockNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, DIRTY, ERROR, type Message, RESOLVED } from \"../core/messages.js\";\nimport { type Node, type NodeOptions, node } from \"../core/node.js\";\nimport { producer, state } from \"../core/sugar.js\";\nimport { NS_PER_MS, NS_PER_SEC } from \"./backoff.js\";\nimport { type WithStatusBundle, withStatus } from \"./resilience.js\";\nimport type { AsyncSourceOpts } from \"./sources.js\";\nimport { globToRegExp, matchesAnyPattern } from \"./sources.js\";\n\n/** Structured callback for sink transport failures (Kafka, Redis, etc.). */\nexport type SinkTransportError = {\n\tstage: \"serialize\" | \"send\";\n\terror: Error;\n\tvalue: unknown;\n};\n\ntype ExtraOpts = Omit<NodeOptions, \"describeKind\">;\n\nfunction sourceOpts(opts?: ExtraOpts): NodeOptions {\n\treturn { describeKind: \"producer\", ...opts };\n}\n\n// ——————————————————————————————————————————————————————————————\n// WebSocket adapter (from sources.ts)\n// ——————————————————————————————————————————————————————————————\n\n/** WebSocket-like transport accepted by {@link fromWebSocket} / {@link toWebSocket}. */\nexport type WebSocketLike = {\n\tsend(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;\n\tclose(code?: number, reason?: string): void;\n\taddEventListener(type: \"message\" | \"error\" | \"close\", listener: (ev: unknown) => void): void;\n\tremoveEventListener(type: \"message\" | \"error\" | \"close\", listener: (ev: unknown) => void): void;\n};\n\nexport type WebSocketMessageEventLike = { data: unknown };\nexport type WebSocketRegister<T> = (\n\temit: (payload: T) => void,\n\terror: (err: unknown) => void,\n\tcomplete: () => void,\n) => () => void;\n\n/**\n * Wraps a WebSocket as a GraphReFly producer source.\n *\n * Incoming socket messages are emitted as `DATA`; socket `error` emits `ERROR`; socket `close`\n * emits `COMPLETE`. Teardown detaches listeners and optionally closes the socket.\n *\n * @category extra\n */\nexport function fromWebSocket<T = unknown>(\n\tsocket: WebSocketLike,\n\topts?: ExtraOpts & {\n\t\tparse?: (payload: unknown, event: unknown) => T;\n\t\tcloseOnTeardown?: boolean;\n\t},\n): Node<T>;\nexport function fromWebSocket<T = unknown>(\n\tregister: WebSocketRegister<T>,\n\topts?: ExtraOpts & {\n\t\tparse?: (payload: unknown, event: unknown) => T;\n\t\tcloseOnTeardown?: boolean;\n\t},\n): Node<T>;\nexport function fromWebSocket<T = unknown>(\n\tsocketOrRegister: WebSocketLike | WebSocketRegister<T>,\n\topts?: ExtraOpts & {\n\t\tparse?: (payload: unknown, event: unknown) => T;\n\t\tcloseOnTeardown?: boolean;\n\t},\n): Node<T> {\n\tconst { parse, closeOnTeardown = false, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tlet active = true;\n\t\tlet cleanup: (() => void) | undefined;\n\t\tconst runCleanup = () => {\n\t\t\tconst fn = cleanup;\n\t\t\tcleanup = undefined;\n\t\t\tfn?.();\n\t\t};\n\t\tconst terminate = (message: Message) => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\ta.down([message]);\n\t\t\trunCleanup();\n\t\t};\n\t\tconst emit = (raw: unknown, event: unknown = raw) => {\n\t\t\tif (!active) return;\n\t\t\ttry {\n\t\t\t\tconst payload =\n\t\t\t\t\traw !== null && typeof raw === \"object\" && \"data\" in (raw as Record<string, unknown>)\n\t\t\t\t\t\t? (raw as WebSocketMessageEventLike).data\n\t\t\t\t\t\t: raw;\n\t\t\t\tconst parsed = parse ? parse(payload, event) : (payload as T);\n\t\t\t\ta.emit(parsed);\n\t\t\t} catch (err) {\n\t\t\t\tterminate([ERROR, err]);\n\t\t\t}\n\t\t};\n\t\tconst error = (err: unknown) => {\n\t\t\tterminate([ERROR, err]);\n\t\t};\n\t\tconst complete = () => {\n\t\t\tterminate([COMPLETE]);\n\t\t};\n\t\tif (typeof socketOrRegister === \"function\") {\n\t\t\ttry {\n\t\t\t\tcleanup = socketOrRegister(emit, error, complete);\n\t\t\t\tif (typeof cleanup !== \"function\") {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"fromWebSocket register contract violation: register must return cleanup callable\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tterminate([ERROR, err]);\n\t\t\t}\n\t\t\treturn () => {\n\t\t\t\tactive = false;\n\t\t\t\trunCleanup();\n\t\t\t};\n\t\t}\n\n\t\tconst ws = socketOrRegister;\n\t\tconst onMessage = (event: unknown) => emit(event, event);\n\t\tconst onError = (event: unknown) => error(event);\n\t\tconst onClose = () => complete();\n\t\tws.addEventListener(\"message\", onMessage);\n\t\tws.addEventListener(\"error\", onError);\n\t\tws.addEventListener(\"close\", onClose);\n\t\tcleanup = () => {\n\t\t\tws.removeEventListener(\"message\", onMessage);\n\t\t\tws.removeEventListener(\"error\", onError);\n\t\t\tws.removeEventListener(\"close\", onClose);\n\t\t\tif (closeOnTeardown) ws.close();\n\t\t};\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t\trunCleanup();\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n// ——————————————————————————————————————————————————————————————\n// Webhook adapter (from sources.ts)\n// ——————————————————————————————————————————————————————————————\n\n/** Registration callback for {@link fromWebhook}. */\nexport type WebhookRegister<T> = (handlers: {\n\t/** Push one webhook payload downstream as `[[DATA, payload]]`. */\n\temit: (payload: T) => void;\n\t/** Push terminal error as `[[ERROR, err]]`. */\n\terror: (err: unknown) => void;\n\t/** Push terminal completion as `[[COMPLETE]]`. */\n\tcomplete: () => void;\n}) => (() => void) | undefined;\n\n/**\n * Bridges HTTP webhook callbacks into a GraphReFly source.\n *\n * The `register` callback wires your runtime/framework callback to GraphReFly and may return a\n * cleanup function. This keeps the adapter runtime-agnostic while following the same producer\n * pattern as {@link fromEvent}.\n *\n * @param register - Registers webhook handlers (`emit`, `error`, `complete`) and optionally returns cleanup.\n * @param opts - Optional producer options.\n * @returns `Node<T>` — webhook payloads as `DATA`; teardown runs returned cleanup.\n *\n * @example\n * ```ts\n * import express from \"express\";\n * import { fromWebhook } from \"@graphrefly/graphrefly-ts\";\n *\n * type HookPayload = { event: string; data: unknown };\n * const app = express();\n * app.use(express.json());\n *\n * const hook$ = fromWebhook<HookPayload>(({ emit, error }) => {\n * const handler = (req: express.Request, res: express.Response) => {\n * try {\n * emit(req.body as HookPayload);\n * res.status(200).send(\"ok\");\n * } catch (e) {\n * error(e);\n * res.status(500).send(\"error\");\n * }\n * };\n * app.post(\"/webhook\", handler);\n * return () => {\n * // Express has no direct route-removal API in common use.\n * };\n * });\n * ```\n *\n * @example Fastify\n * ```ts\n * import Fastify from \"fastify\";\n * import { fromWebhook } from \"@graphrefly/graphrefly-ts\";\n *\n * const fastify = Fastify();\n * const hook$ = fromWebhook<any>(({ emit, error }) => {\n * const handler = async (req: any, reply: any) => {\n * try {\n * emit(req.body);\n * reply.code(200).send({ ok: true });\n * } catch (e) {\n * error(e);\n * reply.code(500).send({ ok: false });\n * }\n * };\n * fastify.post(\"/webhook\", handler);\n * return () => {};\n * });\n * ```\n *\n * @category extra\n */\nexport function fromWebhook<T = unknown>(register: WebhookRegister<T>, opts?: ExtraOpts): Node<T> {\n\treturn producer<T>((_d, a) => {\n\t\tlet active = true;\n\t\tconst emit = (payload: T) => {\n\t\t\tif (!active) return;\n\t\t\ta.emit(payload);\n\t\t};\n\t\tconst error = (err: unknown) => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\ta.down([[ERROR, err]]);\n\t\t};\n\t\tconst complete = () => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\ta.down([[COMPLETE]]);\n\t\t};\n\n\t\ttry {\n\t\t\tconst cleanup = register({ emit, error, complete });\n\t\t\treturn () => {\n\t\t\t\tactive = false;\n\t\t\t\tcleanup?.();\n\t\t\t};\n\t\t} catch (err) {\n\t\t\terror(err);\n\t\t\treturn () => {\n\t\t\t\tactive = false;\n\t\t\t};\n\t\t}\n\t}, sourceOpts(opts));\n}\n\n// ——————————————————————————————————————————————————————————————\n// HTTP adapter (from sources.ts)\n// ——————————————————————————————————————————————————————————————\n\n/**\n * Options for {@link fromHTTP}.\n *\n * @category extra\n */\nexport interface FromHTTPOptions extends AsyncSourceOpts {\n\t/** HTTP method. Default: `\"GET\"`. */\n\tmethod?: string;\n\t/** Request headers. */\n\theaders?: Record<string, string>;\n\t/** Request body (for POST/PUT/PATCH). */\n\tbody?: any;\n\t/** Transform the Response before emitting. Default: `response.json()`. */\n\ttransform?: (response: Response) => any | Promise<any>;\n\t/** Request timeout in **nanoseconds**. Default: `30s` (30 * NS_PER_SEC). */\n\ttimeoutNs?: number;\n}\n\n/**\n * Result of {@link fromHTTP}: main source plus status, error, and fetch count companions.\n *\n * @category extra\n */\nexport type HTTPBundle<T> = WithStatusBundle<T> & {\n\t/** Number of successful fetches. */\n\tfetchCount: Node<number>;\n\t/** Nanosecond wall-clock timestamp of the last successful fetch. */\n\tlastUpdated: Node<number>;\n};\n\n/**\n * Creates a one-shot fetch-based HTTP source with lifecycle tracking.\n *\n * @category extra\n */\nexport function fromHTTP<T = any>(url: string, opts?: FromHTTPOptions): HTTPBundle<T> {\n\tconst {\n\t\tmethod = \"GET\",\n\t\theaders,\n\t\tbody: bodyOpt,\n\t\ttransform = (r: Response) => r.json(),\n\t\ttimeoutNs = 30 * NS_PER_SEC,\n\t\tsignal: externalSignal,\n\t\t...rest\n\t} = opts ?? {};\n\n\tconst fetchCount = state(0, { name: `${rest.name ?? \"http\"}/fetchCount` });\n\tconst lastUpdated = state(0, { name: `${rest.name ?? \"http\"}/lastUpdated` });\n\n\tconst sourceNode = producer<T>((_d, a) => {\n\t\tlet active = true;\n\t\tconst abort = new AbortController();\n\n\t\tif (externalSignal?.aborted) {\n\t\t\ta.down([[ERROR, externalSignal.reason ?? new Error(\"Aborted\")]]);\n\t\t\treturn () => {};\n\t\t}\n\t\texternalSignal?.addEventListener(\"abort\", () => abort.abort(externalSignal.reason), {\n\t\t\tonce: true,\n\t\t});\n\n\t\tconst timeoutId = setTimeout(\n\t\t\t() => abort.abort(new Error(\"Request timeout\")),\n\t\t\tMath.ceil(timeoutNs / NS_PER_MS),\n\t\t);\n\n\t\tconst body =\n\t\t\tbodyOpt !== undefined\n\t\t\t\t? typeof bodyOpt === \"string\"\n\t\t\t\t\t? bodyOpt\n\t\t\t\t\t: JSON.stringify(bodyOpt)\n\t\t\t\t: undefined;\n\n\t\tfetch(url, { method, headers, body, signal: abort.signal })\n\t\t\t.then(async (res) => {\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\tif (!active) return;\n\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tthrow new Error(`HTTP ${res.status}: ${res.statusText}`);\n\t\t\t\t}\n\n\t\t\t\tconst data = await transform(res);\n\t\t\t\tif (!active) return;\n\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfetchCount.down([[DATA, (fetchCount.get() ?? 0) + 1]]);\n\t\t\t\t\tlastUpdated.down([[DATA, wallClockNs()]]);\n\t\t\t\t\ta.emit(data as T);\n\t\t\t\t});\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\tif (!active) return;\n\t\t\t\tif (err.name === \"AbortError\") return;\n\t\t\t\ta.down([[ERROR, err]]);\n\t\t\t});\n\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t\tabort.abort();\n\t\t};\n\t}, sourceOpts(rest));\n\n\tconst tracked = withStatus(sourceNode);\n\n\treturn {\n\t\t...tracked,\n\t\tfetchCount,\n\t\tlastUpdated,\n\t};\n}\n\n// ——————————————————————————————————————————————————————————————\n// SSE sink (from sources.ts)\n// ——————————————————————————————————————————————————————————————\n\n/** Options for {@link toSSE}. */\nexport type ToSSEOptions = {\n\t/** Custom payload serializer for non-string payloads. Default: `JSON.stringify` fallback to `String(value)`. */\n\tserialize?: (value: unknown) => string;\n\t/** Event name for DATA tuples. Default: `\"data\"`. */\n\tdataEvent?: string;\n\t/** Event name for ERROR tuples. Default: `\"error\"`. */\n\terrorEvent?: string;\n\t/** Event name for COMPLETE tuples. Default: `\"complete\"`. */\n\tcompleteEvent?: string;\n\t/** Emit `event: resolved` when RESOLVED arrives. Default: `false`. */\n\tincludeResolved?: boolean;\n\t/** Emit `event: dirty` when DIRTY arrives. Default: `false`. */\n\tincludeDirty?: boolean;\n\t/** Add SSE comment keepalive frames (`: keepalive`) on an interval. Disabled when unset. */\n\tkeepAliveMs?: number;\n\t/** Optional abort signal to terminate the stream early. */\n\tsignal?: AbortSignal;\n\t/** Maps custom message types to SSE event names. */\n\teventNameResolver?: (type: symbol) => string;\n};\n\nfunction messageTypeLabel(t: symbol): string {\n\treturn Symbol.keyFor(t) ?? t.description ?? \"message\";\n}\n\nfunction serializeSseData(value: unknown, serialize: (value: unknown) => string): string {\n\tif (typeof value === \"string\") return value;\n\treturn serialize(value);\n}\n\nfunction sseFrame(event: string, data?: string): string {\n\tlet out = `event: ${event}\\n`;\n\tif (data !== undefined) {\n\t\tconst lines = data.split(/\\r?\\n/);\n\t\tfor (const line of lines) {\n\t\t\tout += `data: ${line}\\n`;\n\t\t}\n\t}\n\treturn `${out}\\n`;\n}\n\n/**\n * Creates a standard Server-Sent Events stream from node messages.\n *\n * @category extra\n */\nexport function toSSE<T>(source: Node<T>, opts?: ToSSEOptions): ReadableStream<Uint8Array> {\n\tconst {\n\t\tserialize = (value: unknown) => {\n\t\t\tif (value instanceof Error) return value.message;\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(value);\n\t\t\t} catch {\n\t\t\t\treturn String(value);\n\t\t\t}\n\t\t},\n\t\tdataEvent = \"data\",\n\t\terrorEvent = \"error\",\n\t\tcompleteEvent = \"complete\",\n\t\tincludeResolved = false,\n\t\tincludeDirty = false,\n\t\tkeepAliveMs,\n\t\tsignal,\n\t\teventNameResolver = messageTypeLabel,\n\t} = opts ?? {};\n\tconst encoder = new TextEncoder();\n\tlet stop: (() => void) | undefined;\n\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tlet closed = false;\n\t\t\tlet keepAlive: ReturnType<typeof setInterval> | undefined;\n\t\t\tlet unsub: () => void = () => {};\n\t\t\tconst close = () => {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tif (keepAlive !== undefined) clearInterval(keepAlive);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tunsub();\n\t\t\t\tcontroller.close();\n\t\t\t};\n\t\t\tstop = close;\n\t\t\tconst write = (event: string, data?: string) => {\n\t\t\t\tif (closed) return;\n\t\t\t\tcontroller.enqueue(encoder.encode(sseFrame(event, data)));\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (closed) return;\n\t\t\t\tclose();\n\t\t\t};\n\t\t\tunsub = source.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tconst t = msg[0];\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\twrite(dataEvent, serializeSseData(msg[1], serialize));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (t === ERROR) {\n\t\t\t\t\t\twrite(errorEvent, serializeSseData(msg[1], serialize));\n\t\t\t\t\t\tclose();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\t\twrite(completeEvent);\n\t\t\t\t\t\tclose();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!includeResolved && t === RESOLVED) continue;\n\t\t\t\t\tif (!includeDirty && t === DIRTY) continue;\n\t\t\t\t\twrite(\n\t\t\t\t\t\teventNameResolver(t),\n\t\t\t\t\t\tmsg.length > 1 ? serializeSseData(msg[1], serialize) : undefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (keepAliveMs !== undefined && keepAliveMs > 0) {\n\t\t\t\tkeepAlive = setInterval(() => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tcontroller.enqueue(encoder.encode(\": keepalive\\n\\n\"));\n\t\t\t\t}, keepAliveMs);\n\t\t\t}\n\t\t\tif (signal?.aborted) onAbort();\n\t\t\telse signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t},\n\t\tcancel() {\n\t\t\tstop?.();\n\t\t},\n\t});\n}\n\n// ——————————————————————————————————————————————————————————————\n// WebSocket sink (from sources.ts)\n// ——————————————————————————————————————————————————————————————\n\n/** Options for {@link toWebSocket}. */\nexport type ToWebSocketOptions<T> = {\n\t/** Serialize DATA payloads before `socket.send(...)`. */\n\tserialize?: (value: T) => string | ArrayBufferLike | Blob | ArrayBufferView;\n\t/** Close socket when upstream emits COMPLETE. Default: `true`. */\n\tcloseOnComplete?: boolean;\n\t/** Close socket when upstream emits ERROR. Default: `true`. */\n\tcloseOnError?: boolean;\n\t/** Optional close code used when close is triggered by terminal tuples. */\n\tcloseCode?: number;\n\t/** Optional close reason used when close is triggered by terminal tuples. */\n\tcloseReason?: string;\n\t/** Structured callback for serialize/send/close transport failures. */\n\tonTransportError?: (event: ToWebSocketTransportError) => void;\n};\n\nexport type ToWebSocketTransportError = {\n\tstage: \"serialize\" | \"send\" | \"close\";\n\terror: Error;\n\tmessage: Message | undefined;\n};\n\n/**\n * Forwards upstream `DATA` payloads to a WebSocket via `send`.\n *\n * @category extra\n */\nexport function toWebSocket<T>(\n\tsource: Node<T>,\n\tsocket: WebSocketLike,\n\topts?: ToWebSocketOptions<T>,\n): () => void {\n\tconst {\n\t\tserialize = (value: T) => {\n\t\t\tif (\n\t\t\t\ttypeof value === \"string\" ||\n\t\t\t\tvalue instanceof Blob ||\n\t\t\t\tvalue instanceof ArrayBuffer ||\n\t\t\t\tArrayBuffer.isView(value)\n\t\t\t) {\n\t\t\t\treturn value as string | ArrayBufferLike | Blob | ArrayBufferView;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(value);\n\t\t\t} catch {\n\t\t\t\treturn String(value);\n\t\t\t}\n\t\t},\n\t\tcloseOnComplete = true,\n\t\tcloseOnError = true,\n\t\tcloseCode,\n\t\tcloseReason,\n\t\tonTransportError,\n\t} = opts ?? {};\n\tlet closed = false;\n\tconst toError = (err: unknown): Error => (err instanceof Error ? err : new Error(String(err)));\n\tconst reportTransportError = (\n\t\tstage: \"serialize\" | \"send\" | \"close\",\n\t\terror: unknown,\n\t\tmessage: Message | undefined,\n\t) => {\n\t\tif (!onTransportError) return;\n\t\ttry {\n\t\t\tonTransportError({ stage, error: toError(error), message });\n\t\t} catch {\n\t\t\t/* user-provided hook should not throw into graph path */\n\t\t}\n\t};\n\tconst closeSocket = (message: Message) => {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\ttry {\n\t\t\tsocket.close(closeCode, closeReason);\n\t\t} catch (err) {\n\t\t\treportTransportError(\"close\", err, message);\n\t\t}\n\t};\n\n\tconst inner = node([source as Node], () => undefined, {\n\t\tdescribeKind: \"effect\",\n\t\tonMessage(msg: Message) {\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\tlet serialized: string | ArrayBufferLike | Blob | ArrayBufferView;\n\t\t\t\ttry {\n\t\t\t\t\tserialized = serialize(msg[1] as T);\n\t\t\t\t} catch (err) {\n\t\t\t\t\treportTransportError(\"serialize\", err, msg);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tsocket.send(serialized === undefined ? String(msg[1] as T) : serialized);\n\t\t\t\t} catch (err) {\n\t\t\t\t\treportTransportError(\"send\", err, msg);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (msg[0] === COMPLETE && closeOnComplete) {\n\t\t\t\tcloseSocket(msg);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (msg[0] === ERROR && closeOnError) {\n\t\t\t\tcloseSocket(msg);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n\treturn inner.subscribe(() => {});\n}\n\n// ——————————————————————————————————————————————————————————————\n// MCP adapter (from sources.ts)\n// ——————————————————————————————————————————————————————————————\n\n/**\n * Duck-typed MCP (Model Context Protocol) client — only the notification\n * registration surface is required so callers are not coupled to a specific SDK.\n */\nexport type MCPClientLike = {\n\tsetNotificationHandler(method: string, handler: (notification: unknown) => void): void;\n};\n\n/** Options for {@link fromMCP}. */\nexport type FromMCPOptions = ExtraOpts & {\n\t/** MCP notification method to subscribe to. Default `\"notifications/message\"`. */\n\tmethod?: string;\n\tonDisconnect?: (cb: (err?: unknown) => void) => void;\n};\n\n/**\n * Wraps an MCP client's server-push notifications as a reactive source.\n *\n * @category extra\n */\nexport function fromMCP<T = unknown>(client: MCPClientLike, opts?: FromMCPOptions): Node<T> {\n\tconst { method = \"notifications/message\", onDisconnect, ...rest } = opts ?? {};\n\treturn producer<T>((_d, a) => {\n\t\tlet active = true;\n\t\tclient.setNotificationHandler(method, (notification) => {\n\t\t\tif (!active) return;\n\t\t\ta.emit(notification as T);\n\t\t});\n\t\tif (onDisconnect) {\n\t\t\tonDisconnect((err?: unknown) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\ta.down([[ERROR, err ?? new Error(\"MCP client disconnected\")]]);\n\t\t\t});\n\t\t}\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t\tclient.setNotificationHandler(method, () => {});\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n// ——————————————————————————————————————————————————————————————\n// Git adapter (from sources.ts)\n// ——————————————————————————————————————————————————————————————\n\n/** Git hook type for {@link fromGitHook}. */\nexport type GitHookType = \"post-commit\" | \"post-merge\" | \"post-checkout\" | \"post-rewrite\";\n\n/** Structured git event emitted by {@link fromGitHook}. */\nexport type GitEvent = {\n\thook: GitHookType;\n\tcommit: string;\n\tfiles: string[];\n\tmessage: string;\n\tauthor: string;\n\ttimestamp_ns: number;\n};\n\n/** Options for {@link fromGitHook}. */\nexport type FromGitHookOptions = ExtraOpts & {\n\tpollMs?: number;\n\tinclude?: string[];\n\texclude?: string[];\n};\n\n// globToRegExp, matchesAnyPattern imported from ./sources.js\n\n/**\n * Git change detection as a reactive source.\n *\n * @category extra\n */\nexport function fromGitHook(repoPath: string, opts?: FromGitHookOptions): Node<GitEvent> {\n\tconst { pollMs = 5000, include, exclude, ...rest } = opts ?? {};\n\tconst includePatterns = include?.map(globToRegExp) ?? [];\n\tconst excludePatterns = exclude?.map(globToRegExp) ?? [];\n\n\treturn producer<GitEvent>((_d, a) => {\n\t\tlet active = true;\n\t\tlet lastSeen: string;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\n\t\tconst { execFileSync } = require(\"node:child_process\") as typeof import(\"node:child_process\");\n\n\t\tconst git = (...args: string[]): string => {\n\t\t\ttry {\n\t\t\t\treturn execFileSync(\"git\", args, { cwd: repoPath, encoding: \"utf-8\" }).trim();\n\t\t\t} catch (err) {\n\t\t\t\tif (!active) return \"\";\n\t\t\t\ta.down([[ERROR, err]]);\n\t\t\t\tcleanup();\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t};\n\n\t\tconst cleanup = () => {\n\t\t\tactive = false;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t};\n\n\t\tlastSeen = git(\"rev-parse\", \"HEAD\");\n\t\tif (!active) return () => {};\n\n\t\tconst schedule = () => {\n\t\t\tif (!active) return;\n\t\t\ttimer = setTimeout(check, pollMs);\n\t\t};\n\n\t\tconst check = () => {\n\t\t\tif (!active) return;\n\t\t\tconst head = git(\"rev-parse\", \"HEAD\");\n\t\t\tif (!active || !head || head === lastSeen) {\n\t\t\t\tschedule();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlet files = git(\"diff\", \"--name-only\", `${lastSeen}..${head}`).split(\"\\n\").filter(Boolean);\n\t\t\tif (!active) {\n\t\t\t\tschedule();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (includePatterns.length > 0) {\n\t\t\t\tfiles = files.filter((f) => matchesAnyPattern(f, includePatterns));\n\t\t\t}\n\t\t\tif (excludePatterns.length > 0) {\n\t\t\t\tfiles = files.filter((f) => !matchesAnyPattern(f, excludePatterns));\n\t\t\t}\n\n\t\t\tconst message = git(\"log\", \"-1\", \"--format=%s\", head);\n\t\t\tif (!active) {\n\t\t\t\tschedule();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst author = git(\"log\", \"-1\", \"--format=%an\", head);\n\t\t\tif (!active) {\n\t\t\t\tschedule();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ta.emit({\n\t\t\t\thook: \"post-commit\" as GitHookType,\n\t\t\t\tcommit: head,\n\t\t\t\tfiles,\n\t\t\t\tmessage,\n\t\t\t\tauthor,\n\t\t\t\ttimestamp_ns: wallClockNs(),\n\t\t\t});\n\t\t\tlastSeen = head;\n\t\t\tschedule();\n\t\t};\n\n\t\tschedule();\n\t\treturn cleanup;\n\t}, sourceOpts(rest));\n}\n\n// ——————————————————————————————————————————————————————————————\n// 5.2c — Ingest adapters (universal source layer)\n// ——————————————————————————————————————————————————————————————\n\n// ——— Shared helpers ———\n\n/** Standard handler triple for adapters that accept injected registrations. */\nexport type AdapterHandlers<T> = {\n\temit: (payload: T) => void;\n\terror: (err: unknown) => void;\n\tcomplete: () => void;\n};\n\n// ——— OpenTelemetry (OTLP/HTTP) ———\n\n/** Structured OTel span. */\nexport type OTelSpan = {\n\ttraceId: string;\n\tspanId: string;\n\toperationName: string;\n\tserviceName: string;\n\tstartTimeNs: number;\n\tendTimeNs: number;\n\tstatus: \"OK\" | \"ERROR\" | \"UNSET\";\n\tattributes: Record<string, unknown>;\n\tevents: Array<{ name: string; timestampNs: number; attributes?: Record<string, unknown> }>;\n};\n\n/** Structured OTel metric data point. */\nexport type OTelMetric = {\n\tname: string;\n\tdescription?: string;\n\tunit?: string;\n\ttype: \"gauge\" | \"sum\" | \"histogram\" | \"summary\";\n\tvalue: number;\n\tattributes: Record<string, unknown>;\n\ttimestampNs: number;\n};\n\n/** Structured OTel log record. */\nexport type OTelLog = {\n\ttimestampNs: number;\n\tseverityNumber?: number;\n\tseverityText?: string;\n\tbody: unknown;\n\tattributes: Record<string, unknown>;\n\ttraceId?: string;\n\tspanId?: string;\n};\n\n/** Registration callback for the OTLP/HTTP receiver. */\nexport type OTelRegister = (handlers: {\n\tonTraces: (spans: OTelSpan[]) => void;\n\tonMetrics: (metrics: OTelMetric[]) => void;\n\tonLogs: (logs: OTelLog[]) => void;\n\tonError: (err: unknown) => void;\n}) => (() => void) | undefined;\n\n/** Options for {@link fromOTel}. */\nexport type FromOTelOptions = ExtraOpts & {};\n\n/** Bundle returned by {@link fromOTel}. */\nexport type OTelBundle = {\n\ttraces: Node<OTelSpan>;\n\tmetrics: Node<OTelMetric>;\n\tlogs: Node<OTelLog>;\n};\n\n/**\n * OTLP/HTTP receiver — accepts traces, metrics, and logs as separate reactive nodes.\n *\n * The caller owns the HTTP server. `fromOTel` receives a `register` callback that\n * wires OTLP POST endpoints to the three signal handlers. Each signal type gets\n * its own `Node` so downstream can subscribe selectively.\n *\n * @param register - Wires OTLP HTTP routes to `onTraces`, `onMetrics`, `onLogs` handlers.\n * @param opts - Optional producer options.\n * @returns {@link OTelBundle} — `{ traces, metrics, logs }` nodes.\n *\n * @example\n * ```ts\n * import express from \"express\";\n * import { fromOTel } from \"@graphrefly/graphrefly-ts\";\n *\n * const app = express();\n * app.use(express.json());\n *\n * const otel = fromOTel(({ onTraces, onMetrics, onLogs }) => {\n * app.post(\"/v1/traces\", (req, res) => { onTraces(req.body.resourceSpans ?? []); res.sendStatus(200); });\n * app.post(\"/v1/metrics\", (req, res) => { onMetrics(req.body.resourceMetrics ?? []); res.sendStatus(200); });\n * app.post(\"/v1/logs\", (req, res) => { onLogs(req.body.resourceLogs ?? []); res.sendStatus(200); });\n * return () => {};\n * });\n * ```\n *\n * @category extra\n */\nexport function fromOTel(register: OTelRegister, opts?: FromOTelOptions): OTelBundle {\n\tlet registerCleanup: (() => void) | undefined;\n\tlet active = true;\n\tlet teardownCount = 0;\n\n\tconst teardownOne = () => {\n\t\tteardownCount++;\n\t\tif (teardownCount >= 3 && registerCleanup) {\n\t\t\tregisterCleanup();\n\t\t\tregisterCleanup = undefined;\n\t\t}\n\t};\n\n\tconst traces = producer<OTelSpan>(\n\t\t(_d, _a) => () => {\n\t\t\tactive = false;\n\t\t\tteardownOne();\n\t\t},\n\t\tsourceOpts(opts),\n\t);\n\tconst metrics = producer<OTelMetric>(\n\t\t(_d, _a) => () => {\n\t\t\tactive = false;\n\t\t\tteardownOne();\n\t\t},\n\t\tsourceOpts(opts),\n\t);\n\tconst logs = producer<OTelLog>(\n\t\t(_d, _a) => () => {\n\t\t\tactive = false;\n\t\t\tteardownOne();\n\t\t},\n\t\tsourceOpts(opts),\n\t);\n\n\t// Wire registration — each handler batch-emits into the corresponding node.\n\tregisterCleanup =\n\t\tregister({\n\t\t\tonTraces: (spans) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const span of spans) traces.down([[DATA, span]]);\n\t\t\t\t});\n\t\t\t},\n\t\t\tonMetrics: (ms) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const m of ms) metrics.down([[DATA, m]]);\n\t\t\t\t});\n\t\t\t},\n\t\t\tonLogs: (ls) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const l of ls) logs.down([[DATA, l]]);\n\t\t\t\t});\n\t\t\t},\n\t\t\tonError: (err) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\ttraces.down([[ERROR, err]]);\n\t\t\t\tmetrics.down([[ERROR, err]]);\n\t\t\t\tlogs.down([[ERROR, err]]);\n\t\t\t},\n\t\t}) ?? undefined;\n\n\treturn { traces, metrics, logs };\n}\n\n// ——— Syslog (RFC 5424) ———\n\n/** Parsed syslog message (RFC 5424). */\nexport type SyslogMessage = {\n\tfacility: number;\n\tseverity: number;\n\ttimestamp: string;\n\thostname: string;\n\tappName: string;\n\tprocId: string;\n\tmsgId: string;\n\tmessage: string;\n\ttimestampNs: number;\n};\n\n/** Registration callback for syslog receiver. */\nexport type SyslogRegister = (handlers: AdapterHandlers<SyslogMessage>) => (() => void) | undefined;\n\n/** Options for {@link fromSyslog}. */\nexport type FromSyslogOptions = ExtraOpts & {};\n\n/**\n * RFC 5424 syslog receiver as a reactive source.\n *\n * The caller owns the UDP/TCP socket. `fromSyslog` receives a `register` callback\n * that wires socket data events to the `emit` handler with parsed syslog messages.\n *\n * @param register - Wires socket to emit/error/complete handlers.\n * @param opts - Optional producer options.\n * @returns `Node<SyslogMessage>` — one `DATA` per syslog message.\n *\n * @example\n * ```ts\n * import dgram from \"node:dgram\";\n * import { fromSyslog, parseSyslog } from \"@graphrefly/graphrefly-ts\";\n *\n * const server = dgram.createSocket(\"udp4\");\n * const syslog$ = fromSyslog(({ emit, error }) => {\n * server.on(\"message\", (buf) => {\n * try { emit(parseSyslog(buf.toString())); }\n * catch (e) { error(e); }\n * });\n * server.bind(514);\n * return () => server.close();\n * });\n * ```\n *\n * @category extra\n */\nexport function fromSyslog(\n\tregister: SyslogRegister,\n\topts?: FromSyslogOptions,\n): Node<SyslogMessage> {\n\treturn fromWebhook<SyslogMessage>(register as WebhookRegister<SyslogMessage>, opts);\n}\n\n/**\n * Parses a raw RFC 5424 syslog line into a structured {@link SyslogMessage}.\n *\n * Format: `<PRI>VERSION TIMESTAMP HOSTNAME APP-NAME PROCID MSGID MSG`\n *\n * @category extra\n */\nexport function parseSyslog(raw: string): SyslogMessage {\n\tconst match = raw.match(/^<(\\d{1,3})>\\d?\\s*(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s*(.*)/s);\n\tif (!match) {\n\t\tconst nowNs = wallClockNs();\n\t\treturn {\n\t\t\tfacility: 1,\n\t\t\tseverity: 6,\n\t\t\ttimestamp: new Date(Math.floor(nowNs / 1_000_000)).toISOString(),\n\t\t\thostname: \"-\",\n\t\t\tappName: \"-\",\n\t\t\tprocId: \"-\",\n\t\t\tmsgId: \"-\",\n\t\t\tmessage: raw.trim(),\n\t\t\ttimestampNs: nowNs,\n\t\t};\n\t}\n\tconst pri = Number(match[1]);\n\treturn {\n\t\tfacility: pri >> 3,\n\t\tseverity: pri & 7,\n\t\ttimestamp: match[2],\n\t\thostname: match[3],\n\t\tappName: match[4],\n\t\tprocId: match[5],\n\t\tmsgId: match[6],\n\t\tmessage: (match[7] ?? \"\").trim(),\n\t\ttimestampNs: wallClockNs(),\n\t};\n}\n\n// ——— StatsD / DogStatsD ———\n\n/** Parsed StatsD metric. */\nexport type StatsDMetric = {\n\tname: string;\n\tvalue: number;\n\ttype: \"counter\" | \"gauge\" | \"timer\" | \"histogram\" | \"set\" | \"distribution\";\n\tsampleRate?: number;\n\ttags: Record<string, string>;\n\ttimestampNs: number;\n};\n\n/** Registration callback for StatsD receiver. */\nexport type StatsDRegister = (handlers: AdapterHandlers<StatsDMetric>) => (() => void) | undefined;\n\n/** Options for {@link fromStatsD}. */\nexport type FromStatsDOptions = ExtraOpts & {};\n\n/**\n * StatsD/DogStatsD UDP receiver as a reactive source.\n *\n * The caller owns the UDP socket. `fromStatsD` receives a `register` callback\n * that wires datagrams to the `emit` handler with parsed metrics.\n *\n * @param register - Wires socket to emit/error/complete handlers.\n * @param opts - Optional producer options.\n * @returns `Node<StatsDMetric>` — one `DATA` per metric line.\n *\n * @example\n * ```ts\n * import dgram from \"node:dgram\";\n * import { fromStatsD, parseStatsD } from \"@graphrefly/graphrefly-ts\";\n *\n * const server = dgram.createSocket(\"udp4\");\n * const stats$ = fromStatsD(({ emit, error }) => {\n * server.on(\"message\", (buf) => {\n * for (const line of buf.toString().split(\"\\\\n\")) {\n * if (line.trim()) {\n * try { emit(parseStatsD(line)); }\n * catch (e) { error(e); }\n * }\n * }\n * });\n * server.bind(8125);\n * return () => server.close();\n * });\n * ```\n *\n * @category extra\n */\nexport function fromStatsD(register: StatsDRegister, opts?: FromStatsDOptions): Node<StatsDMetric> {\n\treturn fromWebhook<StatsDMetric>(register as WebhookRegister<StatsDMetric>, opts);\n}\n\nconst STATSD_TYPES: Record<string, StatsDMetric[\"type\"]> = {\n\tc: \"counter\",\n\tg: \"gauge\",\n\tms: \"timer\",\n\th: \"histogram\",\n\ts: \"set\",\n\td: \"distribution\",\n};\n\n/**\n * Parses a raw StatsD/DogStatsD line into a structured {@link StatsDMetric}.\n *\n * Format: `metric.name:value|type|@sampleRate|#tag1:val1,tag2:val2`\n *\n * @category extra\n */\nexport function parseStatsD(line: string): StatsDMetric {\n\tconst parts = line.split(\"|\");\n\tconst [name, valueStr] = (parts[0] ?? \"\").split(\":\");\n\tif (!name || valueStr === undefined) {\n\t\tthrow new Error(`Invalid StatsD line: ${line}`);\n\t}\n\tconst typeCode = parts[1]?.trim() ?? \"c\";\n\tconst type = STATSD_TYPES[typeCode] ?? \"counter\";\n\t// Set type uses string identifiers (e.g. unique user IDs), not numeric values.\n\tconst value = type === \"set\" ? 0 : Number(valueStr);\n\n\tlet sampleRate: number | undefined;\n\tconst tags: Record<string, string> = {};\n\n\tfor (let i = 2; i < parts.length; i++) {\n\t\tconst part = parts[i].trim();\n\t\tif (part.startsWith(\"@\")) {\n\t\t\tsampleRate = Number(part.slice(1));\n\t\t} else if (part.startsWith(\"#\")) {\n\t\t\tfor (const tag of part.slice(1).split(\",\")) {\n\t\t\t\tconst [k, v] = tag.split(\":\");\n\t\t\t\tif (k) tags[k] = v ?? \"\";\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { name: name.trim(), value, type, sampleRate, tags, timestampNs: wallClockNs() };\n}\n\n// ——— Prometheus scrape ———\n\n/** Parsed Prometheus metric. */\nexport type PrometheusMetric = {\n\tname: string;\n\tlabels: Record<string, string>;\n\tvalue: number;\n\ttimestampMs?: number;\n\ttype?: \"counter\" | \"gauge\" | \"histogram\" | \"summary\" | \"untyped\";\n\thelp?: string;\n\ttimestampNs: number;\n};\n\n/** Options for {@link fromPrometheus}. */\nexport type FromPrometheusOptions = AsyncSourceOpts & {\n\t/** Scrape interval in nanoseconds. Default `15 * NS_PER_SEC` (15s). */\n\tintervalNs?: number;\n\t/** Request headers for the scrape. */\n\theaders?: Record<string, string>;\n\t/** Request timeout in nanoseconds. Default `10 * NS_PER_SEC` (10s). */\n\ttimeoutNs?: number;\n};\n\n/**\n * Scrapes a Prometheus `/metrics` endpoint on a reactive timer interval.\n *\n * Each scrape parses the exposition format and emits one `DATA` per metric line.\n * Uses `fromTimer` semantics internally (reactive timer source, not polling).\n *\n * @param endpoint - URL of the Prometheus metrics endpoint.\n * @param opts - Scrape interval, headers, timeout.\n * @returns `Node<PrometheusMetric>` — one `DATA` per metric per scrape.\n *\n * @example\n * ```ts\n * import { fromPrometheus } from \"@graphrefly/graphrefly-ts\";\n *\n * const prom$ = fromPrometheus(\"http://localhost:9090/metrics\", { intervalNs: 30 * NS_PER_SEC });\n * ```\n *\n * @category extra\n */\nexport function fromPrometheus(\n\tendpoint: string,\n\topts?: FromPrometheusOptions,\n): Node<PrometheusMetric> {\n\tconst {\n\t\tintervalNs = 15 * NS_PER_SEC,\n\t\theaders,\n\t\ttimeoutNs = 10 * NS_PER_SEC,\n\t\tsignal: externalSignal,\n\t\t...rest\n\t} = opts ?? {};\n\tconst intervalMs = Math.ceil(intervalNs / NS_PER_MS);\n\n\treturn producer<PrometheusMetric>((_d, a) => {\n\t\tlet active = true;\n\t\tlet running = false;\n\t\tlet timer: ReturnType<typeof setInterval> | undefined;\n\n\t\tconst cleanup = () => {\n\t\t\tactive = false;\n\t\t\tif (timer !== undefined) {\n\t\t\t\tclearInterval(timer);\n\t\t\t\ttimer = undefined;\n\t\t\t}\n\t\t};\n\n\t\tconst scrape = async () => {\n\t\t\tif (!active || running) return;\n\t\t\trunning = true;\n\t\t\tconst abort = new AbortController();\n\t\t\tconst timeoutId = setTimeout(\n\t\t\t\t() => abort.abort(new Error(\"Scrape timeout\")),\n\t\t\t\tMath.ceil(timeoutNs / NS_PER_MS),\n\t\t\t);\n\n\t\t\ttry {\n\t\t\t\tconst res = await fetch(endpoint, {\n\t\t\t\t\theaders: { Accept: \"text/plain\", ...headers },\n\t\t\t\t\tsignal: abort.signal,\n\t\t\t\t});\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\tif (!active) return;\n\t\t\t\tif (!res.ok) throw new Error(`Prometheus scrape ${res.status}: ${res.statusText}`);\n\n\t\t\t\tconst text = await res.text();\n\t\t\t\tif (!active) return;\n\n\t\t\t\tconst metrics = parsePrometheusText(text);\n\t\t\t\tfor (const m of metrics) a.emit(m);\n\t\t\t} catch (err) {\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\tif (!active) return;\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") return;\n\t\t\t\tcleanup();\n\t\t\t\ta.down([[ERROR, err]]);\n\t\t\t} finally {\n\t\t\t\trunning = false;\n\t\t\t}\n\t\t};\n\n\t\tconst onAbort = () => {\n\t\t\tif (!active) return;\n\t\t\tcleanup();\n\t\t\ta.down([[ERROR, externalSignal?.reason ?? new Error(\"Aborted\")]]);\n\t\t};\n\n\t\tif (externalSignal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn () => {};\n\t\t}\n\t\texternalSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t// Initial scrape + periodic.\n\t\tvoid scrape();\n\t\ttimer = setInterval(() => void scrape(), intervalMs);\n\n\t\treturn () => {\n\t\t\tcleanup();\n\t\t\texternalSignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/**\n * Parses Prometheus exposition format text into structured metrics.\n *\n * @category extra\n */\nexport function parsePrometheusText(text: string): PrometheusMetric[] {\n\tconst results: PrometheusMetric[] = [];\n\tconst types = new Map<string, string>();\n\tconst helps = new Map<string, string>();\n\n\tfor (const rawLine of text.split(\"\\n\")) {\n\t\tconst line = rawLine.trim();\n\t\tif (!line) continue;\n\n\t\tif (line.startsWith(\"# TYPE \")) {\n\t\t\tconst rest = line.slice(7);\n\t\t\tconst spaceIdx = rest.indexOf(\" \");\n\t\t\tif (spaceIdx > 0) {\n\t\t\t\ttypes.set(rest.slice(0, spaceIdx), rest.slice(spaceIdx + 1).trim());\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"# HELP \")) {\n\t\t\tconst rest = line.slice(7);\n\t\t\tconst spaceIdx = rest.indexOf(\" \");\n\t\t\tif (spaceIdx > 0) {\n\t\t\t\thelps.set(rest.slice(0, spaceIdx), rest.slice(spaceIdx + 1).trim());\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (line.startsWith(\"#\")) continue;\n\n\t\t// metric_name{label=\"value\"} 123 timestamp?\n\t\tlet name: string;\n\t\tlet labels: Record<string, string> = {};\n\t\tlet valueStr: string;\n\t\tlet tsStr: string | undefined;\n\n\t\tconst braceIdx = line.indexOf(\"{\");\n\t\tif (braceIdx >= 0) {\n\t\t\tname = line.slice(0, braceIdx);\n\t\t\tconst closeBrace = line.indexOf(\"}\", braceIdx);\n\t\t\tif (closeBrace < 0) continue;\n\t\t\tconst labelStr = line.slice(braceIdx + 1, closeBrace);\n\t\t\tlabels = parsePrometheusLabels(labelStr);\n\t\t\tconst after = line\n\t\t\t\t.slice(closeBrace + 1)\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\s+/);\n\t\t\tvalueStr = after[0] ?? \"\";\n\t\t\ttsStr = after[1];\n\t\t} else {\n\t\t\tconst parts = line.split(/\\s+/);\n\t\t\tname = parts[0] ?? \"\";\n\t\t\tvalueStr = parts[1] ?? \"\";\n\t\t\ttsStr = parts[2];\n\t\t}\n\n\t\tif (!name || !valueStr) continue;\n\n\t\tconst baseName = name.replace(/(_total|_count|_sum|_bucket|_created|_info)$/, \"\");\n\t\tresults.push({\n\t\t\tname,\n\t\t\tlabels,\n\t\t\tvalue: Number(valueStr),\n\t\t\ttimestampMs: tsStr ? Number(tsStr) : undefined,\n\t\t\ttype: (types.get(baseName) ?? types.get(name)) as PrometheusMetric[\"type\"],\n\t\t\thelp: helps.get(baseName) ?? helps.get(name),\n\t\t\ttimestampNs: wallClockNs(),\n\t\t});\n\t}\n\n\treturn results;\n}\n\nfunction parsePrometheusLabels(str: string): Record<string, string> {\n\tconst labels: Record<string, string> = {};\n\tconst re = /(\\w+)=\"((?:[^\"\\\\]|\\\\.)*)\"/g;\n\tlet m: RegExpExecArray | null = re.exec(str);\n\twhile (m !== null) {\n\t\tlabels[m[1]] = m[2].replace(/\\\\(.)/g, \"$1\");\n\t\tm = re.exec(str);\n\t}\n\treturn labels;\n}\n\n// ——— Kafka ———\n\n/** Duck-typed Kafka consumer (compatible with kafkajs, confluent-kafka, Pulsar KoP). */\nexport type KafkaConsumerLike = {\n\tsubscribe(opts: { topic: string; fromBeginning?: boolean }): Promise<void>;\n\trun(opts: {\n\t\teachMessage: (payload: {\n\t\t\ttopic: string;\n\t\t\tpartition: number;\n\t\t\tmessage: {\n\t\t\t\tkey: Buffer | null;\n\t\t\t\tvalue: Buffer | null;\n\t\t\t\theaders?: Record<string, Buffer | string | undefined>;\n\t\t\t\toffset: string;\n\t\t\t\ttimestamp: string;\n\t\t\t};\n\t\t}) => Promise<void>;\n\t}): Promise<void>;\n\tdisconnect(): Promise<void>;\n};\n\n/** Duck-typed Kafka producer. */\nexport type KafkaProducerLike = {\n\tsend(record: {\n\t\ttopic: string;\n\t\tmessages: Array<{\n\t\t\tkey?: string | Buffer | null;\n\t\t\tvalue: string | Buffer | null;\n\t\t\theaders?: Record<string, string | Buffer>;\n\t\t}>;\n\t}): Promise<void>;\n\tdisconnect(): Promise<void>;\n};\n\n/** Structured Kafka message. */\nexport type KafkaMessage<T = unknown> = {\n\ttopic: string;\n\tpartition: number;\n\tkey: string | null;\n\tvalue: T;\n\theaders: Record<string, string>;\n\toffset: string;\n\ttimestamp: string;\n\ttimestampNs: number;\n};\n\n/** Options for {@link fromKafka}. */\nexport type FromKafkaOptions = ExtraOpts & {\n\t/** Start from beginning of topic. Default: `false`. */\n\tfromBeginning?: boolean;\n\t/** Deserialize message value. Default: `JSON.parse(buffer.toString())`. */\n\tdeserialize?: (value: Buffer | null) => unknown;\n};\n\n/**\n * Kafka consumer as a reactive source.\n *\n * Wraps a KafkaJS-compatible consumer. Each message becomes a `DATA` emission.\n * Compatible with Pulsar via KoP (Kafka-on-Pulsar).\n *\n * @param consumer - KafkaJS-compatible consumer instance (caller owns connect/disconnect lifecycle).\n * @param topic - Topic to consume from.\n * @param opts - Deserialization and source options.\n * @returns `Node<KafkaMessage<T>>` — one `DATA` per Kafka message.\n *\n * @example\n * ```ts\n * import { Kafka } from \"kafkajs\";\n * import { fromKafka } from \"@graphrefly/graphrefly-ts\";\n *\n * const kafka = new Kafka({ brokers: [\"localhost:9092\"] });\n * const consumer = kafka.consumer({ groupId: \"my-group\" });\n * await consumer.connect();\n *\n * const events$ = fromKafka(consumer, \"events\", { deserialize: (buf) => JSON.parse(buf!.toString()) });\n * ```\n *\n * @category extra\n */\nexport function fromKafka<T = unknown>(\n\tconsumer: KafkaConsumerLike,\n\ttopic: string,\n\topts?: FromKafkaOptions,\n): Node<KafkaMessage<T>> {\n\tconst {\n\t\tfromBeginning = false,\n\t\tdeserialize = (buf: Buffer | null) => {\n\t\t\tif (buf === null) return null;\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(buf.toString());\n\t\t\t} catch {\n\t\t\t\treturn buf.toString();\n\t\t\t}\n\t\t},\n\t\t...rest\n\t} = opts ?? {};\n\n\treturn producer<KafkaMessage<T>>((_d, a) => {\n\t\tlet active = true;\n\n\t\tconst start = async () => {\n\t\t\ttry {\n\t\t\t\tawait consumer.subscribe({ topic, fromBeginning });\n\t\t\t\tawait consumer.run({\n\t\t\t\t\teachMessage: async ({ topic: t, partition, message: msg }) => {\n\t\t\t\t\t\tif (!active) return;\n\t\t\t\t\t\tconst headers: Record<string, string> = {};\n\t\t\t\t\t\tif (msg.headers) {\n\t\t\t\t\t\t\tfor (const [k, v] of Object.entries(msg.headers)) {\n\t\t\t\t\t\t\t\tif (v !== undefined) headers[k] = typeof v === \"string\" ? v : v.toString();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\ta.emit({\n\t\t\t\t\t\t\ttopic: t,\n\t\t\t\t\t\t\tpartition,\n\t\t\t\t\t\t\tkey: msg.key?.toString() ?? null,\n\t\t\t\t\t\t\tvalue: deserialize(msg.value) as T,\n\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\toffset: msg.offset,\n\t\t\t\t\t\t\ttimestamp: msg.timestamp,\n\t\t\t\t\t\t\ttimestampNs: wallClockNs(),\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tif (active) a.down([[ERROR, err]]);\n\t\t\t}\n\t\t};\n\n\t\tvoid start();\n\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/** Options for {@link toKafka}. */\nexport type ToKafkaOptions<T> = ExtraOpts & {\n\t/** Serialize value for Kafka. Default: `JSON.stringify`. */\n\tserialize?: (value: T) => string | Buffer;\n\t/** Extract message key from value. Default: `null` (no key). */\n\tkeyExtractor?: (value: T) => string | null;\n\t/** Called on serialization or send failures. */\n\tonTransportError?: (err: SinkTransportError) => void;\n};\n\n/**\n * Kafka producer sink — forwards upstream `DATA` to a Kafka topic.\n *\n * @param source - Upstream node to forward.\n * @param kafkaProducer - KafkaJS-compatible producer instance.\n * @param topic - Target topic.\n * @param opts - Serialization and key extraction options.\n * @returns Unsubscribe function.\n *\n * @category extra\n */\nexport function toKafka<T>(\n\tsource: Node<T>,\n\tkafkaProducer: KafkaProducerLike,\n\ttopic: string,\n\topts?: ToKafkaOptions<T>,\n): () => void {\n\tconst {\n\t\tserialize = (v: T) => JSON.stringify(v),\n\t\tkeyExtractor,\n\t\tonTransportError,\n\t\t...rest\n\t} = opts ?? {};\n\n\tconst inner = node([source as Node], () => undefined, {\n\t\tdescribeKind: \"effect\",\n\t\t...rest,\n\t\tonMessage(msg: Message) {\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\tconst value = msg[1] as T;\n\t\t\t\tconst key = keyExtractor?.(value) ?? null;\n\t\t\t\tlet serialized: string | Buffer;\n\t\t\t\ttry {\n\t\t\t\t\tserialized = serialize(value);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tonTransportError?.({\n\t\t\t\t\t\tstage: \"serialize\",\n\t\t\t\t\t\terror: err instanceof Error ? err : new Error(String(err)),\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tvoid kafkaProducer\n\t\t\t\t\t.send({\n\t\t\t\t\t\ttopic,\n\t\t\t\t\t\tmessages: [{ key, value: Buffer.from(serialized as string) }],\n\t\t\t\t\t})\n\t\t\t\t\t.catch((err: unknown) => {\n\t\t\t\t\t\tonTransportError?.({\n\t\t\t\t\t\t\tstage: \"send\",\n\t\t\t\t\t\t\terror: err instanceof Error ? err : new Error(String(err)),\n\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n\treturn inner.subscribe(() => {});\n}\n\n// ——— Redis Streams ———\n\n/** Duck-typed Redis client (compatible with ioredis, redis). */\nexport type RedisClientLike = {\n\txadd(key: string, id: string, ...fieldsAndValues: string[]): Promise<string>;\n\txread(\n\t\t...args: Array<string | number>\n\t): Promise<Array<[string, Array<[string, string[]]>]> | null>;\n\tdisconnect(): void;\n};\n\n/** Structured Redis Stream entry. */\nexport type RedisStreamEntry<T = unknown> = {\n\tid: string;\n\tkey: string;\n\tdata: T;\n\ttimestampNs: number;\n};\n\n/** Options for {@link fromRedisStream}. */\nexport type FromRedisStreamOptions = ExtraOpts & {\n\t/** Block timeout in ms for XREAD. Default: `5000`. */\n\tblockMs?: number;\n\t/** Start ID. Default: `\"$\"` (new entries only). */\n\tstartId?: string;\n\t/** Parse raw Redis hash fields to structured data. Default: parses `data` field as JSON. */\n\tparse?: (fields: string[]) => unknown;\n};\n\n/**\n * Redis Streams consumer as a reactive source.\n *\n * Uses XREAD with BLOCK to reactively consume stream entries.\n *\n * @param client - ioredis/redis-compatible client (caller owns connection).\n * @param key - Redis stream key.\n * @param opts - Block timeout, start ID, and parsing options.\n * @returns `Node<RedisStreamEntry<T>>` — one `DATA` per stream entry.\n *\n * @category extra\n */\nexport function fromRedisStream<T = unknown>(\n\tclient: RedisClientLike,\n\tkey: string,\n\topts?: FromRedisStreamOptions,\n): Node<RedisStreamEntry<T>> {\n\tconst {\n\t\tblockMs = 5000,\n\t\tstartId = \"$\",\n\t\tparse = (fields: string[]) => {\n\t\t\t// Redis returns flat [field, value, field, value, ...] arrays.\n\t\t\tfor (let i = 0; i < fields.length; i += 2) {\n\t\t\t\tif (fields[i] === \"data\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn JSON.parse(fields[i + 1]);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\treturn fields[i + 1];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Return as object if no \"data\" field.\n\t\t\tconst obj: Record<string, string> = {};\n\t\t\tfor (let i = 0; i < fields.length; i += 2) {\n\t\t\t\tobj[fields[i]] = fields[i + 1];\n\t\t\t}\n\t\t\treturn obj;\n\t\t},\n\t\t...rest\n\t} = opts ?? {};\n\n\treturn producer<RedisStreamEntry<T>>((_d, a) => {\n\t\tlet active = true;\n\t\tlet lastId = startId;\n\n\t\tconst poll = async () => {\n\t\t\twhile (active) {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await client.xread(\"BLOCK\", blockMs, \"STREAMS\", key, lastId);\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tfor (const [_streamKey, entries] of result) {\n\t\t\t\t\t\t\tfor (const [id, fields] of entries) {\n\t\t\t\t\t\t\t\tlastId = id;\n\t\t\t\t\t\t\t\ta.emit({\n\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\t\tdata: parse(fields) as T,\n\t\t\t\t\t\t\t\t\ttimestampNs: wallClockNs(),\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}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\ta.down([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tvoid poll();\n\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/** Options for {@link toRedisStream}. */\nexport type ToRedisStreamOptions<T> = ExtraOpts & {\n\t/** Serialize value to Redis hash fields. Default: `[\"data\", JSON.stringify(value)]`. */\n\tserialize?: (value: T) => string[];\n\t/** Max stream length (MAXLEN ~). Default: no trimming. */\n\tmaxLen?: number;\n\t/** Called on serialization or send failures. */\n\tonTransportError?: (err: SinkTransportError) => void;\n};\n\n/**\n * Redis Streams producer sink — forwards upstream `DATA` to a Redis stream.\n *\n * @param source - Upstream node to forward.\n * @param client - ioredis/redis-compatible client.\n * @param key - Redis stream key.\n * @param opts - Serialization options.\n * @returns Unsubscribe function.\n *\n * @category extra\n */\nexport function toRedisStream<T>(\n\tsource: Node<T>,\n\tclient: RedisClientLike,\n\tkey: string,\n\topts?: ToRedisStreamOptions<T>,\n): () => void {\n\tconst {\n\t\tserialize = (v: T) => [\"data\", JSON.stringify(v)],\n\t\tmaxLen,\n\t\tonTransportError,\n\t\t...rest\n\t} = opts ?? {};\n\n\tconst inner = node([source as Node], () => undefined, {\n\t\tdescribeKind: \"effect\",\n\t\t...rest,\n\t\tonMessage(msg: Message) {\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\tconst value = msg[1] as T;\n\t\t\t\tlet fields: string[];\n\t\t\t\ttry {\n\t\t\t\t\tfields = serialize(value);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tonTransportError?.({\n\t\t\t\t\t\tstage: \"serialize\",\n\t\t\t\t\t\terror: err instanceof Error ? err : new Error(String(err)),\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tconst send =\n\t\t\t\t\tmaxLen !== undefined\n\t\t\t\t\t\t? client.xadd(key, \"MAXLEN\", \"~\", String(maxLen), \"*\", ...fields)\n\t\t\t\t\t\t: client.xadd(key, \"*\", ...fields);\n\t\t\t\tvoid send.catch((err: unknown) => {\n\t\t\t\t\tonTransportError?.({\n\t\t\t\t\t\tstage: \"send\",\n\t\t\t\t\t\terror: err instanceof Error ? err : new Error(String(err)),\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n\treturn inner.subscribe(() => {});\n}\n\n// ——— CSV ingest ———\n\n/** Parsed CSV row. */\nexport type CSVRow = Record<string, string>;\n\n/** Options for {@link fromCSV}. */\nexport type FromCSVOptions = ExtraOpts & {\n\t/** Column delimiter. Default: `\",\"`. */\n\tdelimiter?: string;\n\t/** Whether the first row is a header. Default: `true`. */\n\thasHeader?: boolean;\n\t/** Explicit column names (overrides header row). */\n\tcolumns?: string[];\n\t/** Custom line parser (e.g. wrapping a library like `csv-parse`). Overrides built-in parser + delimiter. */\n\tparseLine?: (line: string) => string[];\n};\n\n/**\n * CSV file/stream ingest for batch replay.\n *\n * Reads a CSV from a `ReadableStream<string>` or an `AsyncIterable<string>` of lines,\n * emitting one `DATA` per row. `COMPLETE` after all rows are emitted.\n *\n * @param source - Async iterable of CSV text chunks (lines or multi-line chunks).\n * @param opts - Delimiter, header, and column options.\n * @returns `Node<CSVRow>` — one `DATA` per parsed row.\n *\n * @example\n * ```ts\n * import { createReadStream } from \"node:fs\";\n * import { fromCSV } from \"@graphrefly/graphrefly-ts\";\n *\n * const csv$ = fromCSV(createReadStream(\"data.csv\", \"utf-8\"));\n * ```\n *\n * @category extra\n */\nexport function fromCSV(source: AsyncIterable<string>, opts?: FromCSVOptions): Node<CSVRow> {\n\tconst {\n\t\tdelimiter = \",\",\n\t\thasHeader = true,\n\t\tcolumns: explicitColumns,\n\t\tparseLine,\n\t\t...rest\n\t} = opts ?? {};\n\tconst parse = parseLine ?? ((line: string) => parseCSVLine(line, delimiter));\n\n\treturn producer<CSVRow>((_d, a) => {\n\t\tlet cancelled = false;\n\n\t\tconst run = async () => {\n\t\t\ttry {\n\t\t\t\tlet headers: string[] | undefined = explicitColumns;\n\t\t\t\tlet buffer = \"\";\n\n\t\t\t\tfor await (const chunk of source) {\n\t\t\t\t\tif (cancelled) return;\n\t\t\t\t\tbuffer += chunk;\n\n\t\t\t\t\tconst lines = buffer.split(/\\r?\\n/);\n\t\t\t\t\t// Keep last partial line in buffer.\n\t\t\t\t\tbuffer = lines.pop() ?? \"\";\n\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tif (cancelled) return;\n\t\t\t\t\t\tif (!line.trim()) continue;\n\n\t\t\t\t\t\tconst values = parse(line);\n\n\t\t\t\t\t\tif (!headers && hasHeader) {\n\t\t\t\t\t\t\theaders = values;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!headers) {\n\t\t\t\t\t\t\theaders = values.map((_, i) => `col${i}`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst row: CSVRow = {};\n\t\t\t\t\t\tfor (let i = 0; i < headers.length; i++) {\n\t\t\t\t\t\t\trow[headers[i]] = values[i] ?? \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\ta.emit(row);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Process remaining buffer.\n\t\t\t\tif (!cancelled && buffer.trim()) {\n\t\t\t\t\tconst values = parse(buffer);\n\t\t\t\t\tif (headers) {\n\t\t\t\t\t\tconst row: CSVRow = {};\n\t\t\t\t\t\tfor (let i = 0; i < headers.length; i++) {\n\t\t\t\t\t\t\trow[headers[i]] = values[i] ?? \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\ta.emit(row);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!cancelled) a.down([[COMPLETE]]);\n\t\t\t} catch (err) {\n\t\t\t\tif (!cancelled) a.down([[ERROR, err]]);\n\t\t\t}\n\t\t};\n\n\t\tvoid run();\n\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t}, sourceOpts(rest));\n}\n\nfunction parseCSVLine(line: string, delimiter: string): string[] {\n\tconst values: string[] = [];\n\tlet current = \"\";\n\tlet inQuotes = false;\n\n\tfor (let i = 0; i < line.length; i++) {\n\t\tconst ch = line[i];\n\t\tif (inQuotes) {\n\t\t\tif (ch === '\"') {\n\t\t\t\tif (line[i + 1] === '\"') {\n\t\t\t\t\tcurrent += '\"';\n\t\t\t\t\ti++;\n\t\t\t\t} else {\n\t\t\t\t\tinQuotes = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcurrent += ch;\n\t\t\t}\n\t\t} else if (ch === '\"') {\n\t\t\tinQuotes = true;\n\t\t} else if (ch === delimiter) {\n\t\t\tvalues.push(current);\n\t\t\tcurrent = \"\";\n\t\t} else {\n\t\t\tcurrent += ch;\n\t\t}\n\t}\n\tvalues.push(current);\n\treturn values;\n}\n\n// ——— NDJSON ingest ———\n\n/** Options for {@link fromNDJSON}. */\nexport type FromNDJSONOptions = ExtraOpts & {};\n\n/**\n * Newline-delimited JSON stream ingest for batch replay.\n *\n * Reads an async iterable of text chunks, splits by newline, parses each line\n * as JSON, and emits one `DATA` per parsed object. `COMPLETE` after stream ends.\n *\n * @param source - Async iterable of NDJSON text chunks.\n * @param opts - Optional producer options.\n * @returns `Node<T>` — one `DATA` per JSON line.\n *\n * @example\n * ```ts\n * import { createReadStream } from \"node:fs\";\n * import { fromNDJSON } from \"@graphrefly/graphrefly-ts\";\n *\n * const logs$ = fromNDJSON(createReadStream(\"logs.ndjson\", \"utf-8\"));\n * ```\n *\n * @category extra\n */\nexport function fromNDJSON<T = unknown>(\n\tsource: AsyncIterable<string>,\n\topts?: FromNDJSONOptions,\n): Node<T> {\n\treturn producer<T>((_d, a) => {\n\t\tlet cancelled = false;\n\n\t\tconst run = async () => {\n\t\t\ttry {\n\t\t\t\tlet buffer = \"\";\n\n\t\t\t\tfor await (const chunk of source) {\n\t\t\t\t\tif (cancelled) return;\n\t\t\t\t\tbuffer += chunk;\n\n\t\t\t\t\tconst lines = buffer.split(/\\r?\\n/);\n\t\t\t\t\tbuffer = lines.pop() ?? \"\";\n\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tif (cancelled) return;\n\t\t\t\t\t\tconst trimmed = line.trim();\n\t\t\t\t\t\tif (!trimmed) continue;\n\t\t\t\t\t\ta.emit(JSON.parse(trimmed) as T);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Process remaining buffer.\n\t\t\t\tif (!cancelled && buffer.trim()) {\n\t\t\t\t\ta.emit(JSON.parse(buffer.trim()) as T);\n\t\t\t\t}\n\n\t\t\t\tif (!cancelled) a.down([[COMPLETE]]);\n\t\t\t} catch (err) {\n\t\t\t\tif (!cancelled) a.down([[ERROR, err]]);\n\t\t\t}\n\t\t};\n\n\t\tvoid run();\n\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t}, sourceOpts(opts));\n}\n\n// ——— ClickHouse live materialized view ———\n\n/** Structured ClickHouse query result row. */\nexport type ClickHouseRow = Record<string, unknown>;\n\n/** Duck-typed ClickHouse client. */\nexport type ClickHouseClientLike = {\n\tquery(opts: { query: string; format?: string }): Promise<{\n\t\tjson<T = unknown>(): Promise<T[]>;\n\t}>;\n};\n\n/** Options for {@link fromClickHouseWatch}. */\nexport type FromClickHouseWatchOptions = AsyncSourceOpts & {\n\t/** Polling interval in nanoseconds. Default: `5 * NS_PER_SEC` (5s). */\n\tintervalNs?: number;\n\t/** JSON format to request. Default: `\"JSONEachRow\"`. */\n\tformat?: string;\n};\n\n/**\n * ClickHouse live materialized view as a reactive source.\n *\n * Polls a ClickHouse query on a reactive timer interval and emits new/changed rows.\n * Uses a timer-driven approach (not busy-wait polling).\n *\n * @param client - ClickHouse client instance (caller owns connection).\n * @param query - SQL query to execute on each interval.\n * @param opts - Polling interval and format options.\n * @returns `Node<ClickHouseRow>` — one `DATA` per result row per scrape.\n *\n * @example\n * ```ts\n * import { createClient } from \"@clickhouse/client\";\n * import { fromClickHouseWatch } from \"@graphrefly/graphrefly-ts\";\n *\n * const client = createClient({ url: \"http://localhost:8123\" });\n * const rows$ = fromClickHouseWatch(client, \"SELECT * FROM errors_mv ORDER BY timestamp DESC LIMIT 100\");\n * ```\n *\n * @category extra\n */\nexport function fromClickHouseWatch(\n\tclient: ClickHouseClientLike,\n\tquery: string,\n\topts?: FromClickHouseWatchOptions,\n): Node<ClickHouseRow> {\n\tconst {\n\t\tintervalNs = 5 * NS_PER_SEC,\n\t\tformat = \"JSONEachRow\",\n\t\tsignal: externalSignal,\n\t\t...rest\n\t} = opts ?? {};\n\tconst intervalMs = Math.ceil(intervalNs / NS_PER_MS);\n\n\treturn producer<ClickHouseRow>((_d, a) => {\n\t\tlet active = true;\n\t\tlet running = false;\n\t\tlet timer: ReturnType<typeof setInterval> | undefined;\n\n\t\tconst cleanup = () => {\n\t\t\tactive = false;\n\t\t\tif (timer !== undefined) {\n\t\t\t\tclearInterval(timer);\n\t\t\t\ttimer = undefined;\n\t\t\t}\n\t\t};\n\n\t\tconst execute = async () => {\n\t\t\tif (!active || running) return;\n\t\t\trunning = true;\n\t\t\ttry {\n\t\t\t\tconst result = await client.query({ query, format });\n\t\t\t\tif (!active) return;\n\t\t\t\tconst rows = await result.json<ClickHouseRow>();\n\t\t\t\tif (!active) return;\n\t\t\t\tfor (const row of rows) a.emit(row);\n\t\t\t} catch (err) {\n\t\t\t\tif (!active) return;\n\t\t\t\tcleanup();\n\t\t\t\ta.down([[ERROR, err]]);\n\t\t\t} finally {\n\t\t\t\trunning = false;\n\t\t\t}\n\t\t};\n\n\t\tconst onAbort = () => {\n\t\t\tif (!active) return;\n\t\t\tcleanup();\n\t\t\ta.down([[ERROR, externalSignal?.reason ?? new Error(\"Aborted\")]]);\n\t\t};\n\n\t\tif (externalSignal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn () => {};\n\t\t}\n\t\texternalSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\tvoid execute();\n\t\ttimer = setInterval(() => void execute(), intervalMs);\n\n\t\treturn () => {\n\t\t\tcleanup();\n\t\t\texternalSignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t}, sourceOpts(rest));\n}\n","/**\n * Checkpoint adapters and {@link Graph} save/restore helpers (roadmap §3.1).\n */\n/// <reference lib=\"dom\" />\n\nimport { randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { COMPLETE, DATA, ERROR } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { producer } from \"../core/sugar.js\";\nimport type { Graph, GraphPersistSnapshot } from \"../graph/graph.js\";\n\nfunction sortJsonValue(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sortJsonValue);\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\tconst out: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tout[k] = sortJsonValue(obj[k]);\n\t}\n\treturn out;\n}\n\nfunction warnNonJsonValues(data: GraphPersistSnapshot): void {\n\tfor (const [path, node] of Object.entries(data.nodes)) {\n\t\tconst v = node.value;\n\t\tif (v === undefined || v === null) continue;\n\t\tif (typeof v === \"function\" || typeof v === \"symbol\" || typeof v === \"bigint\") {\n\t\t\tconsole.warn(\n\t\t\t\t`checkpoint: node \"${path}\" has non-JSON-serializable value (${typeof v}); it will be lost on round-trip`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction stableSnapshotJson(data: GraphPersistSnapshot): string {\n\twarnNonJsonValues(data);\n\treturn `${JSON.stringify(sortJsonValue(data), undefined, 0)}\\n`;\n}\n\n/**\n * Persists {@link GraphPersistSnapshot} blobs (single save/load contract, roadmap §3.1).\n */\nexport interface CheckpointAdapter {\n\tsave(data: GraphPersistSnapshot): void;\n\tload(): GraphPersistSnapshot | null;\n}\n\n/**\n * In-memory adapter (process-local; useful for tests).\n *\n * @category extra\n */\nexport class MemoryCheckpointAdapter implements CheckpointAdapter {\n\t#data: GraphPersistSnapshot | null = null;\n\n\tsave(data: GraphPersistSnapshot): void {\n\t\tthis.#data = JSON.parse(JSON.stringify(data)) as GraphPersistSnapshot;\n\t}\n\n\tload(): GraphPersistSnapshot | null {\n\t\treturn this.#data === null\n\t\t\t? null\n\t\t\t: (JSON.parse(JSON.stringify(this.#data)) as GraphPersistSnapshot);\n\t}\n}\n\n/**\n * Stores JSON-cloned snapshots under a key inside a caller-owned record (tests / embedding).\n *\n * @category extra\n */\nexport class DictCheckpointAdapter implements CheckpointAdapter {\n\treadonly #storage: Record<string, unknown>;\n\treadonly #key: string;\n\n\tconstructor(storage: Record<string, unknown>, key = \"graphrefly_checkpoint\") {\n\t\tthis.#storage = storage;\n\t\tthis.#key = key;\n\t}\n\n\tsave(data: GraphPersistSnapshot): void {\n\t\tthis.#storage[this.#key] = JSON.parse(JSON.stringify(data)) as Record<string, unknown>;\n\t}\n\n\tload(): GraphPersistSnapshot | null {\n\t\tconst raw = this.#storage[this.#key];\n\t\treturn raw !== null && typeof raw === \"object\" && !Array.isArray(raw)\n\t\t\t? (JSON.parse(JSON.stringify(raw)) as GraphPersistSnapshot)\n\t\t\t: null;\n\t}\n}\n\n/**\n * Atomic JSON file persistence (temp file in the target directory, then `rename`).\n *\n * @remarks\n * **Errors:** `load()` returns `null` for missing files, empty files, or invalid JSON (no throw).\n *\n * @category extra\n */\nexport class FileCheckpointAdapter implements CheckpointAdapter {\n\treadonly #path: string;\n\n\tconstructor(path: string) {\n\t\tthis.#path = path;\n\t}\n\n\tsave(data: GraphPersistSnapshot): void {\n\t\tconst dir = dirname(this.#path);\n\t\tmkdirSync(dir, { recursive: true });\n\t\tconst payload = stableSnapshotJson(data);\n\t\tconst base = basename(this.#path);\n\t\tconst tmp = join(dir, `.${base}.${randomBytes(8).toString(\"hex\")}.tmp`);\n\t\ttry {\n\t\t\twriteFileSync(tmp, payload, \"utf8\");\n\t\t\trenameSync(tmp, this.#path);\n\t\t} catch (e) {\n\t\t\ttry {\n\t\t\t\tunlinkSync(tmp);\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tload(): GraphPersistSnapshot | null {\n\t\ttry {\n\t\t\tconst text = readFileSync(this.#path, \"utf8\").trim();\n\t\t\tif (!text) return null;\n\t\t\tconst data = JSON.parse(text) as unknown;\n\t\t\treturn data !== null && typeof data === \"object\" && !Array.isArray(data)\n\t\t\t\t? (data as GraphPersistSnapshot)\n\t\t\t\t: null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n}\n\n/**\n * Persists one JSON blob under a fixed key using Node.js `node:sqlite` ({@link DatabaseSync}).\n *\n * @remarks\n * **Runtime:** Requires Node 22.5+ with `node:sqlite` enabled (experimental in some releases). Call `close()` when discarding the adapter.\n *\n * @category extra\n */\nexport class SqliteCheckpointAdapter implements CheckpointAdapter {\n\treadonly #db: DatabaseSync;\n\treadonly #key: string;\n\n\tconstructor(path: string, key = \"graphrefly_checkpoint\") {\n\t\tthis.#db = new DatabaseSync(path);\n\t\tthis.#key = key;\n\t\tthis.#db.exec(\n\t\t\t`CREATE TABLE IF NOT EXISTS graphrefly_checkpoint (k TEXT PRIMARY KEY, v TEXT NOT NULL)`,\n\t\t);\n\t}\n\n\tsave(data: GraphPersistSnapshot): void {\n\t\tconst payload = stableSnapshotJson(data).trimEnd();\n\t\tthis.#db\n\t\t\t.prepare(`INSERT OR REPLACE INTO graphrefly_checkpoint (k, v) VALUES (?, ?)`)\n\t\t\t.run(this.#key, payload);\n\t}\n\n\tload(): GraphPersistSnapshot | null {\n\t\tconst row = this.#db\n\t\t\t.prepare(`SELECT v FROM graphrefly_checkpoint WHERE k = ?`)\n\t\t\t.get(this.#key) as { v: string } | undefined;\n\t\tif (row === undefined || typeof row.v !== \"string\" || row.v.trim() === \"\") return null;\n\t\tconst parsed = JSON.parse(row.v) as unknown;\n\t\treturn parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)\n\t\t\t? (parsed as GraphPersistSnapshot)\n\t\t\t: null;\n\t}\n\n\t/** Close the underlying SQLite connection (safe to call more than once). */\n\tclose(): void {\n\t\ttry {\n\t\t\tthis.#db.close();\n\t\t} catch {\n\t\t\t/* ignore if already closed */\n\t\t}\n\t}\n}\n\n/**\n * Writes {@link Graph.snapshot} through `adapter.save`.\n *\n * @param graph - Target graph instance.\n * @param adapter - Sync persistence backend.\n * @returns `void` — side-effect only; the snapshot is written to `adapter`.\n *\n * @example\n * ```ts\n * import { saveGraphCheckpoint, MemoryCheckpointAdapter, Graph } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const adapter = new MemoryCheckpointAdapter();\n * saveGraphCheckpoint(g, adapter);\n * ```\n *\n * @category extra\n */\nexport function saveGraphCheckpoint(graph: Graph, adapter: CheckpointAdapter): void {\n\tadapter.save(graph.snapshot());\n}\n\n/**\n * Loads a snapshot via `adapter.load` and applies {@link Graph.restore} when data exists.\n *\n * @param graph - Graph whose topology matches the snapshot.\n * @param adapter - Sync persistence backend.\n * @returns `true` if data was present and `restore` ran; `false` if `load()` returned `null`.\n *\n * @example\n * ```ts\n * import {\n * saveGraphCheckpoint,\n * restoreGraphCheckpoint,\n * MemoryCheckpointAdapter,\n * Graph,\n * } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const adapter = new MemoryCheckpointAdapter();\n * saveGraphCheckpoint(g, adapter);\n *\n * const g2 = new Graph(\"app\");\n * restoreGraphCheckpoint(g2, adapter); // true\n * ```\n *\n * @category extra\n */\nexport function restoreGraphCheckpoint(graph: Graph, adapter: CheckpointAdapter): boolean {\n\tconst data = adapter.load();\n\tif (data === null) return false;\n\tgraph.restore(data);\n\treturn true;\n}\n\n/**\n * Minimal JSON-shaped payload for a single node's cached value (custom adapters).\n *\n * @param n - Any {@link Node}.\n * @returns `{ version: 1, value }` from {@link Node.get}.\n *\n * @example\n * ```ts\n * import { checkpointNodeValue, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const s = state(42);\n * checkpointNodeValue(s); // { version: 1, value: 42 }\n * ```\n *\n * @category extra\n */\nexport function checkpointNodeValue<T>(n: Node<T>): { version: number; value: T | undefined } {\n\treturn { version: 1, value: n.get() };\n}\n\nexport type IndexedDbCheckpointSpec = {\n\tdbName: string;\n\tstoreName: string;\n\t/** @default \"graphrefly_checkpoint\" */\n\tkey?: string;\n\tversion?: number;\n};\n\n/**\n * Wraps an `IDBRequest` as a one-shot reactive source.\n *\n * @param req - Request whose callbacks are converted to protocol messages.\n * @returns `Node<T>` that emits `DATA` once on success, then `COMPLETE`; emits `ERROR` on failure.\n *\n * @example\n * ```ts\n * import { fromIDBRequest } from \"@graphrefly/graphrefly-ts\";\n *\n * const req = indexedDB.open(\"myDb\", 1);\n * fromIDBRequest(req).subscribe((msgs) => console.log(msgs));\n * // Emits [[DATA, IDBDatabase], [COMPLETE]] on success\n * ```\n *\n * @category extra\n */\nexport function fromIDBRequest<T>(req: IDBRequest<T>): Node<T> {\n\treturn producer<T>((_d, a) => {\n\t\tlet done = false;\n\t\tconst clear = () => {\n\t\t\treq.onsuccess = null;\n\t\t\treq.onerror = null;\n\t\t};\n\t\treq.onsuccess = () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tclear();\n\t\t\ta.down([[DATA, req.result], [COMPLETE]]);\n\t\t};\n\t\treq.onerror = () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tclear();\n\t\t\ta.down([[ERROR, req.error ?? new Error(\"IndexedDB request failed\")]]);\n\t\t};\n\t\treturn () => {\n\t\t\tdone = true;\n\t\t\tclear();\n\t\t};\n\t});\n}\n\n/**\n * Wraps an `IDBTransaction` terminal lifecycle as a one-shot reactive source.\n *\n * @param tx - Transaction to observe.\n * @returns `Node<void>` that emits `DATA` (`undefined`) then `COMPLETE` on success; emits `ERROR` on `error`/`abort`.\n *\n * @example\n * ```ts\n * import { fromIDBTransaction } from \"@graphrefly/graphrefly-ts\";\n *\n * const db: IDBDatabase = ...; // obtained from indexedDB.open\n * const tx = db.transaction(\"store\", \"readwrite\");\n * fromIDBTransaction(tx).subscribe((msgs) => console.log(msgs));\n * // Emits [[DATA, undefined], [COMPLETE]] when the transaction commits\n * ```\n *\n * @category extra\n */\nexport function fromIDBTransaction(tx: IDBTransaction): Node<void> {\n\treturn producer<void>((_d, a) => {\n\t\tlet done = false;\n\t\tconst clear = () => {\n\t\t\ttx.oncomplete = null;\n\t\t\ttx.onerror = null;\n\t\t\ttx.onabort = null;\n\t\t};\n\t\ttx.oncomplete = () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tclear();\n\t\t\ta.down([[DATA, undefined], [COMPLETE]]);\n\t\t};\n\t\ttx.onerror = () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tclear();\n\t\t\ta.down([[ERROR, tx.error ?? new Error(\"IndexedDB transaction failed\")]]);\n\t\t};\n\t\ttx.onabort = () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tclear();\n\t\t\ta.down([[ERROR, tx.error ?? new Error(\"IndexedDB transaction aborted\")]]);\n\t\t};\n\t\treturn () => {\n\t\t\tdone = true;\n\t\t\tclear();\n\t\t};\n\t});\n}\n\nfunction openIdbNode(dbName: string, storeName: string, version: number): Node<IDBDatabase> {\n\treturn producer<IDBDatabase>((_d, a) => {\n\t\tif (typeof indexedDB === \"undefined\") {\n\t\t\ta.down([[ERROR, new TypeError(\"indexedDB is not available in this environment\")]]);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst req = indexedDB.open(dbName, version);\n\t\treq.onupgradeneeded = () => {\n\t\t\tconst db = req.result;\n\t\t\tif (!db.objectStoreNames.contains(storeName)) {\n\t\t\t\tdb.createObjectStore(storeName);\n\t\t\t}\n\t\t};\n\t\tconst unsub = fromIDBRequest(req).subscribe((msgs) => a.down(msgs));\n\t\treturn () => {\n\t\t\tunsub();\n\t\t};\n\t});\n}\n\n/**\n * Persists {@link Graph.snapshot} under `spec.key` (browser IndexedDB).\n *\n * @param graph - Graph to snapshot.\n * @param spec - Database name, object store name, optional `key` and schema `version`.\n * @returns A reactive `Node<void>` that emits `DATA` (`undefined`) then `COMPLETE` on success, or `ERROR` on failure.\n *\n * @remarks\n * **Environment:** Emits `ERROR` if `indexedDB` is undefined (e.g. Node without a polyfill).\n *\n * @example\n * ```ts\n * import { saveGraphCheckpointIndexedDb, Graph } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const save$ = saveGraphCheckpointIndexedDb(g, {\n * dbName: \"myApp\",\n * storeName: \"checkpoints\",\n * });\n * save$.subscribe((msgs) => console.log(\"saved:\", msgs));\n * ```\n *\n * @category extra\n */\nexport function saveGraphCheckpointIndexedDb(\n\tgraph: Graph,\n\tspec: IndexedDbCheckpointSpec,\n): Node<void> {\n\tconst key = spec.key ?? \"graphrefly_checkpoint\";\n\treturn producer<void>((_d, a) => {\n\t\tlet db: IDBDatabase | undefined;\n\t\tlet opUnsub: (() => void) | undefined;\n\t\tlet done = false;\n\t\tconst close = () => {\n\t\t\tif (db === undefined) return;\n\t\t\tdb.close();\n\t\t\tdb = undefined;\n\t\t};\n\t\tconst finishWith = (msgs: [symbol, unknown?][]) => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\ta.down(msgs);\n\t\t\topUnsub?.();\n\t\t\topUnsub = undefined;\n\t\t\topenUnsub();\n\t\t\tclose();\n\t\t};\n\t\tconst startWrite = () => {\n\t\t\tif (db === undefined || opUnsub !== undefined) return;\n\t\t\tconst tx = db.transaction(spec.storeName, \"readwrite\");\n\t\t\tconst store = tx.objectStore(spec.storeName);\n\t\t\tlet reqDone = false;\n\t\t\tlet txDone = false;\n\t\t\tlet reqError: unknown;\n\t\t\tlet unsubReq: (() => void) | undefined;\n\t\t\tlet unsubTx: (() => void) | undefined;\n\t\t\tconst maybeFinish = () => {\n\t\t\t\tif (reqError !== undefined) {\n\t\t\t\t\tfinishWith([[ERROR, reqError]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!reqDone || !txDone) return;\n\t\t\t\tfinishWith([[DATA, undefined], [COMPLETE]]);\n\t\t\t};\n\t\t\tunsubReq = fromIDBRequest(store.put(graph.snapshot(), key)).subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === ERROR) reqError = m[1];\n\t\t\t\t\tif (m[0] === COMPLETE || m[0] === ERROR) reqDone = true;\n\t\t\t\t}\n\t\t\t\tmaybeFinish();\n\t\t\t});\n\t\t\tunsubTx = fromIDBTransaction(tx).subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\t\tfinishWith([[ERROR, m[1]]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === COMPLETE) txDone = true;\n\t\t\t\t}\n\t\t\t\tmaybeFinish();\n\t\t\t});\n\t\t\topUnsub = () => {\n\t\t\t\tunsubReq?.();\n\t\t\t\tunsubReq = undefined;\n\t\t\t\tunsubTx?.();\n\t\t\t\tunsubTx = undefined;\n\t\t\t};\n\t\t};\n\t\tconst openUnsub = openIdbNode(spec.dbName, spec.storeName, spec.version ?? 1).subscribe(\n\t\t\t(msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\t\tdb = m[1] as IDBDatabase;\n\t\t\t\t\t\tstartWrite();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\t\tfinishWith([[ERROR, m[1]]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\treturn () => {\n\t\t\topUnsub?.();\n\t\t\topUnsub = undefined;\n\t\t\topenUnsub();\n\t\t\tclose();\n\t\t};\n\t});\n}\n\n/**\n * Loads a snapshot from IndexedDB and applies {@link Graph.restore} when present.\n *\n * @param graph - Graph whose topology matches the stored snapshot.\n * @param spec - Same `dbName` / `storeName` / `key` / `version` as save.\n * @returns A reactive `Node<boolean>`: emits `true` if a snapshot was restored, `false` if missing or not a plain object, then `COMPLETE`; or `ERROR` on I/O failure.\n *\n * @example\n * ```ts\n * import { restoreGraphCheckpointIndexedDb, Graph } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const restore$ = restoreGraphCheckpointIndexedDb(g, {\n * dbName: \"myApp\",\n * storeName: \"checkpoints\",\n * });\n * restore$.subscribe((msgs) => console.log(\"restored:\", msgs));\n * // Emits [[DATA, true], [COMPLETE]] if a snapshot was found and applied\n * ```\n *\n * @category extra\n */\nexport function restoreGraphCheckpointIndexedDb(\n\tgraph: Graph,\n\tspec: IndexedDbCheckpointSpec,\n): Node<boolean> {\n\tconst key = spec.key ?? \"graphrefly_checkpoint\";\n\treturn producer<boolean>((_d, a) => {\n\t\tlet db: IDBDatabase | undefined;\n\t\tlet reqUnsub: (() => void) | undefined;\n\t\tlet txUnsub: (() => void) | undefined;\n\t\tlet done = false;\n\t\tlet txDone = false;\n\t\tlet requestDone = false;\n\t\tlet requestValue: unknown;\n\t\tlet requestError: unknown;\n\t\tconst close = () => {\n\t\t\tif (db === undefined) return;\n\t\t\tdb.close();\n\t\t\tdb = undefined;\n\t\t};\n\t\tconst finishWith = (msgs: [symbol, unknown?][]) => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\ta.down(msgs);\n\t\t\treqUnsub?.();\n\t\t\treqUnsub = undefined;\n\t\t\ttxUnsub?.();\n\t\t\ttxUnsub = undefined;\n\t\t\topenUnsub();\n\t\t\tclose();\n\t\t};\n\t\tconst maybeEmitResult = () => {\n\t\t\tif (!requestDone || !txDone) return;\n\t\t\tif (requestError !== undefined) {\n\t\t\t\tfinishWith([[ERROR, requestError]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (requestValue === undefined || requestValue === null) {\n\t\t\t\tfinishWith([[DATA, false], [COMPLETE]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (typeof requestValue !== \"object\" || Array.isArray(requestValue)) {\n\t\t\t\tfinishWith([[DATA, false], [COMPLETE]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tgraph.restore(requestValue as GraphPersistSnapshot);\n\t\t\tfinishWith([[DATA, true], [COMPLETE]]);\n\t\t};\n\t\tconst startRead = () => {\n\t\t\tif (db === undefined || reqUnsub !== undefined || txUnsub !== undefined) return;\n\t\t\tconst tx = db.transaction(spec.storeName, \"readonly\");\n\t\t\tconst store = tx.objectStore(spec.storeName);\n\t\t\treqUnsub = fromIDBRequest(store.get(key)).subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === DATA) requestValue = m[1];\n\t\t\t\t\tif (m[0] === ERROR) requestError = m[1];\n\t\t\t\t\tif (m[0] === COMPLETE || m[0] === ERROR) requestDone = true;\n\t\t\t\t}\n\t\t\t\tmaybeEmitResult();\n\t\t\t});\n\t\t\ttxUnsub = fromIDBTransaction(tx).subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\t\tfinishWith([[ERROR, m[1]]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === COMPLETE) txDone = true;\n\t\t\t\t}\n\t\t\t\tmaybeEmitResult();\n\t\t\t});\n\t\t};\n\t\tconst openUnsub = openIdbNode(spec.dbName, spec.storeName, spec.version ?? 1).subscribe(\n\t\t\t(msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\t\tdb = m[1] as IDBDatabase;\n\t\t\t\t\t\tstartRead();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\t\tfinishWith([[ERROR, m[1]]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\treturn () => {\n\t\t\treqUnsub?.();\n\t\t\treqUnsub = undefined;\n\t\t\ttxUnsub?.();\n\t\t\ttxUnsub = undefined;\n\t\t\topenUnsub();\n\t\t\tclose();\n\t\t};\n\t});\n}\n","/**\n * Tier 1 sync operators (roadmap §2.1) and Tier 2 async/dynamic operators (roadmap §2.2) —\n * each returns a {@link Node} built with {@link node} (or {@link producer} for cold sources).\n */\n\nimport { monotonicNs } from \"../core/clock.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n} from \"../core/messages.js\";\nimport { type Node, type NodeActions, type NodeOptions, node } from \"../core/node.js\";\nimport { derived, producer } from \"../core/sugar.js\";\nimport { NS_PER_MS } from \"./backoff.js\";\nimport { fromAny, type NodeInput } from \"./sources.js\";\n\ntype ExtraOpts = Omit<NodeOptions, \"describeKind\">;\n\nfunction operatorOpts(opts?: ExtraOpts): NodeOptions {\n\treturn { describeKind: \"operator\", ...opts };\n}\n\n/**\n * Maps each settled value from `source` through `project`.\n *\n * @param source - Upstream node.\n * @param project - Transform for each value.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<R>` - Derived node emitting mapped values.\n *\n * @example\n * ```ts\n * import { map, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = map(state(2), (x) => x * 3);\n * ```\n *\n * @category extra\n */\nexport function map<T, R>(source: Node<T>, project: (value: T) => R, opts?: ExtraOpts): Node<R> {\n\treturn derived([source as Node], ([v]) => project(v as T), operatorOpts(opts));\n}\n\n/**\n * Forwards values that satisfy `predicate`; otherwise emits `RESOLVED` with no `DATA` (two-phase semantics).\n *\n * @param source - Upstream node.\n * @param predicate - Inclusion test.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Filtered node.\n *\n * @example\n * ```ts\n * import { filter, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = filter(state(1), (x) => x > 0);\n * ```\n *\n * @category extra\n */\nexport function filter<T>(\n\tsource: Node<T>,\n\tpredicate: (value: T) => boolean,\n\topts?: ExtraOpts,\n): Node<T> {\n\treturn node<T>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\tif (predicate(v as T)) return v as T;\n\t\t\ta.down([[RESOLVED]]);\n\t\t\treturn undefined;\n\t\t},\n\t\toperatorOpts(opts),\n\t);\n}\n\n/**\n * Folds each upstream value into an accumulator; emits the new accumulator every time.\n *\n * Unlike RxJS, `seed` is always required — there is no seedless mode where the first\n * value silently becomes the accumulator.\n *\n * @param source - Upstream node.\n * @param reducer - `(acc, value) => nextAcc`.\n * @param seed - Initial accumulator (required).\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<R>` - Scan node.\n *\n * @example\n * ```ts\n * import { scan, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = scan(state(1), (a, x) => a + x, 0);\n * ```\n *\n * @category extra\n */\nexport function scan<T, R>(\n\tsource: Node<T>,\n\treducer: (acc: R, value: T) => R,\n\tseed: R,\n\topts?: ExtraOpts,\n): Node<R> {\n\tlet acc = seed;\n\treturn node<R>(\n\t\t[source as Node],\n\t\t([v]) => {\n\t\t\tacc = reducer(acc, v as T);\n\t\t\treturn acc;\n\t\t},\n\t\t{ ...operatorOpts(opts), initial: seed, resetOnTeardown: true },\n\t);\n}\n\n/**\n * Reduces to one value emitted when `source` completes; if no `DATA` arrived, emits `seed`.\n *\n * Unlike RxJS, `seed` is always required. If the source completes without emitting\n * DATA, the seed value is emitted (RxJS would throw without a seed).\n *\n * @param source - Upstream node.\n * @param reducer - `(acc, value) => nextAcc`.\n * @param seed - Empty-completion default and initial accumulator (required).\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<R>` - Node that emits once on completion.\n *\n * @example\n * ```ts\n * import { reduce, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = reduce(state(1), (a, x) => a + x, 0);\n * ```\n *\n * @category extra\n */\nexport function reduce<T, R>(\n\tsource: Node<T>,\n\treducer: (acc: R, value: T) => R,\n\tseed: R,\n\topts?: ExtraOpts,\n): Node<R> {\n\tlet acc = seed;\n\tlet sawData = false;\n\treturn node<R>(\n\t\t[source as Node],\n\t\t([v]) => {\n\t\t\tsawData = true;\n\t\t\tacc = reducer(acc, v as T);\n\t\t\treturn undefined;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonResubscribe:\n\t\t\t\topts?.resubscribable === true\n\t\t\t\t\t? () => {\n\t\t\t\t\t\t\tacc = seed;\n\t\t\t\t\t\t\tsawData = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tonMessage(msg: Message, _i: number, a) {\n\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\tif (!sawData) acc = seed;\n\t\t\t\t\ta.emit(acc);\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Emits at most `count` **`DATA`** values, then **`COMPLETE`**. `RESOLVED` does not advance the counter.\n *\n * @param source - Upstream node.\n * @param count - Maximum `DATA` emissions (≤0 completes immediately).\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Limited stream.\n *\n * @example\n * ```ts\n * import { take, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = take(state(0), 3);\n * ```\n *\n * @category extra\n */\nexport function take<T>(source: Node<T>, count: number, opts?: ExtraOpts): Node<T> {\n\tif (count <= 0) {\n\t\treturn node<T>(\n\t\t\t[source as Node],\n\t\t\t(_d, a) => {\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{\n\t\t\t\t...operatorOpts(opts),\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\tonMessage(msg, _i, a) {\n\t\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\tlet taken = 0;\n\tlet done = false;\n\treturn node<T>(\n\t\t[source as Node],\n\t\t([v]) => {\n\t\t\tif (done) return undefined;\n\t\t\treturn v as T;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonResubscribe:\n\t\t\t\topts?.resubscribable === true\n\t\t\t\t\t? () => {\n\t\t\t\t\t\t\ttaken = 0;\n\t\t\t\t\t\t\tdone = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tif (msg[0] === DIRTY) return false;\n\t\t\t\tif (done) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\ttaken += 1;\n\t\t\t\t\tif (taken >= count) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\ta.emit(source.get() as T);\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === RESOLVED) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\tdone = true;\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === ERROR) {\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Skips the first `count` **`DATA`** emissions. `RESOLVED` does not advance the counter.\n *\n * @param source - Upstream node.\n * @param count - Number of `DATA` values to drop.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Skipped stream.\n *\n * @example\n * ```ts\n * import { skip, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = skip(state(0), 2);\n * ```\n *\n * @category extra\n */\nexport function skip<T>(source: Node<T>, count: number, opts?: ExtraOpts): Node<T> {\n\tlet skipped = 0;\n\treturn node<T>([source as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tonMessage(msg, _i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === DIRTY) {\n\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tskipped += 1;\n\t\t\t\tif (skipped <= count) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t} else {\n\t\t\t\t\ta.emit(msg[1]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n/**\n * Emits while `predicate` holds; on first false, sends **`COMPLETE`**.\n *\n * @param source - Upstream node.\n * @param predicate - Continuation test.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Truncated stream.\n *\n * @example\n * ```ts\n * import { takeWhile, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = takeWhile(state(1), (x) => x < 10);\n * ```\n *\n * @category extra\n */\nexport function takeWhile<T>(\n\tsource: Node<T>,\n\tpredicate: (value: T) => boolean,\n\topts?: ExtraOpts,\n): Node<T> {\n\tlet done = false;\n\treturn node<T>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\tif (done) return undefined;\n\t\t\tif (!predicate(v as T)) {\n\t\t\t\tdone = true;\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn v as T;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tif (done) {\n\t\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Forwards `source` until `notifier` matches `predicate` (default: notifier **`DATA`**), then **`COMPLETE`**.\n *\n * @param source - Main upstream.\n * @param notifier - Triggers completion when `predicate(msg)` is true.\n * @param opts - Optional {@link NodeOptions}, plus `predicate` for custom notifier matching.\n * @returns `Node<T>` - Truncated stream.\n *\n * @example\n * ```ts\n * import { producer, takeUntil, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state(1);\n * const stop = producer((_d, a) => a.emit(undefined));\n * const n = takeUntil(src, stop);\n * ```\n *\n * @category extra\n */\nexport function takeUntil<T>(\n\tsource: Node<T>,\n\tnotifier: Node,\n\topts?: ExtraOpts & { predicate?: (msg: Message) => boolean },\n): Node<T> {\n\tconst pred = opts?.predicate ?? ((m: Message) => m[0] === DATA);\n\tconst { predicate: _, ...restOpts } = opts ?? {};\n\tlet stopped = false;\n\treturn node<T>(\n\t\t[source as Node, notifier],\n\t\t([v]) => {\n\t\t\tif (stopped) return undefined;\n\t\t\treturn v as T;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(restOpts as ExtraOpts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, i, a) {\n\t\t\t\tif (stopped) {\n\t\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (i === 1) {\n\t\t\t\t\tif (pred(msg)) {\n\t\t\t\t\t\tstopped = true;\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Emits the first **`DATA`** then **`COMPLETE`** (same as `take(source, 1)`).\n *\n * @param source - Upstream node.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Single-value stream.\n *\n * @example\n * ```ts\n * import { first, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = first(state(42));\n * ```\n *\n * @category extra\n */\nexport function first<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\treturn take(source, 1, opts);\n}\n\n/**\n * Buffers values and emits the last **`DATA`** on **`COMPLETE`**; optional `defaultValue` if none arrived.\n *\n * @param source - Upstream node.\n * @param options - Optional {@link NodeOptions} and `defaultValue` when empty.\n * @returns `Node<T>` - Last-or-default node.\n *\n * @example\n * ```ts\n * import { last, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = last(state(1), { defaultValue: 0 });\n * ```\n *\n * @category extra\n */\nexport function last<T>(source: Node<T>, options?: ExtraOpts & { defaultValue?: T }): Node<T> {\n\tconst { defaultValue, ...rest } = options ?? {};\n\tconst useDefault = options != null && Object.hasOwn(options, \"defaultValue\");\n\tlet lastVal: T | undefined;\n\tlet has = false;\n\treturn node<T>(\n\t\t[source as Node],\n\t\t([v]) => {\n\t\t\tlastVal = v as T;\n\t\t\thas = true;\n\t\t\treturn undefined;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(rest),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\tif (has) {\n\t\t\t\t\t\ta.emit(lastVal as T);\n\t\t\t\t\t} else if (useDefault) {\n\t\t\t\t\t\ta.emit(defaultValue as T);\n\t\t\t\t\t}\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Emits the first value matching `predicate`, then **`COMPLETE`**.\n *\n * @param source - Upstream node.\n * @param predicate - Match test.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - First-match stream.\n *\n * @example\n * ```ts\n * import { find, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = find(state(1), (x) => x > 0);\n * ```\n *\n * @category extra\n */\nexport function find<T>(\n\tsource: Node<T>,\n\tpredicate: (value: T) => boolean,\n\topts?: ExtraOpts,\n): Node<T> {\n\treturn take(filter(source, predicate, opts), 1, opts);\n}\n\n/**\n * Emits the `index`th **`DATA`** (zero-based), then **`COMPLETE`**.\n *\n * @param source - Upstream node.\n * @param index - Zero-based emission index.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Single indexed value.\n *\n * @example\n * ```ts\n * import { elementAt, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = elementAt(state(0), 2);\n * ```\n *\n * @category extra\n */\nexport function elementAt<T>(source: Node<T>, index: number, opts?: ExtraOpts): Node<T> {\n\treturn take(skip(source, index, opts), 1, opts);\n}\n\n/**\n * Prepends `initial` as **`DATA`**, then forwards every value from `source`.\n *\n * @param source - Upstream node.\n * @param initial - Value emitted before upstream.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Prefixed stream.\n *\n * @example\n * ```ts\n * import { startWith, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = startWith(state(2), 0);\n * ```\n *\n * @category extra\n */\nexport function startWith<T>(source: Node<T>, initial: T, opts?: ExtraOpts): Node<T> {\n\tlet prepended = false;\n\treturn node<T>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\tif (!prepended) {\n\t\t\t\tprepended = true;\n\t\t\t\ta.emit(initial);\n\t\t\t}\n\t\t\ta.emit(v as T);\n\t\t\treturn undefined;\n\t\t},\n\t\toperatorOpts(opts),\n\t);\n}\n\n/**\n * Observer shape for {@link tap} — side effects for data, error, and/or complete.\n */\nexport type TapObserver<T> = {\n\tdata?: (value: T) => void;\n\terror?: (err: unknown) => void;\n\tcomplete?: () => void;\n};\n\n/**\n * Invokes side effects; values pass through unchanged.\n *\n * Accepts either a function (called on each DATA) or an observer object\n * `{ data?, error?, complete? }` for lifecycle-aware side effects.\n *\n * @param source - Upstream node.\n * @param fnOrObserver - Side effect function or observer object.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Passthrough node.\n *\n * @example\n * ```ts\n * import { tap, state } from \"@graphrefly/graphrefly-ts\";\n *\n * // Function form (DATA only)\n * tap(state(1), (x) => console.log(x));\n *\n * // Observer form (DATA + ERROR + COMPLETE)\n * tap(state(1), { data: console.log, error: console.error, complete: () => console.log(\"done\") });\n * ```\n *\n * @category extra\n */\nexport function tap<T>(\n\tsource: Node<T>,\n\tfnOrObserver: ((value: T) => void) | TapObserver<T>,\n\topts?: ExtraOpts,\n): Node<T> {\n\tif (typeof fnOrObserver === \"function\") {\n\t\treturn derived(\n\t\t\t[source as Node],\n\t\t\t([v]) => {\n\t\t\t\tfnOrObserver(v as T);\n\t\t\t\treturn v as T;\n\t\t\t},\n\t\t\toperatorOpts(opts),\n\t\t);\n\t}\n\tconst obs = fnOrObserver;\n\treturn node<T>(\n\t\t[source as Node],\n\t\t([v]) => {\n\t\t\tobs.data?.(v as T);\n\t\t\treturn v as T;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\tobs.error?.(msg[1]);\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tobs.complete?.();\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Suppresses adjacent duplicates using `equals` (default `Object.is`).\n *\n * @param source - Upstream node.\n * @param equals - Optional equality for consecutive values.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Deduped stream.\n *\n * @example\n * ```ts\n * import { distinctUntilChanged, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = distinctUntilChanged(state(1));\n * ```\n *\n * @category extra\n */\nexport function distinctUntilChanged<T>(\n\tsource: Node<T>,\n\tequals: (a: T, b: T) => boolean = Object.is,\n\topts?: ExtraOpts,\n): Node<T> {\n\treturn node<T>([source as Node], ([v]) => v as T, {\n\t\t...operatorOpts(opts),\n\t\tequals: equals as (a: unknown, b: unknown) => boolean,\n\t});\n}\n\n/**\n * Emits `[previous, current]` pairs starting after the second value (first pair uses `RESOLVED` only).\n *\n * @param source - Upstream node.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<readonly [T, T]>` - Pair stream.\n *\n * @example\n * ```ts\n * import { pairwise, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = pairwise(state(0));\n * ```\n *\n * @category extra\n */\nexport function pairwise<T>(source: Node<T>, opts?: ExtraOpts): Node<readonly [T, T]> {\n\tlet prev: T | undefined;\n\tlet hasPrev = false;\n\treturn node<readonly [T, T]>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\tconst x = v as T;\n\t\t\tif (!hasPrev) {\n\t\t\t\tprev = x;\n\t\t\t\thasPrev = true;\n\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst pair = [prev as T, x] as const;\n\t\t\tprev = x;\n\t\t\treturn pair;\n\t\t},\n\t\toperatorOpts(opts),\n\t);\n}\n\n/**\n * Combines the latest value from each dependency whenever any dep settles (combineLatest).\n *\n * @param sources - Nodes to combine (variadic).\n * @returns `Node<T>` - Tuple of latest values.\n *\n * @example\n * ```ts\n * import { combine, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = combine(state(1), state(\"a\"));\n * ```\n *\n * @remarks\n * Unlike RxJS `combineLatest`, this is named `combine`. Use the {@link combineLatest} alias\n * if you prefer the RxJS name. Seed is always required for `scan`/`reduce` (no seedless mode).\n *\n * @category extra\n */\nexport function combine<const T extends readonly unknown[]>(\n\t...sources: { [K in keyof T]: Node<T[K]> }\n): Node<T> {\n\tconst deps = [...sources] as unknown as Node[];\n\treturn node<T>(deps, (vals) => vals as unknown as T, operatorOpts());\n}\n\n/**\n * When `primary` settles, emits `[primary, latestSecondary]`. `secondary` alone updates cache only.\n *\n * @param primary - Main stream.\n * @param secondary - Latest value is paired on each primary emission.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<readonly [A, B]>` - Paired stream.\n *\n * @example\n * ```ts\n * import { state, withLatestFrom } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = withLatestFrom(state(1), state(\"x\"));\n * ```\n *\n * @category extra\n */\nexport function withLatestFrom<A, B>(\n\tprimary: Node<A>,\n\tsecondary: Node<B>,\n\topts?: ExtraOpts,\n): Node<readonly [A, B]> {\n\tlet latestB: B | undefined;\n\tlet hasB = false;\n\treturn node<readonly [A, B]>([primary as Node, secondary as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tonMessage(msg, i, a) {\n\t\t\tif (i === 1 && (msg[0] === DATA || msg[0] === RESOLVED)) {\n\t\t\t\tlatestB = secondary.get() as B;\n\t\t\t\thasB = true;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 0 && (msg[0] === DATA || msg[0] === RESOLVED)) {\n\t\t\t\tif (!hasB) {\n\t\t\t\t\tlatestB = secondary.get() as B;\n\t\t\t\t\thasB = true;\n\t\t\t\t}\n\t\t\t\ta.emit([primary.get() as A, latestB as B]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 0 && msg[0] === DIRTY) {\n\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 1 && msg[0] === DIRTY) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (msg[0] === COMPLETE || msg[0] === ERROR) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * Merges **`DATA`** from any source with correct two-phase dirty tracking. **`COMPLETE`** after **all** sources complete (spec §1.3.5).\n *\n * @param sources - Nodes to merge (variadic; empty completes immediately).\n * @returns `Node<T>` - Merged stream.\n *\n * @remarks\n * **Ordering:** DIRTY/RESOLVED rules follow multi-source semantics in `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n *\n * @example\n * ```ts\n * import { merge, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = merge(state(1), state(2));\n * ```\n *\n * @category extra\n */\nexport function merge<T>(...sources: readonly Node<T>[]): Node<T> {\n\tif (sources.length === 0) {\n\t\treturn producer<T>((_d, a) => {\n\t\t\ta.down([[COMPLETE]]);\n\t\t\treturn undefined;\n\t\t}, operatorOpts());\n\t}\n\tconst deps = sources as unknown as Node[];\n\tconst n = deps.length;\n\tlet completed = 0;\n\tlet dirtyMask = 0n;\n\tlet anyData = false;\n\treturn node<T>(deps, () => undefined, {\n\t\t...operatorOpts(),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tconst bit = 1n << BigInt(i);\n\t\t\tif (t === DIRTY) {\n\t\t\t\tconst wasClean = dirtyMask === 0n;\n\t\t\t\tdirtyMask |= bit;\n\t\t\t\tif (wasClean) {\n\t\t\t\t\tanyData = false;\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\tif (dirtyMask & bit) {\n\t\t\t\t\tdirtyMask &= ~bit;\n\t\t\t\t\tif (dirtyMask === 0n && !anyData) {\n\t\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tdirtyMask &= ~bit;\n\t\t\t\tanyData = true;\n\t\t\t\ta.emit(msg[1]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tdirtyMask &= ~bit;\n\t\t\t\tcompleted += 1;\n\t\t\t\tif (completed >= n) {\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * Zips one **`DATA`** from each source per cycle into a tuple. Only **`DATA`** enqueues (spec §1.3.3).\n *\n * @param sources - Nodes to zip (variadic).\n * @returns `Node<T>` - Zipped tuples.\n *\n * @example\n * ```ts\n * import { state, zip } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = zip(state(1), state(2));\n * ```\n *\n * @category extra\n */\nexport function zip<const T extends readonly unknown[]>(\n\t...sources: { [K in keyof T]: Node<T[K]> }\n): Node<T> {\n\tconst n = sources.length;\n\tif (n === 0) {\n\t\treturn node<T>([], () => [] as unknown as T, operatorOpts());\n\t}\n\tconst deps = [...sources] as unknown as Node[];\n\tconst queues: unknown[][] = Array.from({ length: n }, () => []);\n\tlet dirtyMask = 0n;\n\tlet anyData = false;\n\tlet active = n;\n\n\tfunction tryEmit(a: { emit(v: T): void }) {\n\t\twhile (queues.every((q) => q.length > 0)) {\n\t\t\tconst tuple = queues.map((q) => q.shift()!) as unknown as T;\n\t\t\ta.emit(tuple);\n\t\t}\n\t}\n\n\treturn node<T>(deps, () => undefined, {\n\t\t...operatorOpts(),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tconst bit = 1n << BigInt(i);\n\t\t\tif (t === DIRTY) {\n\t\t\t\tconst wasClean = dirtyMask === 0n;\n\t\t\t\tdirtyMask |= bit;\n\t\t\t\tif (wasClean) {\n\t\t\t\t\tanyData = false;\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\tif (dirtyMask & bit) {\n\t\t\t\t\tdirtyMask &= ~bit;\n\t\t\t\t\tif (dirtyMask === 0n) {\n\t\t\t\t\t\tif (anyData) {\n\t\t\t\t\t\t\ttryEmit(a);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tdirtyMask &= ~bit;\n\t\t\t\tqueues[i].push(msg[1]);\n\t\t\t\tanyData = true;\n\t\t\t\tif (dirtyMask === 0n) {\n\t\t\t\t\ttryEmit(a);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tactive -= 1;\n\t\t\t\tif (active === 0 || queues[i].length === 0) {\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * Plays all of `firstSrc`, then all of `secondSrc`. **`DATA`** from `secondSrc` during phase one is buffered until handoff.\n *\n * @param firstSrc - First segment.\n * @param secondSrc - Second segment.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Concatenated stream.\n *\n * @example\n * ```ts\n * import { concat, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = concat(state(1), state(2));\n * ```\n *\n * @category extra\n */\nexport function concat<T>(firstSrc: Node<T>, secondSrc: Node<T>, opts?: ExtraOpts): Node<T> {\n\tlet phase: 0 | 1 = 0;\n\tconst pending: unknown[] = [];\n\treturn node<T>([firstSrc as Node, secondSrc as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (phase === 0 && i === 1) {\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tpending.push(msg[1]);\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (phase === 0 && i === 0) {\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tphase = 1;\n\t\t\t\t\tfor (const v of pending) {\n\t\t\t\t\t\ta.emit(v as T);\n\t\t\t\t\t}\n\t\t\t\t\tpending.length = 0;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (phase === 1 && i === 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (phase === 1 && i === 1) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * First source to emit **`DATA`** wins; later traffic follows only the winner (Rx-style `race`).\n *\n * @param sources - Contestants (variadic; empty completes immediately; one node is identity).\n * @returns `Node<T>` - Winning stream.\n *\n * @example\n * ```ts\n * import { race, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = race(state(1), state(2));\n * ```\n *\n * @category extra\n */\nexport function race<T>(...sources: readonly Node<T>[]): Node<T> {\n\tif (sources.length === 0) {\n\t\treturn producer<T>((_d, a) => {\n\t\t\ta.down([[COMPLETE]]);\n\t\t\treturn undefined;\n\t\t}, operatorOpts());\n\t}\n\tif (sources.length === 1) {\n\t\treturn node<T>([sources[0] as Node], ([v]) => v as T, operatorOpts());\n\t}\n\tconst deps = sources as unknown as Node[];\n\tlet winner: number | null = null;\n\treturn node<T>(deps, () => undefined, {\n\t\t...operatorOpts(),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (winner !== null && i !== winner) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DATA && winner === null) {\n\t\t\t\twinner = i;\n\t\t\t\ta.emit(msg[1]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (winner !== null && i === winner) {\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\ta.emit(msg[1]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (winner === null) {\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n// --- Tier 2: async / dynamic (roadmap §2.2), all on `node` / `producer` ---\n\nfunction forwardInner<R>(inner: Node<R>, a: NodeActions, onInnerComplete: () => void): () => void {\n\tlet unsub: (() => void) | undefined;\n\tlet finished = false;\n\tlet emitted = false;\n\tconst finish = (): void => {\n\t\tif (finished) return;\n\t\tfinished = true;\n\t\tonInnerComplete();\n\t};\n\tunsub = inner.subscribe((msgs) => {\n\t\tlet sawComplete = false;\n\t\tlet sawError = false;\n\t\tconst out: Message[] = [];\n\t\tfor (const m of msgs) {\n\t\t\tif (m[0] === DATA) emitted = true;\n\t\t\tif (m[0] === COMPLETE) sawComplete = true;\n\t\t\telse {\n\t\t\t\tif (m[0] === ERROR) sawError = true;\n\t\t\t\tout.push(m);\n\t\t\t}\n\t\t}\n\t\tif (out.length > 0) a.down(out as unknown as Messages);\n\t\tif (sawError) {\n\t\t\tunsub?.();\n\t\t\tunsub = undefined;\n\t\t\tfinish();\n\t\t} else if (sawComplete) {\n\t\t\tfinish();\n\t\t}\n\t});\n\tif (!emitted && (inner.status === \"settled\" || inner.status === \"resolved\")) {\n\t\ta.emit(inner.get() as R);\n\t}\n\tif (inner.status === \"completed\" || inner.status === \"errored\") {\n\t\tfinish();\n\t}\n\treturn () => {\n\t\tunsub?.();\n\t\tunsub = undefined;\n\t};\n}\n\n/**\n * Maps each settled value to an inner node; unsubscribes the previous inner (Rx-style `switchMap`).\n *\n * @param source - Upstream node.\n * @param project - Maps each outer value to an inner source shape (`Node`, scalar, `PromiseLike`, `Iterable`, or `AsyncIterable`) coerced via {@link fromAny}.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<R>` - Emissions from the active inner subscription.\n * @example\n * ```ts\n * import { switchMap, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state(0);\n * switchMap(src, (n) => state((n as number) * 2));\n * ```\n *\n * @category extra\n */\nexport function switchMap<T, R>(\n\tsource: Node<T>,\n\tproject: (value: T) => NodeInput<R>,\n\topts?: ExtraOpts,\n): Node<R> {\n\tlet innerUnsub: (() => void) | undefined;\n\tlet sourceDone = false;\n\tlet attached = false;\n\n\tfunction clearInner(): void {\n\t\tinnerUnsub?.();\n\t\tinnerUnsub = undefined;\n\t}\n\n\tfunction attach(v: T, a: NodeActions): void {\n\t\tattached = true;\n\t\tclearInner();\n\t\tinnerUnsub = forwardInner(fromAny(project(v)), a, () => {\n\t\t\tclearInner();\n\t\t\tif (sourceDone) a.down([[COMPLETE]]);\n\t\t});\n\t}\n\n\treturn node<R>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\t// Skip if onMessage already handled the initial DATA during connect.\n\t\t\tif (!attached) attach(v as T, a);\n\t\t\treturn clearInner;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\tclearInner();\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tsourceDone = true;\n\t\t\t\t\tif (innerUnsub === undefined) a.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tattach(msg[1] as T, a);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Like {@link switchMap}, but ignores outer `DATA` while an inner subscription is active (`exhaustMap`).\n *\n * @param source - Upstream node.\n * @param project - Maps each outer value to an inner source shape (`Node`, scalar, `PromiseLike`, `Iterable`, or `AsyncIterable`) coerced via {@link fromAny}.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<R>` - Emissions from the active inner while it runs.\n * @example\n * ```ts\n * import { exhaustMap, state } from \"@graphrefly/graphrefly-ts\";\n *\n * exhaustMap(state(0), () => state(1));\n * ```\n *\n * @category extra\n */\nexport function exhaustMap<T, R>(\n\tsource: Node<T>,\n\tproject: (value: T) => NodeInput<R>,\n\topts?: ExtraOpts,\n): Node<R> {\n\tlet innerUnsub: (() => void) | undefined;\n\tlet sourceDone = false;\n\tlet attached = false;\n\n\tfunction clearInner(): void {\n\t\tinnerUnsub?.();\n\t\tinnerUnsub = undefined;\n\t}\n\n\tfunction attach(v: T, a: NodeActions): void {\n\t\tattached = true;\n\t\tinnerUnsub = forwardInner(fromAny(project(v)), a, () => {\n\t\t\tclearInner();\n\t\t\tif (sourceDone) a.down([[COMPLETE]]);\n\t\t});\n\t}\n\n\treturn node<R>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\tif (!attached && innerUnsub === undefined) attach(v as T, a);\n\t\t\treturn clearInner;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\tclearInner();\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tsourceDone = true;\n\t\t\t\t\tif (innerUnsub === undefined) a.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tif (innerUnsub !== undefined) {\n\t\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tattach(msg[1] as T, a);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Enqueues each outer value and subscribes to inners one at a time (`concatMap`).\n *\n * @param source - Upstream node.\n * @param project - Maps each outer value to an inner source shape (`Node`, scalar, `PromiseLike`, `Iterable`, or `AsyncIterable`) coerced via {@link fromAny}.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<R>` - Sequential concatenation of inner streams.\n * @example\n * ```ts\n * import { concatMap, state } from \"@graphrefly/graphrefly-ts\";\n *\n * concatMap(state(0), (n) => state((n as number) + 1));\n * ```\n *\n * @category extra\n */\nexport function concatMap<T, R>(\n\tsource: Node<T>,\n\tproject: (value: T) => NodeInput<R>,\n\topts?: ExtraOpts & { maxBuffer?: number },\n): Node<R> {\n\tconst { maxBuffer: maxBuf, ...concatNodeOpts } = opts ?? {};\n\tconst queue: T[] = [];\n\tlet innerUnsub: (() => void) | undefined;\n\tlet sourceDone = false;\n\tlet attached = false;\n\n\tfunction clearInner(): void {\n\t\tinnerUnsub?.();\n\t\tinnerUnsub = undefined;\n\t}\n\n\tfunction tryPump(a: NodeActions): void {\n\t\tif (innerUnsub !== undefined) return;\n\t\tif (queue.length === 0) {\n\t\t\tif (sourceDone) a.down([[COMPLETE]]);\n\t\t\treturn;\n\t\t}\n\t\tconst v = queue.shift()!;\n\t\tinnerUnsub = forwardInner(fromAny(project(v)), a, () => {\n\t\t\tclearInner();\n\t\t\ttryPump(a);\n\t\t});\n\t}\n\n\tfunction enqueue(v: T, a: NodeActions): void {\n\t\tattached = true;\n\t\tif (maxBuf && maxBuf > 0 && queue.length >= maxBuf) queue.shift();\n\t\tqueue.push(v);\n\t\ttryPump(a);\n\t}\n\n\treturn node<R>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\tif (!attached) enqueue(v as T, a);\n\t\t\treturn clearInner;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(concatNodeOpts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\tclearInner();\n\t\t\t\t\tqueue.length = 0;\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tsourceDone = true;\n\t\t\t\t\ttryPump(a);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tenqueue(msg[1] as T, a);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/** Options for {@link mergeMap}. */\nexport type MergeMapOptions = ExtraOpts & {\n\t/** Maximum number of concurrent inner subscriptions. Default: `Infinity` (unbounded). */\n\tconcurrent?: number;\n};\n\n/**\n * Subscribes to inner nodes in parallel (up to `concurrent`) and merges outputs (`mergeMap` / `flatMap`).\n *\n * @param source - Upstream node.\n * @param project - Maps each outer value to an inner source shape (`Node`, scalar, `PromiseLike`, `Iterable`, or `AsyncIterable`) coerced via {@link fromAny}.\n * @param opts - Optional options including `concurrent` limit.\n * @returns `Node<R>` - Merged output of all active inners; completes when the outer and every inner complete.\n * @example\n * ```ts\n * import { mergeMap, state } from \"@graphrefly/graphrefly-ts\";\n *\n * // Unbounded (default)\n * mergeMap(state(0), (n) => state((n as number) + 1));\n *\n * // Limited concurrency\n * mergeMap(state(0), (n) => state((n as number) + 1), { concurrent: 3 });\n * ```\n *\n * @category extra\n */\nexport function mergeMap<T, R>(\n\tsource: Node<T>,\n\tproject: (value: T) => NodeInput<R>,\n\topts?: MergeMapOptions,\n): Node<R> {\n\tconst { concurrent: concurrentOpt, ...mergeNodeOpts } = opts ?? {};\n\tconst maxConcurrent =\n\t\tconcurrentOpt != null && concurrentOpt > 0 ? concurrentOpt : Number.POSITIVE_INFINITY;\n\tlet active = 0;\n\tlet sourceDone = false;\n\tconst innerStops = new Set<() => void>();\n\tconst buffer: T[] = [];\n\n\tfunction tryComplete(a: NodeActions): void {\n\t\tif (sourceDone && active === 0 && buffer.length === 0) a.down([[COMPLETE]]);\n\t}\n\n\tfunction spawn(v: T, a: NodeActions): void {\n\t\tactive++;\n\t\tconst inner = fromAny(project(v));\n\t\tlet stop: (() => void) | undefined;\n\t\tconst runStop = (): void => {\n\t\t\tstop?.();\n\t\t\tif (stop !== undefined) innerStops.delete(stop);\n\t\t\tstop = undefined;\n\t\t};\n\t\tstop = inner.subscribe((msgs) => {\n\t\t\tlet sawComplete = false;\n\t\t\tconst out: Message[] = [];\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === COMPLETE) sawComplete = true;\n\t\t\t\telse out.push(m);\n\t\t\t}\n\t\t\tif (out.length > 0) a.down(out as unknown as Messages);\n\t\t\tif (sawComplete) {\n\t\t\t\trunStop();\n\t\t\t\tactive--;\n\t\t\t\tdrainBuffer(a);\n\t\t\t\ttryComplete(a);\n\t\t\t}\n\t\t});\n\t\tinnerStops.add(stop);\n\t}\n\n\tfunction drainBuffer(a: NodeActions): void {\n\t\twhile (buffer.length > 0 && active < maxConcurrent) {\n\t\t\tspawn(buffer.shift()!, a);\n\t\t}\n\t}\n\n\tfunction enqueue(v: T, a: NodeActions): void {\n\t\tif (active < maxConcurrent) {\n\t\t\tspawn(v, a);\n\t\t} else {\n\t\t\tbuffer.push(v);\n\t\t}\n\t}\n\n\tfunction clearAll(): void {\n\t\tfor (const u of innerStops) u();\n\t\tinnerStops.clear();\n\t\tactive = 0;\n\t\tbuffer.length = 0;\n\t}\n\n\tlet attached = false;\n\n\treturn node<R>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\tif (!attached) {\n\t\t\t\tattached = true;\n\t\t\t\tenqueue(v as T, a);\n\t\t\t}\n\t\t\treturn clearAll;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(mergeNodeOpts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\tclearAll();\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tsourceDone = true;\n\t\t\t\t\ttryComplete(a);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tenqueue(msg[1] as T, a);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * RxJS-named alias for {@link mergeMap} — projects each `DATA` to an inner node and merges outputs.\n *\n * @param source - Upstream node.\n * @param project - Returns an inner `Node<R>` per value.\n * @param opts - Optional concurrency cap and node options (excluding `describeKind`).\n * @returns Merged projection; behavior matches `mergeMap`.\n *\n * @example\n * ```ts\n * import { flatMap, state } from \"@graphrefly/graphrefly-ts\";\n *\n * flatMap(state(0), (n) => state(n));\n * ```\n *\n * @category extra\n */\nexport const flatMap = mergeMap;\n\n/**\n * Delays phase-2 emissions by `ms` (timers). `DIRTY` still forwards immediately.\n *\n * @param source - Upstream node.\n * @param ms - Delay in milliseconds.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Same values, shifted in time.\n * @example\n * ```ts\n * import { delay, state } from \"@graphrefly/graphrefly-ts\";\n *\n * delay(state(1), 100);\n * ```\n *\n * @category extra\n */\nexport function delay<T>(source: Node<T>, ms: number, opts?: ExtraOpts): Node<T> {\n\tconst timers = new Set<ReturnType<typeof setTimeout>>();\n\tfunction clearAll(): void {\n\t\tfor (const id of timers) clearTimeout(id);\n\t\ttimers.clear();\n\t}\n\treturn node<T>([source as Node], () => clearAll, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, _i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === DIRTY || t === ERROR || t === COMPLETE || t === PAUSE || t === RESUME) {\n\t\t\t\tif (t === COMPLETE) clearAll();\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tconst id = setTimeout(() => {\n\t\t\t\t\ttimers.delete(id);\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t}, ms);\n\t\t\t\ttimers.add(id);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * Emits the latest value only after `ms` quiet time since the last trigger (`debounce`).\n *\n * @param source - Upstream node.\n * @param ms - Quiet window in milliseconds.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Debounced stream.\n * @example\n * ```ts\n * import { debounce, state } from \"@graphrefly/graphrefly-ts\";\n *\n * debounce(state(0), 50);\n * ```\n *\n * @category extra\n */\nexport function debounce<T>(source: Node<T>, ms: number, opts?: ExtraOpts): Node<T> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet pending: T | undefined;\n\tfunction clearTimer(): void {\n\t\tif (timer !== undefined) {\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t}\n\t}\n\treturn node<T>([source as Node], () => clearTimer, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, _i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === ERROR || t === PAUSE || t === RESUME) {\n\t\t\t\tclearTimer();\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tif (timer !== undefined) {\n\t\t\t\t\tclearTimer();\n\t\t\t\t\ta.emit(pending as T);\n\t\t\t\t}\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tclearTimer();\n\t\t\t\tpending = msg[1] as T;\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\ttimer = undefined;\n\t\t\t\t\ta.emit(pending as T);\n\t\t\t\t}, ms);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\nexport type ThrottleOptions = { leading?: boolean; trailing?: boolean };\n\n/**\n * Rate-limits emissions to at most once per `ms` window (`throttleTime`).\n *\n * @param source - Upstream node.\n * @param ms - Minimum spacing in milliseconds.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`) plus `leading` / `trailing`.\n * @returns `Node<T>` - Throttled stream.\n * @example\n * ```ts\n * import { throttle, state } from \"@graphrefly/graphrefly-ts\";\n *\n * throttle(state(0), 1_000, { trailing: false });\n * ```\n *\n * @category extra\n */\nexport function throttle<T>(\n\tsource: Node<T>,\n\tms: number,\n\topts?: ExtraOpts & ThrottleOptions,\n): Node<T> {\n\tconst { leading: leadingOpt, trailing: trailingOpt, ...throttleNodeOpts } = opts ?? {};\n\tconst leading = leadingOpt !== false;\n\tconst trailing = trailingOpt === true;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst windowNs = ms * NS_PER_MS;\n\tlet lastEmitNs = -Infinity;\n\tlet pending: T | undefined;\n\tlet hasPending = false;\n\n\tfunction clearTimer(): void {\n\t\tif (timer !== undefined) {\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t}\n\t}\n\n\treturn node<T>(\n\t\t[source as Node],\n\t\t() => {\n\t\t\tclearTimer();\n\t\t\treturn undefined;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(throttleNodeOpts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR || t === COMPLETE || t === PAUSE || t === RESUME) {\n\t\t\t\t\tclearTimer();\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tconst v = msg[1] as T;\n\t\t\t\t\tconst nowNs = monotonicNs();\n\t\t\t\t\tif (leading && nowNs - lastEmitNs >= windowNs) {\n\t\t\t\t\t\tlastEmitNs = nowNs;\n\t\t\t\t\t\ta.emit(v);\n\t\t\t\t\t\tclearTimer();\n\t\t\t\t\t\tif (trailing) {\n\t\t\t\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\t\t\t\ttimer = undefined;\n\t\t\t\t\t\t\t\tif (hasPending) {\n\t\t\t\t\t\t\t\t\tlastEmitNs = monotonicNs();\n\t\t\t\t\t\t\t\t\ta.emit(pending as T);\n\t\t\t\t\t\t\t\t\thasPending = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}, ms);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tif (trailing) {\n\t\t\t\t\t\tpending = v;\n\t\t\t\t\t\thasPending = true;\n\t\t\t\t\t\tif (timer === undefined) {\n\t\t\t\t\t\t\tconst elapsedMs = (nowNs - lastEmitNs) / NS_PER_MS;\n\t\t\t\t\t\t\ttimer = setTimeout(\n\t\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\t\ttimer = undefined;\n\t\t\t\t\t\t\t\t\tif (hasPending) {\n\t\t\t\t\t\t\t\t\t\tlastEmitNs = monotonicNs();\n\t\t\t\t\t\t\t\t\t\ta.emit(pending as T);\n\t\t\t\t\t\t\t\t\t\thasPending = false;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tMath.max(0, ms - elapsedMs),\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\treturn true;\n\t\t\t\t}\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Emits the most recent source value whenever `notifier` settles (`sample`).\n *\n * @param source - Node whose latest value is sampled.\n * @param notifier - When this node settles (`DATA` / `RESOLVED`), a sample is taken.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Sampled snapshots of `source`.\n * @remarks **Undefined payload:** If `T` includes `undefined`, `get() === undefined` is treated as “no snapshot” and the operator emits `RESOLVED` instead of `DATA`.\n * @example\n * ```ts\n * import { sample, state } from \"@graphrefly/graphrefly-ts\";\n *\n * sample(state(1), state(0));\n * ```\n *\n * @category extra\n */\nexport function sample<T>(source: Node<T>, notifier: Node<unknown>, opts?: ExtraOpts): Node<T> {\n\treturn node<T>([source as Node, notifier as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === ERROR) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 1 && t === DATA) {\n\t\t\t\t// Emit the latest source value when notifier fires.\n\t\t\t\t// `undefined` is a valid value (Node<void>); always emit.\n\t\t\t\ta.emit((source as Node<T>).get() as T);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 1 && t === RESOLVED) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n/**\n * After each source `DATA`, waits `ms` then emits the latest value if another `DATA` has not arrived (`auditTime` / trailing window).\n *\n * @param source - Upstream node.\n * @param ms - Window in milliseconds after each `DATA`.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Trailing-edge sampled stream.\n * @example\n * ```ts\n * import { audit, state } from \"@graphrefly/graphrefly-ts\";\n *\n * audit(state(0), 100);\n * ```\n *\n * @category extra\n */\nexport function audit<T>(source: Node<T>, ms: number, opts?: ExtraOpts): Node<T> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet latest: T | undefined;\n\tlet has = false;\n\n\tfunction clearTimer(): void {\n\t\tif (timer !== undefined) {\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t}\n\t}\n\n\treturn node<T>([source as Node], () => clearTimer, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, _i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === ERROR || t === COMPLETE || t === PAUSE || t === RESUME) {\n\t\t\t\tclearTimer();\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tlatest = msg[1] as T;\n\t\t\t\thas = true;\n\t\t\t\tclearTimer();\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\ttimer = undefined;\n\t\t\t\t\tif (has) {\n\t\t\t\t\t\thas = false;\n\t\t\t\t\t\ta.emit(latest as T);\n\t\t\t\t\t}\n\t\t\t\t}, ms);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * Errors if no `DATA` arrives within `ms` after subscribe or after the previous `DATA`.\n *\n * @param source - Upstream node.\n * @param ms - Idle budget in milliseconds.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`) and `with` for a custom error payload.\n * @returns `Node<T>` - Pass-through with idle watchdog.\n * @example\n * ```ts\n * import { timeout, state } from \"@graphrefly/graphrefly-ts\";\n *\n * timeout(state(0), 5_000);\n * ```\n *\n * @category extra\n */\nexport function timeout<T>(\n\tsource: Node<T>,\n\tms: number,\n\topts?: ExtraOpts & { with?: unknown },\n): Node<T> {\n\tconst { with: withPayload, ...timeoutNodeOpts } = opts ?? {};\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst err = withPayload ?? new Error(\"timeout\");\n\n\tfunction arm(a: NodeActions): void {\n\t\tclearTimeout(timer);\n\t\ttimer = setTimeout(() => {\n\t\t\ttimer = undefined;\n\t\t\ta.down([[ERROR, err]]);\n\t\t}, ms);\n\t}\n\n\treturn node<T>(\n\t\t[source as Node],\n\t\t([_v], a) => {\n\t\t\tarm(a);\n\t\t\treturn () => clearTimeout(timer);\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(timeoutNodeOpts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tarm(a);\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY || t === RESOLVED) {\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Buffers source `DATA` values; flushes an array when `notifier` settles (`buffer`).\n *\n * @param source - Upstream node.\n * @param notifier - Flush trigger on each settlement.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T[]>` - Emits buffered arrays (may be empty-handled via `RESOLVED` when nothing buffered).\n * @example\n * ```ts\n * import { buffer, state } from \"@graphrefly/graphrefly-ts\";\n *\n * buffer(state(0), state(0));\n * ```\n *\n * @category extra\n */\nexport function buffer<T>(source: Node<T>, notifier: Node<unknown>, opts?: ExtraOpts): Node<T[]> {\n\tconst buf: T[] = [];\n\treturn node<T[]>([source as Node, notifier as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === ERROR) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE && i === 0) {\n\t\t\t\tif (buf.length > 0) a.emit([...buf]);\n\t\t\t\tbuf.length = 0;\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE && i === 1) {\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 0 && t === DATA) {\n\t\t\t\tbuf.push(msg[1] as T);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 1 && t === DATA) {\n\t\t\t\tif (buf.length > 0) {\n\t\t\t\t\ta.emit([...buf]);\n\t\t\t\t\tbuf.length = 0;\n\t\t\t\t} else {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 1 && t === RESOLVED) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 0 && (t === DIRTY || t === RESOLVED)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n/**\n * Batches consecutive `DATA` values into arrays of length `count` (`bufferCount` / `windowCount`).\n *\n * @param source - Upstream node.\n * @param count - Buffer size before emit; must be > 0.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T[]>` - Emits fixed-size arrays; remainder flushes on `COMPLETE`.\n * @example\n * ```ts\n * import { bufferCount, state } from \"@graphrefly/graphrefly-ts\";\n *\n * bufferCount(state(0), 3);\n * ```\n *\n * @category extra\n */\nexport function bufferCount<T>(source: Node<T>, count: number, opts?: ExtraOpts): Node<T[]> {\n\tif (count <= 0) throw new RangeError(\"bufferCount expects count > 0\");\n\tconst buf: T[] = [];\n\tlet started = false;\n\treturn node<T[]>(\n\t\t[source as Node],\n\t\t([v], a) => {\n\t\t\t// onMessage intercepts subsequent DATA; compute fn only runs on initial connect.\n\t\t\tif (!started) {\n\t\t\t\tstarted = true;\n\t\t\t\tbuf.push(v as T);\n\t\t\t\tif (buf.length >= count) {\n\t\t\t\t\ta.emit(buf.splice(0, buf.length));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tif (buf.length > 0) a.emit([...buf]);\n\t\t\t\t\tbuf.length = 0;\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tbuf.push(msg[1] as T);\n\t\t\t\t\tif (buf.length >= count) {\n\t\t\t\t\t\ta.emit(buf.splice(0, buf.length));\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Splits source `DATA` into sub-nodes of `count` values each. Each sub-node completes after `count` items or when source completes.\n *\n * @param source - Upstream node.\n * @param count - Items per window.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<Node<T>>` - Each emission is a sub-node carrying that window's values.\n *\n * @example\n * ```ts\n * import { windowCount, state } from \"@graphrefly/graphrefly-ts\";\n *\n * windowCount(state(0), 3);\n * ```\n *\n * @category extra\n */\nexport function windowCount<T>(source: Node<T>, count: number, opts?: ExtraOpts): Node<Node<T>> {\n\tif (count <= 0) throw new RangeError(\"windowCount expects count > 0\");\n\tlet win: Node<T> | undefined;\n\tlet winDown: ((msgs: Messages) => void) | undefined;\n\tlet n = 0;\n\n\tfunction openWindow(a: NodeActions): void {\n\t\tconst s = producer<T>((_d, actions) => {\n\t\t\twinDown = actions.down.bind(actions);\n\t\t\treturn () => {\n\t\t\t\twinDown = undefined;\n\t\t\t};\n\t\t}, operatorOpts());\n\t\twin = s;\n\t\tn = 0;\n\t\ta.emit(s);\n\t}\n\n\treturn node<Node<T>>([source as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, _i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (!win) openWindow(a);\n\t\t\t\twinDown?.([[DATA, msg[1]]]);\n\t\t\t\tn += 1;\n\t\t\t\tif (n >= count) {\n\t\t\t\t\twinDown?.([[COMPLETE]]);\n\t\t\t\t\twin = undefined;\n\t\t\t\t\twinDown = undefined;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\twinDown?.([[COMPLETE]]);\n\t\t\t\twin = undefined;\n\t\t\t\twinDown = undefined;\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\twinDown?.([msg]);\n\t\t\t\twin = undefined;\n\t\t\t\twinDown = undefined;\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n/**\n * Flushes buffered `DATA` values every `ms` (`bufferTime` / `windowTime`).\n *\n * @param source - Upstream node.\n * @param ms - Flush interval in milliseconds.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T[]>` - Time-windowed batches.\n * @example\n * ```ts\n * import { bufferTime, state } from \"@graphrefly/graphrefly-ts\";\n *\n * bufferTime(state(0), 250);\n * ```\n *\n * @category extra\n */\nexport function bufferTime<T>(source: Node<T>, ms: number, opts?: ExtraOpts): Node<T[]> {\n\tconst buf: T[] = [];\n\tlet iv: ReturnType<typeof setInterval> | undefined;\n\treturn node<T[]>(\n\t\t[source as Node],\n\t\t(_deps, a) => {\n\t\t\tiv = setInterval(() => {\n\t\t\t\tif (buf.length > 0) {\n\t\t\t\t\ta.emit([...buf]);\n\t\t\t\t\tbuf.length = 0;\n\t\t\t\t}\n\t\t\t}, ms);\n\t\t\treturn () => {\n\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\t\tif (buf.length > 0) a.emit([...buf]);\n\t\t\t\t\tbuf.length = 0;\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tbuf.push(msg[1] as T);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Splits source `DATA` into time-windowed sub-nodes; each window lasts `ms`.\n *\n * @param source - Upstream node.\n * @param ms - Window duration in milliseconds.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<Node<T>>` - Each emission is a sub-node carrying that window's values.\n *\n * @example\n * ```ts\n * import { windowTime, state } from \"@graphrefly/graphrefly-ts\";\n *\n * windowTime(state(0), 500);\n * ```\n *\n * @category extra\n */\nexport function windowTime<T>(source: Node<T>, ms: number, opts?: ExtraOpts): Node<Node<T>> {\n\tlet winDown: ((msgs: Messages) => void) | undefined;\n\tlet iv: ReturnType<typeof setInterval> | undefined;\n\n\tfunction closeWindow(): void {\n\t\twinDown?.([[COMPLETE]]);\n\t\twinDown = undefined;\n\t}\n\n\treturn node<Node<T>>(\n\t\t[source as Node],\n\t\t(_deps, a) => {\n\t\t\tfunction openWindow(): void {\n\t\t\t\tconst s = producer<T>((_d, actions) => {\n\t\t\t\t\twinDown = actions.down.bind(actions);\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\twinDown = undefined;\n\t\t\t\t\t};\n\t\t\t\t}, operatorOpts());\n\t\t\t\ta.emit(s);\n\t\t\t}\n\t\t\topenWindow();\n\t\t\tiv = setInterval(() => {\n\t\t\t\tcloseWindow();\n\t\t\t\topenWindow();\n\t\t\t}, ms);\n\t\t\treturn () => {\n\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\tcloseWindow();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...operatorOpts(opts),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tonMessage(msg, _i, a) {\n\t\t\t\tconst t = msg[0];\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\twinDown?.([[DATA, msg[1]]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === COMPLETE) {\n\t\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\t\tcloseWindow();\n\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === ERROR) {\n\t\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\t\twinDown?.([msg]);\n\t\t\t\t\tcloseWindow();\n\t\t\t\t\ta.down([msg]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\ta.down([[DIRTY]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (t === RESOLVED) {\n\t\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t},\n\t);\n}\n\n/**\n * Splits source `DATA` into sub-nodes, opening a new window each time `notifier` emits `DATA`.\n *\n * @param source - Upstream node.\n * @param notifier - Each `DATA` from `notifier` closes the current window and opens a new one.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<Node<T>>` - Each emission is a sub-node carrying that window's values.\n *\n * @example\n * ```ts\n * import { state, window } from \"@graphrefly/graphrefly-ts\";\n *\n * window(state(0), state(0));\n * ```\n *\n * @category extra\n */\nexport function window<T>(\n\tsource: Node<T>,\n\tnotifier: Node<unknown>,\n\topts?: ExtraOpts,\n): Node<Node<T>> {\n\tlet win: Node<T> | undefined;\n\tlet winDown: ((msgs: Messages) => void) | undefined;\n\n\tfunction closeWindow(): void {\n\t\twinDown?.([[COMPLETE]]);\n\t\twin = undefined;\n\t\twinDown = undefined;\n\t}\n\n\treturn node<Node<T>>([source as Node, notifier as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (i === 0 && t === DATA) {\n\t\t\t\tif (!win) {\n\t\t\t\t\tconst s = producer<T>((_d, actions) => {\n\t\t\t\t\t\twinDown = actions.down.bind(actions);\n\t\t\t\t\t\treturn () => {\n\t\t\t\t\t\t\twinDown = undefined;\n\t\t\t\t\t\t};\n\t\t\t\t\t}, operatorOpts());\n\t\t\t\t\twin = s;\n\t\t\t\t\ta.emit(s);\n\t\t\t\t}\n\t\t\t\twinDown?.([[DATA, msg[1]]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 1 && t === DATA) {\n\t\t\t\tcloseWindow();\n\t\t\t\tconst s = producer<T>((_d, actions) => {\n\t\t\t\t\twinDown = actions.down.bind(actions);\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\twinDown = undefined;\n\t\t\t\t\t};\n\t\t\t\t}, operatorOpts());\n\t\t\t\twin = s;\n\t\t\t\ta.emit(s);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE && i === 0) {\n\t\t\t\tcloseWindow();\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE && i === 1) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\twinDown?.([msg]);\n\t\t\t\twin = undefined;\n\t\t\t\twinDown = undefined;\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 0 && (t === DIRTY || t === RESOLVED)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (i === 1 && t === RESOLVED) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t});\n}\n\n/**\n * Increments on each tick (`interval`); uses `setInterval` via {@link producer}.\n *\n * @param periodMs - Time between ticks.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<number>` - Emits `0`, `1`, `2`, … while subscribed.\n * @example\n * ```ts\n * import { interval } from \"@graphrefly/graphrefly-ts\";\n *\n * interval(1_000);\n * ```\n *\n * @category extra\n */\nexport function interval(periodMs: number, opts?: ExtraOpts): Node<number> {\n\tlet n = 0;\n\treturn producer<number>((_d, a) => {\n\t\tconst id = setInterval(() => {\n\t\t\ta.emit(n);\n\t\t\tn += 1;\n\t\t}, periodMs);\n\t\treturn () => clearInterval(id);\n\t}, operatorOpts(opts));\n}\n\n/**\n * Subscribes to `source` repeatedly (`count` times, sequentially). Best with a fresh or `resubscribable` source.\n *\n * @param source - Upstream node to replay.\n * @param count - Number of subscription rounds.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Forwards each round then completes after the last inner `COMPLETE`.\n * @example\n * ```ts\n * import { repeat, state } from \"@graphrefly/graphrefly-ts\";\n *\n * repeat(state(1, { resubscribable: true }), 2);\n * ```\n *\n * @category extra\n */\nexport function repeat<T>(source: Node<T>, count: number, opts?: ExtraOpts): Node<T> {\n\tif (count <= 0) throw new RangeError(\"repeat expects count > 0\");\n\treturn producer<T>((_d, a) => {\n\t\tlet remaining = count;\n\t\tlet innerU: (() => void) | undefined;\n\n\t\tconst start = (): void => {\n\t\t\tinnerU?.();\n\t\t\tinnerU = source.subscribe((msgs) => {\n\t\t\t\tlet completed = false;\n\t\t\t\tconst fwd: Message[] = [];\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === COMPLETE) completed = true;\n\t\t\t\t\telse fwd.push(m);\n\t\t\t\t}\n\t\t\t\tif (fwd.length > 0) a.down(fwd as unknown as Messages);\n\t\t\t\tif (completed) {\n\t\t\t\t\tinnerU?.();\n\t\t\t\t\tinnerU = undefined;\n\t\t\t\t\tremaining -= 1;\n\t\t\t\t\tif (remaining > 0) start();\n\t\t\t\t\telse a.down([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\n\t\tstart();\n\t\treturn () => {\n\t\t\tinnerU?.();\n\t\t};\n\t}, operatorOpts(opts));\n}\n\n/**\n * While `PAUSE` is in effect, buffers `DIRTY` / `DATA` / `RESOLVED`; flushes on `RESUME`.\n *\n * @param source - Upstream node.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Pass-through with pause buffering.\n * @example\n * ```ts\n * import { pausable, state, PAUSE, RESUME } from \"@graphrefly/graphrefly-ts\";\n *\n * const s = state(0);\n * pausable(s);\n * s.down([[PAUSE]]);\n * s.down([[RESUME]]);\n * ```\n *\n * @category extra\n */\nexport function pausable<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\tlet paused = false;\n\tconst backlog: Message[] = [];\n\n\treturn node<T>([source as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, _i, a) {\n\t\t\tconst t = msg[0];\n\t\t\tif (t === PAUSE) {\n\t\t\t\tpaused = true;\n\t\t\t\ta.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESUME) {\n\t\t\t\tpaused = false;\n\t\t\t\ta.down([msg]);\n\t\t\t\tfor (const m of backlog) a.down([m]);\n\t\t\t\tbacklog.length = 0;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (paused && (t === DIRTY || t === DATA || t === RESOLVED)) {\n\t\t\t\tbacklog.push(msg);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * Replaces an upstream `ERROR` with a recovered value (`catchError`-style).\n *\n * @param source - Upstream node.\n * @param recover - Maps the error payload to a replacement value; if it throws, `ERROR` is forwarded.\n * @param opts - Optional {@link NodeOptions} (excluding `describeKind`).\n * @returns `Node<T>` - Recovered stream.\n * @example\n * ```ts\n * import { rescue, state } from \"@graphrefly/graphrefly-ts\";\n *\n * rescue(state(0), () => 0);\n * ```\n *\n * @category extra\n */\nexport function rescue<T>(\n\tsource: Node<T>,\n\trecover: (err: unknown) => T,\n\topts?: ExtraOpts,\n): Node<T> {\n\treturn node<T>([source as Node], () => undefined, {\n\t\t...operatorOpts(opts),\n\t\tcompleteWhenDepsComplete: false,\n\t\tonMessage(msg, _i, a) {\n\t\t\tif (msg[0] === ERROR) {\n\t\t\t\ttry {\n\t\t\t\t\ta.emit(recover(msg[1]));\n\t\t\t\t} catch (err) {\n\t\t\t\t\ta.down([[ERROR, err]]);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ta.down([msg]);\n\t\t\treturn true;\n\t\t},\n\t});\n}\n\n/**\n * Forwards upstream `DATA` only while `control.get()` is truthy; when closed, emits `RESOLVED`\n * instead of repeating the last value (value-level gate). For protocol pause/resume, use {@link pausable}.\n *\n * @param source - Upstream value node.\n * @param control - Boolean node; when falsy, output stays “closed” for that tick.\n * @param opts - Optional node options (excluding `describeKind`).\n * @returns `Node<T>` gated by `control`.\n *\n * @example\n * ```ts\n * import { gate, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const data = state(1);\n * const open = state(true);\n * gate(data, open);\n * ```\n *\n * @category extra\n */\nexport function gate<T>(source: Node<T>, control: Node<boolean>, opts?: ExtraOpts): Node<T> {\n\treturn node<T>(\n\t\t[source as Node, control as Node],\n\t\t(_deps, a) => {\n\t\t\tconst v = (source as Node).get();\n\t\t\tconst c = (control as Node).get();\n\t\t\tif (!c) {\n\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn v as T;\n\t\t},\n\t\toperatorOpts(opts),\n\t);\n}\n\n// ——————————————————————————————————————————————————————————————\n// RxJS-compatible aliases — improve AI code-generation accuracy\n// ——————————————————————————————————————————————————————————————\n\n/**\n * RxJS-named alias for {@link combine} — emits when any dep updates with latest tuple of values.\n *\n * @param sources - Upstream nodes as separate arguments (same calling shape as `combine`).\n * @returns Combined node; signature matches `combine`.\n *\n * @example\n * ```ts\n * import { combineLatest, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = combineLatest(state(1), state(\"a\"));\n * ```\n *\n * @category extra\n */\nexport const combineLatest = combine;\n\n/**\n * RxJS-named alias for {@link debounce} — drops rapid `DATA` until `ms` of quiet.\n *\n * @param source - Upstream node.\n * @param ms - Quiet period in milliseconds.\n * @param opts - Optional node options (excluding `describeKind`).\n * @returns Debounced node; behavior matches `debounce`.\n *\n * @example\n * ```ts\n * import { debounceTime, state } from \"@graphrefly/graphrefly-ts\";\n *\n * debounceTime(state(0), 100);\n * ```\n *\n * @category extra\n */\nexport const debounceTime = debounce;\n\n/**\n * RxJS-named alias for {@link throttle} — emits on leading/trailing edges within `ms`.\n *\n * @param source - Upstream node.\n * @param ms - Minimum spacing in milliseconds.\n * @param opts - Optional throttle shape (`leading` / `trailing`) and node options.\n * @returns Throttled node; behavior matches `throttle`.\n *\n * @example\n * ```ts\n * import { throttleTime, state } from \"@graphrefly/graphrefly-ts\";\n *\n * throttleTime(state(0), 100);\n * ```\n *\n * @category extra\n */\nexport const throttleTime = throttle;\n\n/**\n * RxJS-named alias for {@link rescue} — replaces upstream `ERROR` with a recovered value.\n *\n * @param source - Upstream node.\n * @param recover - Maps error payload to replacement value.\n * @param opts - Optional node options (excluding `describeKind`).\n * @returns Recovered stream; behavior matches `rescue`.\n *\n * @example\n * ```ts\n * import { catchError, state } from \"@graphrefly/graphrefly-ts\";\n *\n * catchError(state(0), () => 0);\n * ```\n *\n * @category extra\n */\nexport const catchError = rescue;\n","/**\n * Reactive key–value map (roadmap §3.2) — versioned snapshots (`reactive-base`) and a manual\n * {@link state} node.\n */\nimport { batch } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node, NodeOptions } from \"../core/node.js\";\nimport { state } from \"../core/sugar.js\";\nimport { bumpVersion, snapshotEqualsVersion, type Versioned } from \"./reactive-base.js\";\n\ntype MapEntry<V> = { value: V; expiresAt?: number };\n\nexport type ReactiveMapSnapshot<K, V> = Versioned<{ map: ReadonlyMap<K, V> }>;\n\nexport type ReactiveMapOptions = {\n\t/** Optional registry name for `describe()` / debugging. */\n\tname?: string;\n\t/** When set, evicts least-recently-used keys after inserts that exceed this size. */\n\tmaxSize?: number;\n\t/** Default TTL in seconds. Used when `set` omits per-call `ttl`. */\n\tdefaultTtl?: number;\n} & Omit<NodeOptions, \"initial\" | \"describeKind\" | \"equals\">;\n\nexport type ReactiveMapBundle<K, V> = {\n\t/** Emits {@link ReactiveMapSnapshot} on each structural change (two-phase). */\n\tnode: Node<ReactiveMapSnapshot<K, V>>;\n\tget: (key: K) => V | undefined;\n\tset: (key: K, value: V, opts?: { ttl?: number }) => void;\n\tdelete: (key: K) => void;\n\tclear: () => void;\n\thas: (key: K) => boolean;\n\treadonly size: number;\n\t/** Removes expired entries (monotonic clock), emitting if the visible map changes. */\n\tpruneExpired: () => void;\n};\n\nfunction emptySnapshot<K, V>(): ReactiveMapSnapshot<K, V> {\n\treturn { version: 0, value: { map: new Map() } };\n}\n\nfunction isExpired(e: MapEntry<unknown>, now: number): boolean {\n\treturn e.expiresAt !== undefined && now >= e.expiresAt;\n}\n\nfunction buildMap<K, V>(store: Map<K, MapEntry<V>>, now: number): Map<K, V> {\n\tconst out = new Map<K, V>();\n\tfor (const [k, e] of store) {\n\t\tif (!isExpired(e, now)) out.set(k, e.value);\n\t}\n\treturn out;\n}\n\n/**\n * Creates a reactive `Map` with optional per-key TTL and optional LRU max size.\n *\n * @param options - Node options plus `maxSize` / `defaultTtl` (seconds).\n * @returns `ReactiveMapBundle` — imperative `get` / `set` / `delete` / `clear` / `pruneExpired` and a `node` emitting versioned readonly map snapshots.\n *\n * @remarks\n * **TTL:** Expiry is checked on `get`, `has`, `size`, `pruneExpired`, and before each\n * snapshot emission (expired keys are pruned first). There is no\n * background timer; monotonic-clock–expired keys may still appear in the last-emitted\n * snapshot on `node` until a read or `pruneExpired` removes them.\n * Uses `monotonicNs()` — immune to wall-clock adjustments.\n *\n * **LRU:** Uses native `Map` insertion order — `get` / `has` refreshes position; under\n * `maxSize` pressure the first key in iteration order is evicted. When `maxSize` is\n * omitted or is less than 1, no size-based eviction runs.\n *\n * @example\n * ```ts\n * import { reactiveMap } from \"@graphrefly/graphrefly-ts\";\n *\n * const m = reactiveMap<string, number>({ name: \"cache\", maxSize: 100, defaultTtl: 60 });\n * m.set(\"x\", 1);\n * m.node.subscribe((msgs) => {\n * console.log(msgs);\n * });\n * ```\n *\n * @category extra\n */\nexport function reactiveMap<K, V>(options: ReactiveMapOptions = {}): ReactiveMapBundle<K, V> {\n\tconst { name, maxSize, defaultTtl, ...nodeOpts } = options;\n\tconst store = new Map<K, MapEntry<V>>();\n\n\tlet current = emptySnapshot<K, V>();\n\n\tconst n = state<ReactiveMapSnapshot<K, V>>(current, {\n\t\t...nodeOpts,\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: snapshotEqualsVersion,\n\t});\n\n\tfunction pruneExpiredInternal(): boolean {\n\t\tconst now = monotonicNs();\n\t\tlet removed = false;\n\t\tfor (const [k, e] of store) {\n\t\t\tif (isExpired(e, now)) {\n\t\t\t\tstore.delete(k);\n\t\t\t\tremoved = true;\n\t\t\t}\n\t\t}\n\t\treturn removed;\n\t}\n\n\tfunction evictLruWhileOver(): void {\n\t\tif (maxSize === undefined || maxSize < 1) return;\n\t\twhile (store.size > maxSize) {\n\t\t\tconst first = store.keys().next().value as K | undefined;\n\t\t\tif (first === undefined) break;\n\t\t\tstore.delete(first);\n\t\t}\n\t}\n\n\tfunction pushSnapshot(): void {\n\t\tpruneExpiredInternal();\n\t\tconst now = monotonicNs();\n\t\tconst map = buildMap(store, now) as ReadonlyMap<K, V>;\n\t\tconst nv = n.v;\n\t\tcurrent = bumpVersion(current, { map }, nv ? { id: nv.id, version: nv.version } : undefined);\n\t\tbatch(() => {\n\t\t\tn.down([[DIRTY]]);\n\t\t\tn.down([[DATA, current]]);\n\t\t});\n\t}\n\n\tfunction touchLru(key: K): void {\n\t\tconst e = store.get(key);\n\t\tif (e === undefined) return;\n\t\tstore.delete(key);\n\t\tstore.set(key, e);\n\t}\n\n\tconst bundle: ReactiveMapBundle<K, V> = {\n\t\tnode: n,\n\n\t\tget(key: K): V | undefined {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst e = store.get(key);\n\t\t\tif (e === undefined) return undefined;\n\t\t\tif (isExpired(e, now)) {\n\t\t\t\tstore.delete(key);\n\t\t\t\tpushSnapshot();\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\ttouchLru(key);\n\t\t\treturn e.value;\n\t\t},\n\n\t\tset(key: K, value: V, setOpts?: { ttl?: number }): void {\n\t\t\tpruneExpiredInternal();\n\t\t\tconst ttlSec = setOpts?.ttl ?? defaultTtl;\n\t\t\tif (ttlSec !== undefined && ttlSec <= 0) {\n\t\t\t\tthrow new RangeError(`reactiveMap: ttl must be positive (got ${ttlSec})`);\n\t\t\t}\n\t\t\tconst expiresAt = ttlSec !== undefined ? monotonicNs() + ttlSec * 1_000_000_000 : undefined;\n\t\t\tif (store.has(key)) store.delete(key);\n\t\t\tstore.set(key, { value, expiresAt });\n\t\t\tevictLruWhileOver();\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tdelete(key: K): void {\n\t\t\tif (!store.delete(key)) return;\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tclear(): void {\n\t\t\tif (store.size === 0) return;\n\t\t\tstore.clear();\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\thas(key: K): boolean {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst e = store.get(key);\n\t\t\tif (e === undefined) return false;\n\t\t\tif (isExpired(e, now)) {\n\t\t\t\tstore.delete(key);\n\t\t\t\tpushSnapshot();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttouchLru(key);\n\t\t\treturn true;\n\t\t},\n\n\t\tget size(): number {\n\t\t\tpruneExpiredInternal();\n\t\t\treturn store.size;\n\t\t},\n\n\t\tpruneExpired(): void {\n\t\t\tif (!pruneExpiredInternal()) return;\n\t\t\tpushSnapshot();\n\t\t},\n\t};\n\n\treturn bundle;\n}\n","/**\n * Composite data patterns (roadmap §3.2b).\n *\n * These helpers compose existing primitives (`node`, `switchMap`, `reactiveMap`,\n * `dynamicNode`, `fromAny`) without introducing new protocol semantics.\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { dynamicNode } from \"../core/dynamic-node.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node, NodeOptions } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { merge, switchMap } from \"./operators.js\";\nimport { type ReactiveMapBundle, type ReactiveMapOptions, reactiveMap } from \"./reactive-map.js\";\nimport { forEach, fromAny, type NodeInput } from \"./sources.js\";\n\nfunction isNodeLike<T>(value: unknown): value is Node<T> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\ttypeof (value as Node<T>).get === \"function\" &&\n\t\ttypeof (value as Node<T>).subscribe === \"function\"\n\t);\n}\n\n/**\n * Verification payload shape is intentionally user-defined.\n */\nexport type VerifyValue = unknown;\n\nexport type VerifiableOptions<TVerify = VerifyValue> = Omit<\n\tNodeOptions,\n\t\"describeKind\" | \"initial\"\n> & {\n\t/** Reactive re-verification trigger. */\n\ttrigger?: NodeInput<unknown>;\n\t/** Re-run verification whenever `source` settles. */\n\tautoVerify?: boolean;\n\t/** Initial verification companion value. */\n\tinitialVerified?: TVerify | null;\n};\n\nexport type VerifiableBundle<T, TVerify = VerifyValue> = {\n\t/** Coerced source node. */\n\tnode: Node<T>;\n\t/** Latest verification result (`null` before first verification). */\n\tverified: Node<TVerify | null>;\n\t/** Effective trigger node used for verification, if any. */\n\ttrigger: Node<unknown> | null;\n};\n\n/**\n * Composes a value node with a reactive verification companion.\n *\n * Uses `switchMap` so newer triggers cancel stale in-flight verification work.\n */\nexport function verifiable<T, TVerify = VerifyValue>(\n\tsource: NodeInput<T>,\n\tverifyFn: (value: T) => NodeInput<TVerify>,\n\topts?: VerifiableOptions<TVerify>,\n): VerifiableBundle<T, TVerify> {\n\tconst sourceNode = fromAny(source);\n\tconst hasSourceVersioning = sourceNode.v != null;\n\tconst verified = state<TVerify | null>(opts?.initialVerified ?? null, {\n\t\t...(hasSourceVersioning ? { meta: { sourceVersion: null } } : {}),\n\t});\n\tconst hasTrigger = opts?.trigger !== undefined && opts.trigger !== null;\n\n\tlet triggerNode: Node<unknown> | null = null;\n\tif (hasTrigger && opts?.autoVerify) {\n\t\ttriggerNode = merge(fromAny(opts.trigger) as Node<unknown>, sourceNode as Node<unknown>);\n\t} else if (hasTrigger) {\n\t\ttriggerNode = fromAny(opts.trigger);\n\t} else if (opts?.autoVerify) {\n\t\ttriggerNode = sourceNode as Node<unknown>;\n\t}\n\n\tif (triggerNode !== null) {\n\t\tconst verifyStream = switchMap(triggerNode, () => verifyFn(sourceNode.get() as T));\n\t\tforEach(verifyStream, (value) => {\n\t\t\tbatch(() => {\n\t\t\t\tverified.down([[DATA, value]]);\n\t\t\t\t// V0 backfill: stamp which source version was verified (§6.0b).\n\t\t\t\tif (hasSourceVersioning) {\n\t\t\t\t\tconst sv = sourceNode.v;\n\t\t\t\t\tif (sv != null) {\n\t\t\t\t\t\tverified.meta.sourceVersion.down([[DATA, { id: sv.id, version: sv.version }]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\treturn { node: sourceNode, verified, trigger: triggerNode };\n}\n\nexport type Extraction<TMem> = {\n\tupsert: Array<{ key: string; value: TMem }>;\n\tremove?: string[];\n};\n\nexport type DistillOptions<TMem> = {\n\tscore: (mem: TMem, context: unknown) => number;\n\tcost: (mem: TMem) => number;\n\tbudget?: number;\n\tevict?: (key: string, mem: TMem) => boolean | Node<boolean>;\n\tconsolidate?: (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;\n\tconsolidateTrigger?: NodeInput<unknown>;\n\tcontext?: NodeInput<unknown>;\n\tmapOptions?: ReactiveMapOptions;\n};\n\nexport type DistillBundle<TMem> = {\n\tstore: ReactiveMapBundle<string, TMem>;\n\tcompact: Node<Array<{ key: string; value: TMem; score: number }>>;\n\tsize: Node<number>;\n};\n\nfunction keepalive(node: Node): void {\n\tnode.subscribe(() => undefined);\n}\n\nfunction mapFromSnapshot<TMem>(snapshot: unknown): ReadonlyMap<string, TMem> {\n\tif (\n\t\ttypeof snapshot === \"object\" &&\n\t\tsnapshot !== null &&\n\t\t\"value\" in snapshot &&\n\t\ttypeof (snapshot as { value?: unknown }).value === \"object\" &&\n\t\t(snapshot as { value?: unknown }).value !== null &&\n\t\t\"map\" in ((snapshot as { value?: unknown }).value as object)\n\t) {\n\t\treturn ((snapshot as { value: { map: ReadonlyMap<string, TMem> } }).value.map ??\n\t\t\tnew Map<string, TMem>()) as ReadonlyMap<string, TMem>;\n\t}\n\treturn new Map<string, TMem>();\n}\n\nfunction asReadonlyMap<TMem>(store: ReactiveMapBundle<string, TMem>): ReadonlyMap<string, TMem> {\n\treturn mapFromSnapshot<TMem>(store.node.get());\n}\n\nfunction applyExtraction<TMem>(\n\tstore: ReactiveMapBundle<string, TMem>,\n\textraction: Extraction<TMem>,\n): void {\n\tif (!Array.isArray(extraction.upsert)) {\n\t\tthrow new TypeError(\"distill extraction requires upsert: Array<{ key, value }>\");\n\t}\n\tbatch(() => {\n\t\tfor (const { key, value } of extraction.upsert) {\n\t\t\tstore.set(key, value);\n\t\t}\n\t\tfor (const key of extraction.remove ?? []) {\n\t\t\tstore.delete(key);\n\t\t}\n\t});\n}\n\n/**\n * Budget-constrained reactive memory composition.\n */\nexport function distill<TRaw, TMem>(\n\tsource: NodeInput<TRaw>,\n\textractFn: (raw: TRaw, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>,\n\topts: DistillOptions<TMem>,\n): DistillBundle<TMem> {\n\tconst sourceNode = fromAny(source);\n\tconst store = reactiveMap<string, TMem>(opts.mapOptions ?? {});\n\tconst budget = opts.budget ?? 2000;\n\tconst hasContext = opts.context !== undefined && opts.context !== null;\n\tconst contextNode = hasContext ? fromAny(opts.context) : state<unknown>(null);\n\n\tconst extractionStream = switchMap(sourceNode, (raw) => extractFn(raw, asReadonlyMap(store)));\n\tforEach(extractionStream, (extraction) => {\n\t\tapplyExtraction(store, extraction);\n\t});\n\n\tif (opts.evict) {\n\t\tconst evictionKeys = dynamicNode((get) => {\n\t\t\tconst out: string[] = [];\n\t\t\tconst snapshot = mapFromSnapshot<TMem>(get(store.node));\n\t\t\tfor (const [key, mem] of snapshot) {\n\t\t\t\tconst verdict = opts.evict!(key, mem);\n\t\t\t\tif (isNodeLike<boolean>(verdict)) {\n\t\t\t\t\tif (get(verdict) === true) out.push(key);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (typeof verdict === \"boolean\") {\n\t\t\t\t\tif (verdict) out.push(key);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow new TypeError(\"distill evict() must return boolean or Node<boolean>\");\n\t\t\t}\n\t\t\treturn out;\n\t\t});\n\t\tforEach(evictionKeys, (keys) => {\n\t\t\tfor (const key of keys) store.delete(key);\n\t\t});\n\t}\n\n\tconst hasConsolidateTrigger =\n\t\topts.consolidateTrigger !== undefined && opts.consolidateTrigger !== null;\n\tif (opts.consolidate && hasConsolidateTrigger) {\n\t\tconst consolidateTriggerNode = fromAny(opts.consolidateTrigger);\n\t\tconst consolidationStream = switchMap(consolidateTriggerNode, () =>\n\t\t\topts.consolidate!(asReadonlyMap(store)),\n\t\t);\n\t\tforEach(consolidationStream, (extraction) => {\n\t\t\tapplyExtraction(store, extraction);\n\t\t});\n\t}\n\n\tconst compact = derived([store.node, contextNode], ([snapshot, context]) => {\n\t\tconst entries = [...mapFromSnapshot<TMem>(snapshot).entries()].map(([key, value]) => ({\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\tscore: opts.score(value, context),\n\t\t\tcost: opts.cost(value),\n\t\t}));\n\t\tentries.sort((a, b) => b.score - a.score);\n\n\t\tconst packed: Array<{ key: string; value: TMem; score: number }> = [];\n\t\tlet remaining = budget;\n\t\tfor (const item of entries) {\n\t\t\tif (item.cost <= remaining) {\n\t\t\t\tpacked.push({ key: item.key, value: item.value, score: item.score });\n\t\t\t\tremaining -= item.cost;\n\t\t\t}\n\t\t}\n\t\treturn packed;\n\t});\n\n\tconst size = derived([store.node], ([snapshot]) => mapFromSnapshot<TMem>(snapshot).size);\n\tkeepalive(compact);\n\tkeepalive(size);\n\n\treturn { store, compact, size };\n}\n","/**\n * Lazy per-topic manual nodes (roadmap §3.2) — create topics on first access, publish with two-phase push.\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { DATA, DIRTY, TEARDOWN } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { state } from \"../core/sugar.js\";\n\n/**\n * In-memory lazy topic registry: each topic is an independent {@link state} node.\n *\n * @category extra\n */\nexport interface PubSubHub {\n\t/**\n\t * Returns the topic node, creating it on first use.\n\t *\n\t * @param name - Topic key.\n\t * @returns `Node` whose value is the last published payload (initially `undefined`).\n\t */\n\ttopic(name: string): Node<unknown>;\n\n\t/**\n\t * Pushes a value to the topic (two-phase `DIRTY` then `DATA`, matching other manual sources here).\n\t *\n\t * @param name - Topic key.\n\t * @param value - Payload.\n\t */\n\tpublish(name: string, value: unknown): void;\n\n\t/**\n\t * Removes a topic and tears down its node. Returns `true` if the topic existed.\n\t *\n\t * @param name - Topic key.\n\t */\n\tremoveTopic(name: string): boolean;\n}\n\nclass PubSubHubImpl implements PubSubHub {\n\tprivate readonly topics = new Map<string, Node<unknown>>();\n\n\ttopic(name: string): Node<unknown> {\n\t\tlet n = this.topics.get(name);\n\t\tif (n === undefined) {\n\t\t\tn = state(undefined, { describeKind: \"state\" });\n\t\t\tthis.topics.set(name, n);\n\t\t}\n\t\treturn n;\n\t}\n\n\tpublish(name: string, value: unknown): void {\n\t\tconst t = this.topic(name);\n\t\tbatch(() => {\n\t\t\tt.down([[DIRTY]]);\n\t\t\tt.down([[DATA, value]]);\n\t\t});\n\t}\n\n\tremoveTopic(name: string): boolean {\n\t\tconst n = this.topics.get(name);\n\t\tif (n === undefined) return false;\n\t\tn.down([[TEARDOWN]]);\n\t\tthis.topics.delete(name);\n\t\treturn true;\n\t}\n}\n\n/**\n * Creates an empty {@link PubSubHub} for lazy topic nodes.\n *\n * @returns A new hub with no topics until {@link PubSubHub.topic} or {@link PubSubHub.publish} runs.\n *\n * @example\n * ```ts\n * import { pubsub } from \"@graphrefly/graphrefly-ts\";\n *\n * const hub = pubsub();\n * const t = hub.topic(\"events\");\n * t.subscribe((msgs) => console.log(msgs));\n * hub.publish(\"events\", { ok: true });\n * hub.removeTopic(\"events\"); // tears down the node\n * ```\n *\n * @category extra\n */\nexport function pubsub(): PubSubHub {\n\treturn new PubSubHubImpl();\n}\n","/**\n * Dual-key sorted index (roadmap §3.2) — unique primary key, rows ordered by `(secondary, primary)`.\n */\nimport { batch } from \"../core/batch.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { bumpVersion, snapshotEqualsVersion, type Versioned } from \"./reactive-base.js\";\n\nexport type IndexRow<K, V = unknown> = {\n\treadonly primary: K;\n\treadonly secondary: unknown;\n\treadonly value: V;\n};\n\nexport type ReactiveIndexSnapshot<K, V = unknown> = Versioned<{ rows: readonly IndexRow<K, V>[] }>;\n\nexport type ReactiveIndexOptions = {\n\tname?: string;\n};\n\nexport type ReactiveIndexBundle<K, V = unknown> = {\n\t/** Rows sorted by `(secondary, primary)`; versioned snapshots. */\n\treadonly ordered: Node<ReactiveIndexSnapshot<K, V>>;\n\t/** Map from primary key to stored value. */\n\treadonly byPrimary: Node<ReadonlyMap<K, V>>;\n\tupsert: (primary: K, secondary: unknown, value: V) => void;\n\tdelete: (primary: K) => void;\n\tclear: () => void;\n};\n\nfunction emptySnapshot<K, V>(): ReactiveIndexSnapshot<K, V> {\n\treturn { version: 0, value: { rows: [] } };\n}\n\nfunction rowKey<K, V>(row: IndexRow<K, V>): [unknown, K] {\n\treturn [row.secondary, row.primary];\n}\n\n/** Lexicographic ordering for index keys (mirrors Python tuple compare for typical primitives). */\nfunction cmpOrd(a: unknown, b: unknown): number {\n\tif (a === b) return 0;\n\tconst ta = typeof a;\n\tconst tb = typeof b;\n\tif (ta === tb && (ta === \"number\" || ta === \"string\" || ta === \"boolean\" || ta === \"bigint\")) {\n\t\tconst ax = a as number | string | boolean | bigint;\n\t\tconst bx = b as number | string | boolean | bigint;\n\t\tif (ax < bx) return -1;\n\t\tif (ax > bx) return 1;\n\t\treturn 0;\n\t}\n\treturn String(a).localeCompare(String(b));\n}\n\nfunction compareKeys<K>(a: [unknown, K], b: [unknown, K]): number {\n\tlet c = cmpOrd(a[0], b[0]);\n\tif (c !== 0) return c;\n\tc = cmpOrd(a[1], b[1]);\n\treturn c;\n}\n\nfunction bisectLeft<K, V>(rows: readonly IndexRow<K, V>[], row: IndexRow<K, V>): number {\n\tconst k = rowKey(row);\n\tlet lo = 0;\n\tlet hi = rows.length;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >> 1;\n\t\tif (compareKeys(k, rowKey(rows[mid]!)) > 0) lo = mid + 1;\n\t\telse hi = mid;\n\t}\n\treturn lo;\n}\n\nfunction byPrimaryMap<K, V>(rows: readonly IndexRow<K, V>[]): Map<K, V> {\n\tconst m = new Map<K, V>();\n\tfor (const r of rows) m.set(r.primary, r.value);\n\treturn m;\n}\n\nfunction keepaliveDerived(n: Node<unknown>): void {\n\tvoid n.subscribe(() => {});\n}\n\n/**\n * Creates a reactive index: unique primary key per row, rows sorted by `(secondary, primary)` for ordered scans.\n *\n * @param options - Optional `name` for `describe()` / debugging.\n * @returns Bundle with `ordered` (versioned rows), `byPrimary` (map), and imperative `upsert` / `delete` / `clear`.\n *\n * @remarks\n * **Ordering:** `secondary` and `primary` are compared via a small total order: same primitive `typeof` uses\n * numeric/string/boolean/bigint comparison; mixed or object keys fall back to `String(a).localeCompare(String(b))`\n * (not identical to Python’s rich comparison for exotic types).\n *\n * @example\n * ```ts\n * import { reactiveIndex } from \"@graphrefly/graphrefly-ts\";\n *\n * const idx = reactiveIndex<string, string>();\n * idx.upsert(\"id1\", 10, \"row-a\");\n * idx.upsert(\"id2\", 5, \"row-b\");\n * ```\n *\n * @category extra\n */\nexport function reactiveIndex<K, V = unknown>(\n\toptions: ReactiveIndexOptions = {},\n): ReactiveIndexBundle<K, V> {\n\tconst { name } = options;\n\tconst buf: IndexRow<K, V>[] = [];\n\tlet current = emptySnapshot<K, V>();\n\n\tconst ordered = state<ReactiveIndexSnapshot<K, V>>(current, {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: snapshotEqualsVersion,\n\t});\n\n\tconst byPrimary = derived(\n\t\t[ordered],\n\t\t([s]) => {\n\t\t\tconst rows = (s as ReactiveIndexSnapshot<K, V>).value.rows;\n\t\t\treturn byPrimaryMap(rows);\n\t\t},\n\t\t{ initial: new Map<K, V>(), describeKind: \"derived\" },\n\t);\n\tkeepaliveDerived(byPrimary);\n\n\tfunction pushSnapshot(): void {\n\t\tconst ov = ordered.v;\n\t\tcurrent = bumpVersion(\n\t\t\tcurrent,\n\t\t\t{ rows: [...buf] },\n\t\t\tov ? { id: ov.id, version: ov.version } : undefined,\n\t\t);\n\t\tbatch(() => {\n\t\t\tordered.down([[DIRTY]]);\n\t\t\tordered.down([[DATA, current]]);\n\t\t});\n\t}\n\n\treturn {\n\t\tordered,\n\t\tbyPrimary,\n\n\t\tupsert(primary: K, secondary: unknown, value: V): void {\n\t\t\tconst next = buf.filter((r) => r.primary !== primary);\n\t\t\tconst row: IndexRow<K, V> = { primary, secondary, value };\n\t\t\tconst pos = bisectLeft(next, row);\n\t\t\tnext.splice(pos, 0, row);\n\t\t\tbuf.length = 0;\n\t\t\tbuf.push(...next);\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tdelete(primary: K): void {\n\t\t\tconst next = buf.filter((r) => r.primary !== primary);\n\t\t\tif (next.length === buf.length) return;\n\t\t\tbuf.length = 0;\n\t\t\tbuf.push(...next);\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tclear(): void {\n\t\t\tif (buf.length === 0) return;\n\t\t\tbuf.length = 0;\n\t\t\tpushSnapshot();\n\t\t},\n\t};\n}\n","/**\n * Reactive positional list (roadmap §3.2) — tuple snapshot with append / insert / pop / clear.\n */\nimport { batch } from \"../core/batch.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { state } from \"../core/sugar.js\";\nimport { bumpVersion, snapshotEqualsVersion, type Versioned } from \"./reactive-base.js\";\n\nexport type ReactiveListSnapshot<T> = Versioned<{ items: readonly T[] }>;\n\nexport type ReactiveListOptions = {\n\tname?: string;\n};\n\nexport type ReactiveListBundle<T> = {\n\t/** Emits {@link ReactiveListSnapshot} on each structural change (two-phase). */\n\treadonly items: Node<ReactiveListSnapshot<T>>;\n\tappend: (value: T) => void;\n\tinsert: (index: number, value: T) => void;\n\tpop: (index?: number) => T;\n\tclear: () => void;\n};\n\nfunction emptySnapshot<T>(): ReactiveListSnapshot<T> {\n\treturn { version: 0, value: { items: [] } };\n}\n\n/**\n * Creates a reactive list with versioned immutable array snapshots.\n *\n * @param initial - Optional initial items (copied).\n * @param options - Optional `name` for `describe()` / debugging.\n * @returns Bundle with `items` (state node) and `append` / `insert` / `pop` / `clear`.\n *\n * @example\n * ```ts\n * import { reactiveList } from \"@graphrefly/graphrefly-ts\";\n *\n * const list = reactiveList<string>([\"a\"], { name: \"queue\" });\n * list.append(\"b\");\n * ```\n *\n * @category extra\n */\nexport function reactiveList<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveListOptions = {},\n): ReactiveListBundle<T> {\n\tconst { name } = options;\n\tconst buf: T[] = initial ? [...initial] : [];\n\tlet current: ReactiveListSnapshot<T> =\n\t\tbuf.length > 0 ? { version: 1, value: { items: [...buf] } } : emptySnapshot();\n\n\tconst items = state<ReactiveListSnapshot<T>>(current, {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: snapshotEqualsVersion,\n\t});\n\n\tfunction pushSnapshot(): void {\n\t\tconst iv = items.v;\n\t\tcurrent = bumpVersion(\n\t\t\tcurrent,\n\t\t\t{ items: [...buf] },\n\t\t\tiv ? { id: iv.id, version: iv.version } : undefined,\n\t\t);\n\t\tbatch(() => {\n\t\t\titems.down([[DIRTY]]);\n\t\t\titems.down([[DATA, current]]);\n\t\t});\n\t}\n\n\treturn {\n\t\titems,\n\n\t\tappend(value: T): void {\n\t\t\tbuf.push(value);\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tinsert(index: number, value: T): void {\n\t\t\tif (index < 0 || index > buf.length) {\n\t\t\t\tthrow new RangeError(\"index out of range\");\n\t\t\t}\n\t\t\tbuf.splice(index, 0, value);\n\t\t\tpushSnapshot();\n\t\t},\n\n\t\tpop(index = -1): T {\n\t\t\tif (buf.length === 0) {\n\t\t\t\tthrow new RangeError(\"pop from empty list\");\n\t\t\t}\n\t\t\tconst i = index >= 0 ? index : buf.length + index;\n\t\t\tif (i < 0 || i >= buf.length) {\n\t\t\t\tthrow new RangeError(\"index out of range\");\n\t\t\t}\n\t\t\tconst [v] = buf.splice(i, 1);\n\t\t\tpushSnapshot();\n\t\t\treturn v as T;\n\t\t},\n\n\t\tclear(): void {\n\t\t\tif (buf.length === 0) return;\n\t\t\tbuf.length = 0;\n\t\t\tpushSnapshot();\n\t\t},\n\t};\n}\n","/**\n * Wire protocol for worker bridge communication.\n *\n * Messages with {@link messageTier} >= 2 cross the wire (DATA values via\n * coalescing, RESOLVED/COMPLETE/TEARDOWN as signals, ERROR as serialized\n * payloads). Tier 0–1 (DIRTY, INVALIDATE, PAUSE, RESUME) stay local to\n * each side's reactive graph.\n *\n * Lifecycle signals serialize as string names since Symbols can't survive\n * structured clone. Unknown {@link Symbol.for} symbols are round-tripped\n * via their registered key.\n */\n\nimport { COMPLETE, ERROR, INVALIDATE, PAUSE, RESUME, TEARDOWN } from \"../../core/messages.js\";\n\n// ---------------------------------------------------------------------------\n// Wire message types\n// ---------------------------------------------------------------------------\n\n/** Value update — one node changed. */\nexport interface ValueMessage {\n\tt: \"v\";\n\t/** Node name. */\n\ts: string;\n\t/** Serialized value. */\n\td: unknown;\n}\n\n/** Lifecycle signal — serialized symbol name. */\nexport interface SignalMessage {\n\tt: \"s\";\n\t/** Node name, or `\"*\"` for bridge-wide. */\n\ts: string;\n\t/** Signal name string (e.g. \"TEARDOWN\"). */\n\tsig: string;\n\t/** Optional payload for custom symbols (spec §1.3.6 forward unchanged). */\n\td?: unknown;\n}\n\n/** Ready — worker declares its exported nodes with initial values. */\nexport interface ReadyMessage {\n\tt: \"r\";\n\tstores: Record<string, unknown>;\n}\n\n/** Init — main sends initial values of its exposed nodes. */\nexport interface InitMessage {\n\tt: \"i\";\n\tstores: Record<string, unknown>;\n}\n\n/** Batch value update — multiple nodes changed in one reactive cycle. */\nexport interface BatchMessage {\n\tt: \"b\";\n\tu: Record<string, unknown>;\n\t/** V0 versions per node for delta sync — peer skips if version <= lastSeen (§6.0b). */\n\tv?: Record<string, number>;\n}\n\n/** Error payload — serialized since Error objects don't survive structured clone. */\nexport interface ErrorMessage {\n\tt: \"e\";\n\t/** Node name. */\n\ts: string;\n\t/** Serialized error. */\n\terr: { message: string; name: string; stack?: string };\n}\n\nexport type BridgeMessage =\n\t| ValueMessage\n\t| SignalMessage\n\t| ReadyMessage\n\t| InitMessage\n\t| BatchMessage\n\t| ErrorMessage;\n\n// ---------------------------------------------------------------------------\n// Signal serialization — Symbol <-> string for structured clone\n// ---------------------------------------------------------------------------\n\nconst signalToNameMap = new Map<symbol, string>([\n\t[INVALIDATE, \"INVALIDATE\"],\n\t[PAUSE, \"PAUSE\"],\n\t[RESUME, \"RESUME\"],\n\t[TEARDOWN, \"TEARDOWN\"],\n\t[COMPLETE, \"COMPLETE\"],\n\t[ERROR, \"ERROR\"],\n]);\n\nconst nameToSignalMap = new Map<string, symbol>([\n\t[\"INVALIDATE\", INVALIDATE],\n\t[\"PAUSE\", PAUSE],\n\t[\"RESUME\", RESUME],\n\t[\"TEARDOWN\", TEARDOWN],\n\t[\"COMPLETE\", COMPLETE],\n\t[\"ERROR\", ERROR],\n]);\n\n/**\n * Serialize a message type symbol to a string for structured clone transfer.\n *\n * Known GraphReFly symbols map to their canonical names. Unknown symbols\n * registered via {@link Symbol.for} use their registered key. Unregistered\n * symbols return `\"UNKNOWN\"`.\n */\nexport function signalToName(s: symbol): string {\n\tconst known = signalToNameMap.get(s);\n\tif (known) return known;\n\tconst key = Symbol.keyFor(s);\n\treturn key ?? \"UNKNOWN\";\n}\n\n/**\n * Deserialize a string back to a message type symbol.\n *\n * Known GraphReFly names map to their canonical symbols. Other non-empty\n * strings are reconstructed via {@link Symbol.for} (round-trip safe for\n * custom message types). Returns `undefined` for `\"UNKNOWN\"`.\n */\nexport function nameToSignal(name: string): symbol | undefined {\n\tconst known = nameToSignalMap.get(name);\n\tif (known) return known;\n\tif (name && name !== \"UNKNOWN\") return Symbol.for(name);\n\treturn undefined;\n}\n\n/** Serialize an error for structured clone transfer. */\nexport function serializeError(err: unknown): { message: string; name: string; stack?: string } {\n\tif (err instanceof Error) {\n\t\treturn { message: err.message, name: err.name, stack: err.stack };\n\t}\n\treturn { message: String(err), name: \"Error\" };\n}\n\n/** Deserialize an error payload back to an Error object. */\nexport function deserializeError(payload: {\n\tmessage: string;\n\tname: string;\n\tstack?: string;\n}): Error {\n\tconst err = new Error(payload.message);\n\terr.name = payload.name;\n\tif (payload.stack) err.stack = payload.stack;\n\treturn err;\n}\n","/**\n * WorkerTransport — normalized message channel for all worker types.\n *\n * Abstracts Worker, SharedWorker, ServiceWorker, BroadcastChannel, and\n * MessagePort behind a uniform post/listen/terminate interface.\n */\n\n/** Normalized bidirectional message channel. */\nexport interface WorkerTransport {\n\t/** Send data to the other side. Optional transferables for zero-copy. */\n\tpost(data: unknown, transfer?: Transferable[]): void;\n\t/** Listen for incoming messages. Returns unsubscribe function. */\n\tlisten(handler: (data: unknown) => void): () => void;\n\t/** Terminate the connection (if supported by the underlying transport). */\n\tterminate?(): void;\n}\n\n/**\n * Auto-detect transport type and create a normalized WorkerTransport.\n *\n * Supports:\n * - `Worker` — direct postMessage/onmessage\n * - `SharedWorker` — port-based postMessage/onmessage\n * - `ServiceWorker` — postMessage via controller, listen via navigator.serviceWorker\n * - `BroadcastChannel` — postMessage/onmessage (no Transferable support)\n * - `MessagePort` — direct postMessage/onmessage (worker-side SharedWorker port)\n */\nexport function createTransport(target: unknown): WorkerTransport {\n\t// MessagePort (SharedWorker port from inside the worker, or raw MessagePort)\n\tif (typeof MessagePort !== \"undefined\" && target instanceof MessagePort) {\n\t\treturn {\n\t\t\tpost(data, transfer) {\n\t\t\t\ttarget.postMessage(data, transfer ?? []);\n\t\t\t},\n\t\t\tlisten(handler) {\n\t\t\t\tconst h = (e: MessageEvent) => handler(e.data);\n\t\t\t\ttarget.addEventListener(\"message\", h);\n\t\t\t\ttarget.start();\n\t\t\t\treturn () => target.removeEventListener(\"message\", h);\n\t\t\t},\n\t\t\tterminate() {\n\t\t\t\ttarget.close();\n\t\t\t},\n\t\t};\n\t}\n\n\t// SharedWorker — use its port\n\tif (typeof SharedWorker !== \"undefined\" && target instanceof SharedWorker) {\n\t\treturn createTransport(target.port);\n\t}\n\n\t// Web Worker\n\tif (typeof Worker !== \"undefined\" && target instanceof Worker) {\n\t\treturn {\n\t\t\tpost(data, transfer) {\n\t\t\t\ttarget.postMessage(data, transfer ?? []);\n\t\t\t},\n\t\t\tlisten(handler) {\n\t\t\t\tconst h = (e: MessageEvent) => handler(e.data);\n\t\t\t\ttarget.addEventListener(\"message\", h);\n\t\t\t\treturn () => target.removeEventListener(\"message\", h);\n\t\t\t},\n\t\t\tterminate() {\n\t\t\t\ttarget.terminate();\n\t\t\t},\n\t\t};\n\t}\n\n\t// BroadcastChannel — no Transferable support\n\tif (typeof BroadcastChannel !== \"undefined\" && target instanceof BroadcastChannel) {\n\t\treturn {\n\t\t\tpost(data, transfer?) {\n\t\t\t\tif (transfer && transfer.length > 0) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\"[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\ttarget.postMessage(data);\n\t\t\t},\n\t\t\tlisten(handler) {\n\t\t\t\tconst h = (e: MessageEvent) => handler(e.data);\n\t\t\t\ttarget.addEventListener(\"message\", h);\n\t\t\t\treturn () => target.removeEventListener(\"message\", h);\n\t\t\t},\n\t\t\tterminate() {\n\t\t\t\ttarget.close();\n\t\t\t},\n\t\t};\n\t}\n\n\t// ServiceWorker\n\tif (typeof ServiceWorker !== \"undefined\" && target instanceof ServiceWorker) {\n\t\treturn {\n\t\t\tpost(data, transfer) {\n\t\t\t\ttarget.postMessage(data, transfer ?? []);\n\t\t\t},\n\t\t\tlisten(handler) {\n\t\t\t\tconst h = (e: MessageEvent) => {\n\t\t\t\t\tif (e.source === target) handler(e.data);\n\t\t\t\t};\n\t\t\t\tnavigator.serviceWorker.addEventListener(\"message\", h);\n\t\t\t\treturn () => navigator.serviceWorker.removeEventListener(\"message\", h);\n\t\t\t},\n\t\t};\n\t}\n\n\tthrow new Error(\n\t\t\"createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.\",\n\t);\n}\n","/**\n * workerBridge — main-thread reactive node bridge to a worker.\n *\n * Creates proxy nodes for imported worker nodes, subscribes to exposed\n * nodes and sends values across the wire. Uses derived() + effect() for\n * natural batch coalescing via two-phase push + bitmask resolution.\n *\n * Wire filtering: messages with {@link messageTier} >= 2 cross the wire.\n * DATA values go through the coalescing path; RESOLVED, COMPLETE, ERROR,\n * TEARDOWN, and unknown {@link Symbol.for} types go through the signal\n * subscription. Tier 0–1 (DIRTY, INVALIDATE, PAUSE, RESUME) stay local.\n *\n * Handshake:\n * 1. Main creates bridge, starts listening\n * 2. Worker sends { t: 'r', stores: { name: initialValue, ... } }\n * 3. Main creates proxy nodes, marks meta.status \"connected\"\n * 4. Main sends { t: 'i', stores: { name: currentValue, ... } }\n * 5. Bidirectional value flow begins\n */\n\nimport { batch } from \"../../core/batch.js\";\nimport {\n\tDATA,\n\tERROR,\n\tknownMessageTypes,\n\ttype Messages,\n\tmessageTier,\n\tTEARDOWN,\n} from \"../../core/messages.js\";\nimport type { Node, NodeSink } from \"../../core/node.js\";\nimport { derived, effect, state } from \"../../core/sugar.js\";\nimport type { BatchMessage, BridgeMessage } from \"./protocol.js\";\nimport { deserializeError, nameToSignal, serializeError, signalToName } from \"./protocol.js\";\nimport type { WorkerTransport } from \"./transport.js\";\nimport { createTransport } from \"./transport.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkerBridgeOptions<\n\tTExpose extends Record<string, Node<any>>,\n\tTImport extends readonly string[],\n> {\n\t/** Nodes to send to the worker. */\n\texpose?: TExpose;\n\t/** Node names the worker will provide. */\n\timport?: TImport;\n\t/** Per-node transferable extractors for zero-copy ArrayBuffer passing. */\n\ttransfer?: Partial<Record<keyof TExpose, (value: any) => Transferable[]>>;\n\t/** Debug name. */\n\tname?: string;\n\t/**\n\t * Handshake timeout in milliseconds. If the worker doesn't send READY\n\t * within this window, `meta.status` transitions to `\"closed\"` and\n\t * `meta.error` is set. Default: no timeout.\n\t */\n\ttimeoutMs?: number;\n}\n\n/** Proxy nodes created from imported worker node names. */\ntype ImportedNodes<T extends readonly string[]> = {\n\treadonly [K in T[number]]: Node<any>;\n};\n\nexport type WorkerBridge<\n\t_TExpose extends Record<string, Node<any>>,\n\tTImport extends readonly string[],\n> = ImportedNodes<TImport> & {\n\t/** Connection status meta node. */\n\tmeta: {\n\t\tstatus: Node<\"connecting\" | \"connected\" | \"closed\">;\n\t\terror: Node<Error | null>;\n\t};\n\t/** Destroy the bridge: sends TEARDOWN, disconnects, terminates worker. */\n\tdestroy(): void;\n};\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nfunction isTransport(t: unknown): t is WorkerTransport {\n\treturn (\n\t\ttypeof t === \"object\" &&\n\t\tt !== null &&\n\t\ttypeof (t as any).post === \"function\" &&\n\t\ttypeof (t as any).listen === \"function\"\n\t);\n}\n\nexport function workerBridge<\n\tTExpose extends Record<string, Node<any>>,\n\tTImport extends readonly string[],\n>(\n\ttarget: unknown | WorkerTransport,\n\topts: WorkerBridgeOptions<TExpose, TImport>,\n): WorkerBridge<TExpose, TImport> {\n\tconst transport = isTransport(target) ? target : createTransport(target);\n\tconst bridgeName = opts.name ?? \"workerBridge\";\n\tconst exposeEntries = Object.entries(opts.expose ?? {});\n\tconst importNames = (opts.import ?? []) as readonly string[];\n\tconst transferFns = opts.transfer ?? {};\n\n\t// -- Meta: connection status -----------------------------------------------\n\tconst statusNode = state<\"connecting\" | \"connected\" | \"closed\">(\"connecting\", {\n\t\tname: `${bridgeName}::meta::status`,\n\t});\n\tconst errorNode = state<Error | null>(null, {\n\t\tname: `${bridgeName}::meta::error`,\n\t});\n\n\t// -- Proxy nodes for imports (worker -> main) ------------------------------\n\tconst proxyNodes = new Map<string, Node<any>>();\n\tconst lastSeenImportVersions = new Map<string, number>();\n\tfor (const name of importNames) {\n\t\tconst proxy = state(undefined, { name: `${bridgeName}::${name}` });\n\t\tproxyNodes.set(name, proxy);\n\t}\n\n\t// -- Send coalescing via derived + effect ----------------------------------\n\tconst lastSent = new Map<string, unknown>();\n\tlet effectUnsub: (() => void) | undefined;\n\n\tif (exposeEntries.length > 0) {\n\t\tconst exposedNodes = exposeEntries.map(([, n]) => n);\n\n\t\tconst aggregated = derived(\n\t\t\texposedNodes,\n\t\t\t() => {\n\t\t\t\tconst updates: Record<string, unknown> = {};\n\t\t\t\tfor (const [name, n] of exposeEntries) {\n\t\t\t\t\tconst v = n.get();\n\t\t\t\t\tif (v !== lastSent.get(name)) {\n\t\t\t\t\t\tupdates[name] = v;\n\t\t\t\t\t\tlastSent.set(name, v);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn updates;\n\t\t\t},\n\t\t\t{ equals: () => false, name: `${bridgeName}::aggregated` },\n\t\t);\n\n\t\tconst effectNode = effect([aggregated], () => {\n\t\t\tconst updates = aggregated.get() as Record<string, unknown>;\n\t\t\tif (Object.keys(updates).length === 0) return;\n\n\t\t\tconst transferList: Transferable[] = [];\n\t\t\tfor (const name of Object.keys(updates)) {\n\t\t\t\tconst fn = (transferFns as any)[name];\n\t\t\t\tif (fn) transferList.push(...fn(updates[name]));\n\t\t\t}\n\n\t\t\t// V0 delta sync: include version counters when available (§6.0b).\n\t\t\tlet versions: Record<string, number> | undefined;\n\t\t\tfor (const [name, n] of exposeEntries) {\n\t\t\t\tif (name in updates && n.v != null) {\n\t\t\t\t\tif (versions == null) versions = {};\n\t\t\t\t\tversions[name] = n.v.version;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst msg: BatchMessage = { t: \"b\", u: updates, ...(versions ? { v: versions } : {}) };\n\t\t\ttry {\n\t\t\t\ttransport.post(msg, transferList.length > 0 ? transferList : undefined);\n\t\t\t} catch (err) {\n\t\t\t\terrorNode.down([[DATA, err instanceof Error ? err : new Error(String(err))]]);\n\t\t\t}\n\t\t});\n\t\t// Effect nodes are lazy — subscribe to activate the chain\n\t\teffectUnsub = effectNode.subscribe(() => {});\n\t}\n\n\t// -- Receive handler -------------------------------------------------------\n\tlet destroyed = false;\n\n\tconst unlisten = transport.listen((data) => {\n\t\tif (destroyed) return;\n\t\tconst msg = data as BridgeMessage;\n\n\t\tswitch (msg.t) {\n\t\t\t// Worker ready — set proxy nodes with initial values\n\t\t\tcase \"r\": {\n\t\t\t\tif (handshakeTimer !== undefined) clearTimeout(handshakeTimer);\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const [name, value] of Object.entries(msg.stores)) {\n\t\t\t\t\t\tconst proxy = proxyNodes.get(name);\n\t\t\t\t\t\tif (proxy) proxy.down([[DATA, value]]);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tstatusNode.down([[DATA, \"connected\"]]);\n\n\t\t\t\t// Send initial values of exposed nodes\n\t\t\t\tconst initValues: Record<string, unknown> = {};\n\t\t\t\tfor (const [name, n] of exposeEntries) {\n\t\t\t\t\tinitValues[name] = n.get();\n\t\t\t\t\tlastSent.set(name, initValues[name]);\n\t\t\t\t}\n\t\t\t\ttransport.post({ t: \"i\", stores: initValues } satisfies BridgeMessage);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Single value update from worker\n\t\t\tcase \"v\": {\n\t\t\t\tconst proxy = proxyNodes.get(msg.s);\n\t\t\t\tif (proxy) proxy.down([[DATA, msg.d]]);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Batch value update from worker\n\t\t\tcase \"b\": {\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const [name, value] of Object.entries(msg.u)) {\n\t\t\t\t\t\tconst incomingVersion = msg.v?.[name];\n\t\t\t\t\t\tif (incomingVersion != null) {\n\t\t\t\t\t\t\tconst lastSeen = lastSeenImportVersions.get(name);\n\t\t\t\t\t\t\tif (lastSeen != null && incomingVersion <= lastSeen) continue;\n\t\t\t\t\t\t\tlastSeenImportVersions.set(name, incomingVersion);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst proxy = proxyNodes.get(name);\n\t\t\t\t\t\tif (proxy) proxy.down([[DATA, value]]);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Error from worker node\n\t\t\tcase \"e\": {\n\t\t\t\tconst proxy = proxyNodes.get(msg.s);\n\t\t\t\tif (proxy) proxy.down([[ERROR, deserializeError(msg.err)]]);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Lifecycle signal from worker\n\t\t\tcase \"s\": {\n\t\t\t\tconst sig = nameToSignal(msg.sig);\n\t\t\t\tif (!sig) break;\n\n\t\t\t\tconst targets: Node<any>[] =\n\t\t\t\t\tmsg.s === \"*\"\n\t\t\t\t\t\t? [...proxyNodes.values()]\n\t\t\t\t\t\t: proxyNodes.has(msg.s)\n\t\t\t\t\t\t\t? [proxyNodes.get(msg.s)!]\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\tfor (const proxy of targets) {\n\t\t\t\t\tproxy.down((msg.d === undefined ? [[sig]] : [[sig, msg.d]]) as Messages);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t});\n\n\t// -- Subscribe to exposed nodes: forward tier >= 2 messages -----------------\n\tconst exposeUnsubs: Array<() => void> = [];\n\tfor (const [name, n] of exposeEntries) {\n\t\tconst unsub = n.subscribe(((msgs: Messages) => {\n\t\t\tif (destroyed) return;\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst type = m[0] as symbol;\n\t\t\t\t// DATA goes through the coalescing path — skip here\n\t\t\t\tif (type === DATA) continue;\n\t\t\t\t// Block known tier 0/1 (DIRTY, INVALIDATE, PAUSE, RESUME) — local only.\n\t\t\t\t// Unknown types (not in knownMessageTypes) always forward (spec §1.3.6).\n\t\t\t\tif (knownMessageTypes.includes(type) && messageTier(type) < 2) continue;\n\t\t\t\t// ERROR: serialize payload\n\t\t\t\tif (type === ERROR) {\n\t\t\t\t\ttransport.post({\n\t\t\t\t\t\tt: \"e\",\n\t\t\t\t\t\ts: name,\n\t\t\t\t\t\terr: serializeError(m[1]),\n\t\t\t\t\t} satisfies BridgeMessage);\n\t\t\t\t} else {\n\t\t\t\t\t// RESOLVED, COMPLETE, TEARDOWN, and unknown Symbol.for types\n\t\t\t\t\ttransport.post({\n\t\t\t\t\t\tt: \"s\",\n\t\t\t\t\t\ts: name,\n\t\t\t\t\t\tsig: signalToName(type),\n\t\t\t\t\t\td: m.length > 1 ? m[1] : undefined,\n\t\t\t\t\t} satisfies BridgeMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}) as NodeSink);\n\t\texposeUnsubs.push(unsub);\n\t}\n\n\t// -- Handshake timeout -----------------------------------------------------\n\tlet handshakeTimer: ReturnType<typeof setTimeout> | undefined;\n\tif (opts.timeoutMs != null && opts.timeoutMs > 0) {\n\t\thandshakeTimer = setTimeout(() => {\n\t\t\tif (statusNode.get() === \"connecting\") {\n\t\t\t\terrorNode.down([[DATA, new Error(\"Worker bridge handshake timeout\")]]);\n\t\t\t\tdestroy();\n\t\t\t}\n\t\t}, opts.timeoutMs);\n\t}\n\n\t// -- Build result object ---------------------------------------------------\n\tfunction destroy() {\n\t\tif (destroyed) return;\n\t\tdestroyed = true;\n\n\t\tif (handshakeTimer !== undefined) clearTimeout(handshakeTimer);\n\n\t\t// Send bridge-level TEARDOWN to worker\n\t\ttransport.post({\n\t\t\tt: \"s\",\n\t\t\ts: \"*\",\n\t\t\tsig: signalToName(TEARDOWN),\n\t\t} satisfies BridgeMessage);\n\n\t\t// Cleanup: unsub effect first (stops sending), then unsub expose\n\t\t// listeners, then unlisten on transport\n\t\tif (effectUnsub) effectUnsub();\n\t\tfor (const unsub of exposeUnsubs) unsub();\n\t\texposeUnsubs.length = 0;\n\t\tunlisten();\n\n\t\tstatusNode.down([[DATA, \"closed\"]]);\n\n\t\tlastSent.clear();\n\t\tlastSeenImportVersions.clear();\n\t\tproxyNodes.clear();\n\t}\n\n\tconst result: any = {\n\t\tmeta: { status: statusNode, error: errorNode },\n\t\tdestroy,\n\t};\n\n\t// Attach proxy nodes as properties\n\tfor (const [name, proxy] of proxyNodes) {\n\t\tresult[name] = proxy;\n\t}\n\n\treturn result as WorkerBridge<TExpose, TImport>;\n}\n","/**\n * workerSelf — worker-side reactive node bridge.\n *\n * Mirror of workerBridge() for the worker side. Creates proxy nodes for\n * imports from main thread, exposes local nodes via the same wire protocol.\n * Uses derived() + effect() for batch coalescing.\n *\n * Wire filtering: messages with {@link messageTier} >= 2 cross the wire.\n * DATA values go through the coalescing path; RESOLVED, COMPLETE, ERROR,\n * TEARDOWN, and unknown {@link Symbol.for} types go through the signal\n * subscription. Tier 0–1 (DIRTY, INVALIDATE, PAUSE, RESUME) stay local.\n *\n * Handshake (worker perspective):\n * 1. workerSelf() called — creates proxy nodes for imports\n * 2. Runs expose factory with proxy nodes -> gets nodes to expose\n * 3. Sends { t: 'r', stores: { name: initialValue, ... } } to main\n * 4. Receives { t: 'i', stores: { name: value, ... } } from main\n * 5. Updates proxy nodes -> triggers local effects\n */\n\nimport { batch } from \"../../core/batch.js\";\nimport {\n\tDATA,\n\tERROR,\n\tknownMessageTypes,\n\ttype Messages,\n\tmessageTier,\n\tTEARDOWN,\n} from \"../../core/messages.js\";\nimport type { Node, NodeSink } from \"../../core/node.js\";\nimport { derived, effect, state } from \"../../core/sugar.js\";\nimport type { BatchMessage, BridgeMessage } from \"./protocol.js\";\nimport { deserializeError, nameToSignal, serializeError, signalToName } from \"./protocol.js\";\nimport type { WorkerTransport } from \"./transport.js\";\nimport { createTransport } from \"./transport.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkerSelfOptions<TImport extends readonly string[]> {\n\t/** Node names that the main thread will provide. */\n\timport?: TImport;\n\t/** Factory that receives imported proxy nodes and returns nodes to expose. */\n\texpose: (imported: WorkerImported<TImport>) => Record<string, Node<any>>;\n\t/** Per-node transferable extractors for zero-copy ArrayBuffer passing. */\n\ttransfer?: Record<string, (value: any) => Transferable[]>;\n}\n\n/** Proxy nodes available inside the worker from main-thread exposed nodes. */\ntype WorkerImported<T extends readonly string[]> = {\n\treadonly [K in T[number]]: Node<any>;\n};\n\nexport interface WorkerSelfHandle {\n\t/** Dispose all subscriptions and stop the bridge. */\n\tdestroy(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nfunction isTransport(t: unknown): t is WorkerTransport {\n\treturn (\n\t\ttypeof t === \"object\" &&\n\t\tt !== null &&\n\t\ttypeof (t as any).post === \"function\" &&\n\t\ttypeof (t as any).listen === \"function\"\n\t);\n}\n\nexport function workerSelf<TImport extends readonly string[]>(\n\ttarget: unknown | WorkerTransport,\n\topts: WorkerSelfOptions<TImport>,\n): WorkerSelfHandle {\n\tconst transport = isTransport(target) ? target : createTransport(target);\n\tconst importNames = (opts.import ?? []) as readonly string[];\n\tconst transferFns = opts.transfer ?? {};\n\n\t// -- Proxy nodes for imports (main -> worker) ------------------------------\n\tconst proxyNodes = new Map<string, Node<any>>();\n\tconst lastSeenImportVersions = new Map<string, number>();\n\tconst importedObj: any = {};\n\tfor (const name of importNames) {\n\t\tconst s = state(undefined, { name: `worker::${name}` });\n\t\tproxyNodes.set(name, s);\n\t\timportedObj[name] = s;\n\t}\n\n\t// -- Run expose factory ----------------------------------------------------\n\tconst exposedNodes = opts.expose(importedObj as WorkerImported<TImport>);\n\tconst exposeEntries = Object.entries(exposedNodes);\n\n\t// -- Send coalescing via derived + effect ----------------------------------\n\tconst lastSent = new Map<string, unknown>();\n\tlet effectUnsub: (() => void) | undefined;\n\tlet destroyed = false;\n\n\tif (exposeEntries.length > 0) {\n\t\tconst nodes = exposeEntries.map(([, n]) => n);\n\n\t\tconst aggregated = derived(\n\t\t\tnodes,\n\t\t\t() => {\n\t\t\t\tconst updates: Record<string, unknown> = {};\n\t\t\t\tfor (const [name, n] of exposeEntries) {\n\t\t\t\t\tconst v = n.get();\n\t\t\t\t\tif (v !== lastSent.get(name)) {\n\t\t\t\t\t\tupdates[name] = v;\n\t\t\t\t\t\tlastSent.set(name, v);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn updates;\n\t\t\t},\n\t\t\t{ equals: () => false, name: \"workerSelf::aggregated\" },\n\t\t);\n\n\t\tconst effectNode = effect([aggregated], () => {\n\t\t\tif (destroyed) return;\n\t\t\tconst updates = aggregated.get() as Record<string, unknown>;\n\t\t\tif (Object.keys(updates).length === 0) return;\n\n\t\t\tconst transferList: Transferable[] = [];\n\t\t\tfor (const name of Object.keys(updates)) {\n\t\t\t\tconst fn = (transferFns as any)[name];\n\t\t\t\tif (fn) transferList.push(...fn(updates[name]));\n\t\t\t}\n\n\t\t\t// V0 delta sync: include version counters when available (§6.0b).\n\t\t\tlet versions: Record<string, number> | undefined;\n\t\t\tfor (const [name, n] of exposeEntries) {\n\t\t\t\tif (name in updates && n.v != null) {\n\t\t\t\t\tif (versions == null) versions = {};\n\t\t\t\t\tversions[name] = n.v.version;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst msg: BatchMessage = { t: \"b\", u: updates, ...(versions ? { v: versions } : {}) };\n\t\t\ttry {\n\t\t\t\ttransport.post(msg, transferList.length > 0 ? transferList : undefined);\n\t\t\t} catch (_err) {\n\t\t\t\t// Transport failure — bridge is likely destroyed; swallow\n\t\t\t}\n\t\t});\n\t\t// Effect nodes are lazy — subscribe to activate the chain\n\t\teffectUnsub = effectNode.subscribe(() => {});\n\t}\n\n\t// -- Subscribe to exposed nodes: forward tier >= 2 messages -----------------\n\tconst exposeUnsubs: Array<() => void> = [];\n\tfor (const [name, n] of exposeEntries) {\n\t\tconst unsub = n.subscribe(((msgs: Messages) => {\n\t\t\tif (destroyed) return;\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst type = m[0] as symbol;\n\t\t\t\t// DATA goes through the coalescing path — skip here\n\t\t\t\tif (type === DATA) continue;\n\t\t\t\t// Block known tier 0/1 (DIRTY, INVALIDATE, PAUSE, RESUME) — local only.\n\t\t\t\t// Unknown types (not in knownMessageTypes) always forward (spec §1.3.6).\n\t\t\t\tif (knownMessageTypes.includes(type) && messageTier(type) < 2) continue;\n\t\t\t\t// ERROR: serialize payload\n\t\t\t\tif (type === ERROR) {\n\t\t\t\t\ttransport.post({\n\t\t\t\t\t\tt: \"e\",\n\t\t\t\t\t\ts: name,\n\t\t\t\t\t\terr: serializeError(m[1]),\n\t\t\t\t\t} satisfies BridgeMessage);\n\t\t\t\t} else {\n\t\t\t\t\t// RESOLVED, COMPLETE, TEARDOWN, and unknown Symbol.for types\n\t\t\t\t\ttransport.post({\n\t\t\t\t\t\tt: \"s\",\n\t\t\t\t\t\ts: name,\n\t\t\t\t\t\tsig: signalToName(type),\n\t\t\t\t\t\td: m.length > 1 ? m[1] : undefined,\n\t\t\t\t\t} satisfies BridgeMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}) as NodeSink);\n\t\texposeUnsubs.push(unsub);\n\t}\n\n\t// -- Receive handler -------------------------------------------------------\n\tconst unlisten = transport.listen((data) => {\n\t\tif (destroyed) return;\n\t\tconst msg = data as BridgeMessage;\n\n\t\tswitch (msg.t) {\n\t\t\t// Init from main — set proxy node values\n\t\t\tcase \"i\": {\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const [name, value] of Object.entries(msg.stores)) {\n\t\t\t\t\t\tconst proxy = proxyNodes.get(name);\n\t\t\t\t\t\tif (proxy) proxy.down([[DATA, value]]);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Single value update from main\n\t\t\tcase \"v\": {\n\t\t\t\tconst proxy = proxyNodes.get(msg.s);\n\t\t\t\tif (proxy) proxy.down([[DATA, msg.d]]);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Batch value update from main\n\t\t\tcase \"b\": {\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const [name, value] of Object.entries(msg.u)) {\n\t\t\t\t\t\tconst incomingVersion = msg.v?.[name];\n\t\t\t\t\t\tif (incomingVersion != null) {\n\t\t\t\t\t\t\tconst lastSeen = lastSeenImportVersions.get(name);\n\t\t\t\t\t\t\tif (lastSeen != null && incomingVersion <= lastSeen) continue;\n\t\t\t\t\t\t\tlastSeenImportVersions.set(name, incomingVersion);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst proxy = proxyNodes.get(name);\n\t\t\t\t\t\tif (proxy) proxy.down([[DATA, value]]);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Error from main node\n\t\t\tcase \"e\": {\n\t\t\t\tconst proxy = proxyNodes.get(msg.s);\n\t\t\t\tif (proxy) proxy.down([[ERROR, deserializeError(msg.err)]]);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Lifecycle signal from main\n\t\t\tcase \"s\": {\n\t\t\t\tconst sig = nameToSignal(msg.sig);\n\t\t\t\tif (!sig) break;\n\n\t\t\t\tif (sig === TEARDOWN && msg.s === \"*\") {\n\t\t\t\t\tdestroy();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst targets: Node<any>[] =\n\t\t\t\t\tmsg.s === \"*\"\n\t\t\t\t\t\t? [...proxyNodes.values()]\n\t\t\t\t\t\t: proxyNodes.has(msg.s)\n\t\t\t\t\t\t\t? [proxyNodes.get(msg.s)!]\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\tfor (const proxy of targets) {\n\t\t\t\t\tproxy.down((msg.d === undefined ? [[sig]] : [[sig, msg.d]]) as Messages);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t});\n\n\t// -- Send ready message ----------------------------------------------------\n\tconst readyValues: Record<string, unknown> = {};\n\tfor (const [name, n] of exposeEntries) {\n\t\treadyValues[name] = n.get();\n\t\tlastSent.set(name, readyValues[name]);\n\t}\n\ttransport.post({ t: \"r\", stores: readyValues } satisfies BridgeMessage);\n\n\t// -- Destroy ---------------------------------------------------------------\n\tfunction destroy() {\n\t\tif (destroyed) return;\n\t\tdestroyed = true;\n\n\t\t// Cleanup: unsub effect first (stops sending), then expose listeners,\n\t\t// then unlisten on transport\n\t\tif (effectUnsub) effectUnsub();\n\t\tfor (const unsub of exposeUnsubs) unsub();\n\t\texposeUnsubs.length = 0;\n\t\tunlisten();\n\t\ttransport.terminate?.();\n\n\t\tlastSent.clear();\n\t\tlastSeenImportVersions.clear();\n\t\tproxyNodes.clear();\n\t}\n\n\treturn { destroy };\n}\n","/**\n * Patterns layer: domain/solution helpers (Phase 4+).\n */\n\nexport * as ai from \"./ai.js\";\nexport * as cqrs from \"./cqrs.js\";\nexport * as memory from \"./memory.js\";\nexport * as messaging from \"./messaging.js\";\nexport * as orchestration from \"./orchestration.js\";\nexport * as layout from \"./reactive-layout/index.js\";\n","/**\n * AI surface patterns (roadmap §4.4).\n *\n * Domain-layer factories for LLM-backed agents, chat, tool registries, and\n * agentic memory. Composed from core + extra + Phase 3–4.3 primitives.\n */\n\nimport type { Actor } from \"../core/actor.js\";\nimport { batch } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, ERROR, TEARDOWN } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, producer, state } from \"../core/sugar.js\";\nimport {\n\ttype DistillBundle,\n\ttype DistillOptions,\n\tdistill,\n\ttype Extraction,\n} from \"../extra/composite.js\";\nimport { switchMap } from \"../extra/operators.js\";\nimport {\n\ttype ReactiveLogBundle,\n\ttype ReactiveLogSnapshot,\n\treactiveLog,\n} from \"../extra/reactive-log.js\";\nimport { fromAny, fromTimer, type NodeInput } from \"../extra/sources.js\";\nimport {\n\ttype AutoCheckpointAdapter,\n\tGraph,\n\ttype GraphAutoCheckpointHandle,\n\ttype GraphAutoCheckpointOptions,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n} from \"../graph/graph.js\";\nimport {\n\tdecay,\n\ttype KnowledgeGraphGraph,\n\tknowledgeGraph,\n\ttype LightCollectionBundle,\n\tlightCollection,\n\ttype VectorIndexBundle,\n\ttype VectorSearchResult,\n\tvectorIndex,\n} from \"./memory.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A single chat message in a conversation. */\nexport type ChatMessage = {\n\treadonly role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n\treadonly content: string;\n\treadonly name?: string;\n\treadonly toolCallId?: string;\n\treadonly toolCalls?: readonly ToolCall[];\n\treadonly metadata?: Record<string, unknown>;\n};\n\n/** A tool invocation request from an LLM. */\nexport type ToolCall = {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly arguments: Record<string, unknown>;\n};\n\n/** The response from an LLM invocation. */\nexport type LLMResponse = {\n\treadonly content: string;\n\treadonly toolCalls?: readonly ToolCall[];\n\treadonly usage?: { readonly inputTokens: number; readonly outputTokens: number };\n\treadonly finishReason?: string;\n\treadonly metadata?: Record<string, unknown>;\n};\n\n/** Provider-agnostic LLM client adapter protocol. */\nexport type LLMAdapter = {\n\tinvoke(messages: readonly ChatMessage[], opts?: LLMInvokeOptions): NodeInput<LLMResponse>;\n\tstream(messages: readonly ChatMessage[], opts?: LLMInvokeOptions): AsyncIterable<string>;\n};\n\nexport type LLMInvokeOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n\tsignal?: AbortSignal;\n};\n\n/** A tool definition for LLM consumption. */\nexport type ToolDefinition = {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly parameters: Record<string, unknown>; // JSON Schema\n\treadonly handler: (args: Record<string, unknown>) => NodeInput<unknown>;\n\t/**\n\t * V0 version of the backing node at `knobsAsTools()` call time (§6.0b).\n\t * Snapshot — re-call `knobsAsTools()` to refresh.\n\t */\n\treadonly version?: { id: string; version: number };\n};\n\nexport type AgentLoopStatus = \"idle\" | \"thinking\" | \"acting\" | \"done\" | \"error\";\n\n// ---------------------------------------------------------------------------\n// Meta helpers\n// ---------------------------------------------------------------------------\n\ntype AIMeta = {\n\tai?: true;\n\tai_type?: string;\n};\n\nfunction aiMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn {\n\t\tai: true,\n\t\tai_type: kind,\n\t\t...(extra ?? {}),\n\t} satisfies AIMeta;\n}\n\nfunction keepalive(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => undefined);\n}\n\nfunction isPromiseLike(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isNodeLike(x: unknown): x is Node<unknown> {\n\treturn (\n\t\ttypeof x === \"object\" &&\n\t\tx !== null &&\n\t\t\"subscribe\" in x &&\n\t\ttypeof (x as Node<unknown>).subscribe === \"function\" &&\n\t\t\"get\" in x &&\n\t\ttypeof (x as Node<unknown>).get === \"function\"\n\t);\n}\n\nfunction isAsyncIterableLike(x: unknown): x is AsyncIterable<unknown> {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === \"object\" &&\n\t\tSymbol.asyncIterator in x &&\n\t\ttypeof (x as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** First settled `DATA` from a `Node` (do not pass plain strings — `fromAny` would iterate chars). */\nfunction firstDataFromNode(\n\tresolved: Node<unknown>,\n\topts?: { timeoutMs?: number },\n): Promise<unknown> {\n\t// Only trust get() when node is in settled state\n\tif ((resolved as { status?: string }).status === \"settled\") {\n\t\tconst immediate = resolved.get();\n\t\tif (immediate !== undefined) {\n\t\t\treturn Promise.resolve(immediate);\n\t\t}\n\t}\n\tconst timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\treturn new Promise((resolve, reject) => {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t};\n\t\tconst unsub = resolved.subscribe((messages) => {\n\t\t\tfor (const msg of messages) {\n\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tunsub();\n\t\t\t\t\tresolve(msg[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === ERROR) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tunsub();\n\t\t\t\t\treject(msg[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tunsub();\n\t\t\t\t\treject(new Error(\"firstDataFromNode: completed without producing a value\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\ttimer = setTimeout(() => {\n\t\t\tunsub();\n\t\t\treject(new Error(`firstDataFromNode: timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\t});\n}\n\n/** Await Promise-likes, then resolve `Node` / async-iterable inputs via `fromAny` + first `DATA`. */\nasync function resolveToolHandlerResult(value: unknown): Promise<unknown> {\n\tif (isPromiseLike(value)) {\n\t\treturn resolveToolHandlerResult(await value);\n\t}\n\tif (isNodeLike(value)) {\n\t\treturn firstDataFromNode(value);\n\t}\n\tif (isAsyncIterableLike(value)) {\n\t\treturn firstDataFromNode(fromAny(value as NodeInput<unknown>));\n\t}\n\treturn value;\n}\n\n// ---------------------------------------------------------------------------\n// fromLLM\n// ---------------------------------------------------------------------------\n\nexport type FromLLMOptions = {\n\tname?: string;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n};\n\n/**\n * Reactive LLM invocation adapter. Returns a derived node that re-invokes\n * the LLM whenever the messages dep changes.\n *\n * Uses `switchMap` internally — new invocations cancel stale in-flight ones.\n */\nexport function fromLLM(\n\tadapter: LLMAdapter,\n\tmessages: NodeInput<readonly ChatMessage[]>,\n\topts?: FromLLMOptions,\n): Node<LLMResponse | null> {\n\tconst msgsNode = fromAny(messages);\n\tconst result = switchMap(msgsNode, (msgs) => {\n\t\tif (!msgs || (msgs as readonly ChatMessage[]).length === 0) {\n\t\t\treturn state<LLMResponse | null>(null) as NodeInput<LLMResponse | null>;\n\t\t}\n\t\tconst tools = opts?.tools;\n\t\treturn adapter.invoke(msgs as readonly ChatMessage[], {\n\t\t\tmodel: opts?.model,\n\t\t\ttemperature: opts?.temperature,\n\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\ttools,\n\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t}) as NodeInput<LLMResponse | null>;\n\t});\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// fromLLMStream\n// ---------------------------------------------------------------------------\n\nexport type FromLLMStreamOptions = FromLLMOptions;\n\n/**\n * Bundle returned by {@link fromLLMStream}. `node` is the reactive log of\n * token chunks; `dispose` tears down the internal effect and log.\n */\nexport type LLMStreamHandle = {\n\t/** Reactive log node accumulating token chunks. */\n\tnode: Node<ReactiveLogSnapshot<string>>;\n\t/** Tear down the internal effect, abort any in-flight stream, and release resources. */\n\tdispose: () => void;\n};\n\n/**\n * Streaming LLM invocation. Returns a `{ node, dispose }` bundle where\n * `node` is a `reactiveLog`-backed node that accumulates token chunks as\n * they arrive from `adapter.stream()`.\n *\n * An `effect` watches the messages input; new values abort the in-flight\n * stream and clear the log before starting a new one. Call `dispose()` to\n * tear down the effect and release resources.\n */\nexport function fromLLMStream(\n\tadapter: LLMAdapter,\n\tmessages: NodeInput<readonly ChatMessage[]>,\n\topts?: FromLLMStreamOptions,\n): LLMStreamHandle {\n\tconst msgsNode = fromAny(messages);\n\tlet controller: AbortController | undefined;\n\n\tconst log = reactiveLog<string>([], { name: opts?.name ?? \"llmStream\" });\n\n\tconst eff = effect([msgsNode], ([msgs]) => {\n\t\t// Abort any in-flight stream\n\t\tcontroller?.abort();\n\t\tlog.clear();\n\n\t\tconst chatMsgs = msgs as readonly ChatMessage[];\n\t\tif (!chatMsgs || chatMsgs.length === 0) return;\n\n\t\tcontroller = new AbortController();\n\t\tconst iter = adapter.stream(chatMsgs, {\n\t\t\tmodel: opts?.model,\n\t\t\ttemperature: opts?.temperature,\n\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\ttools: opts?.tools,\n\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t\tsignal: controller.signal,\n\t\t});\n\t\tconst ctrl = controller;\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tfor await (const chunk of iter) {\n\t\t\t\t\tif (ctrl.signal.aborted) break;\n\t\t\t\t\tlog.append(chunk);\n\t\t\t\t}\n\t\t\t} catch (_err) {\n\t\t\t\t// Stream errors are silently absorbed when aborted.\n\t\t\t\t// Non-abort errors are also absorbed — surfacing ERROR on\n\t\t\t\t// a state node (log.entries) would violate terminal semantics.\n\t\t\t\t// Callers needing error visibility should wrap with a meta node.\n\t\t\t}\n\t\t})();\n\n\t\treturn () => {\n\t\t\tctrl.abort();\n\t\t};\n\t});\n\tconst unsub = keepalive(eff);\n\n\treturn {\n\t\tnode: log.entries,\n\t\tdispose() {\n\t\t\tcontroller?.abort();\n\t\t\tunsub();\n\t\t\teff.down([[TEARDOWN]]);\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// chatStream\n// ---------------------------------------------------------------------------\n\nexport type ChatStreamOptions = {\n\tgraph?: GraphOptions;\n\tmaxMessages?: number;\n};\n\nexport class ChatStreamGraph extends Graph {\n\tprivate readonly _log: ReactiveLogBundle<ChatMessage>;\n\tprivate readonly _keepaliveSubs: Array<() => void> = [];\n\treadonly messages: Node<ReactiveLogSnapshot<ChatMessage>>;\n\treadonly latest: Node<ChatMessage | undefined>;\n\treadonly messageCount: Node<number>;\n\n\tconstructor(name: string, opts: ChatStreamOptions = {}) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis._log = reactiveLog<ChatMessage>([], {\n\t\t\tname: \"messages\",\n\t\t\tmaxSize: opts.maxMessages,\n\t\t});\n\t\tthis.messages = this._log.entries;\n\t\tthis.add(\"messages\", this.messages);\n\n\t\tthis.latest = derived<ChatMessage | undefined>(\n\t\t\t[this.messages],\n\t\t\t([snapshot]) => {\n\t\t\t\tconst entries = (snapshot as ReactiveLogSnapshot<ChatMessage>).value.entries;\n\t\t\t\treturn entries.length === 0 ? undefined : entries[entries.length - 1];\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"latest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"chat_latest\"),\n\t\t\t\tinitial: undefined,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"latest\", this.latest);\n\t\tthis.connect(\"messages\", \"latest\");\n\t\tthis._keepaliveSubs.push(keepalive(this.latest));\n\n\t\tthis.messageCount = derived<number>(\n\t\t\t[this.messages],\n\t\t\t([snapshot]) => (snapshot as ReactiveLogSnapshot<ChatMessage>).value.entries.length,\n\t\t\t{\n\t\t\t\tname: \"messageCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"chat_message_count\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"messageCount\", this.messageCount);\n\t\tthis.connect(\"messages\", \"messageCount\");\n\t\tthis._keepaliveSubs.push(keepalive(this.messageCount));\n\t}\n\n\tappend(role: ChatMessage[\"role\"], content: string, extra?: Partial<ChatMessage>): void {\n\t\tthis._log.append({ role, content, ...extra });\n\t}\n\n\tappendToolResult(callId: string, content: string): void {\n\t\tthis._log.append({ role: \"tool\", content, toolCallId: callId });\n\t}\n\n\tclear(): void {\n\t\tthis._log.clear();\n\t}\n\n\tallMessages(): readonly ChatMessage[] {\n\t\treturn (this.messages.get() as ReactiveLogSnapshot<ChatMessage>).value.entries;\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const unsub of this._keepaliveSubs) unsub();\n\t\tthis._keepaliveSubs.length = 0;\n\t\tsuper.destroy();\n\t}\n}\n\nexport function chatStream(name: string, opts?: ChatStreamOptions): ChatStreamGraph {\n\treturn new ChatStreamGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// toolRegistry\n// ---------------------------------------------------------------------------\n\nexport type ToolRegistryOptions = {\n\tgraph?: GraphOptions;\n};\n\nexport class ToolRegistryGraph extends Graph {\n\treadonly definitions: Node<ReadonlyMap<string, ToolDefinition>>;\n\treadonly schemas: Node<readonly ToolDefinition[]>;\n\tprivate readonly _keepaliveSubs: Array<() => void> = [];\n\n\tconstructor(name: string, opts: ToolRegistryOptions = {}) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis.definitions = state<ReadonlyMap<string, ToolDefinition>>(new Map(), {\n\t\t\tname: \"definitions\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"tool_definitions\"),\n\t\t});\n\t\tthis.add(\"definitions\", this.definitions);\n\n\t\tthis.schemas = derived<readonly ToolDefinition[]>(\n\t\t\t[this.definitions],\n\t\t\t([defs]) => [...((defs ?? new Map()) as ReadonlyMap<string, ToolDefinition>).values()],\n\t\t\t{\n\t\t\t\tname: \"schemas\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"tool_schemas\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tthis.add(\"schemas\", this.schemas);\n\t\tthis.connect(\"definitions\", \"schemas\");\n\t\tthis._keepaliveSubs.push(keepalive(this.schemas));\n\t}\n\n\tregister(tool: ToolDefinition): void {\n\t\tconst current = this.definitions.get() as ReadonlyMap<string, ToolDefinition>;\n\t\tconst next = new Map(current);\n\t\tnext.set(tool.name, tool);\n\t\tthis.definitions.down([[DATA, next]]);\n\t}\n\n\tunregister(name: string): void {\n\t\tconst current = this.definitions.get() as ReadonlyMap<string, ToolDefinition>;\n\t\tif (!current.has(name)) return;\n\t\tconst next = new Map(current);\n\t\tnext.delete(name);\n\t\tthis.definitions.down([[DATA, next]]);\n\t}\n\n\tasync execute(name: string, args: Record<string, unknown>): Promise<unknown> {\n\t\tconst defs = this.definitions.get() as ReadonlyMap<string, ToolDefinition>;\n\t\tconst tool = defs.get(name);\n\t\tif (!tool) throw new Error(`toolRegistry: unknown tool \"${name}\"`);\n\t\tconst raw = tool.handler(args);\n\t\treturn resolveToolHandlerResult(raw);\n\t}\n\n\tgetDefinition(name: string): ToolDefinition | undefined {\n\t\treturn (this.definitions.get() as ReadonlyMap<string, ToolDefinition>).get(name);\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const unsub of this._keepaliveSubs) unsub();\n\t\tthis._keepaliveSubs.length = 0;\n\t\tsuper.destroy();\n\t}\n}\n\nexport function toolRegistry(name: string, opts?: ToolRegistryOptions): ToolRegistryGraph {\n\treturn new ToolRegistryGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// systemPromptBuilder\n// ---------------------------------------------------------------------------\n\n/**\n * Assembles a system prompt from reactive sections. Each section is a\n * `NodeInput<string>` — the prompt updates when any section changes.\n */\nexport type SystemPromptHandle = Node<string> & { dispose: () => void };\n\nexport function systemPromptBuilder(\n\tsections: readonly NodeInput<string>[],\n\topts?: { separator?: string; name?: string },\n): SystemPromptHandle {\n\tconst separator = opts?.separator ?? \"\\n\\n\";\n\tconst sectionNodes = sections.map((s) => (typeof s === \"string\" ? state(s) : fromAny(s)));\n\tconst prompt = derived(\n\t\tsectionNodes,\n\t\t(values) => (values as string[]).filter((v) => v != null && v !== \"\").join(separator),\n\t\t{\n\t\t\tname: opts?.name ?? \"systemPrompt\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: aiMeta(\"system_prompt\"),\n\t\t\tinitial: \"\",\n\t\t},\n\t);\n\tconst unsub = keepalive(prompt);\n\treturn Object.assign(prompt, { dispose: unsub });\n}\n\n// ---------------------------------------------------------------------------\n// llmExtractor / llmConsolidator\n// ---------------------------------------------------------------------------\n\nexport type LLMExtractorOptions = {\n\tadapter: LLMAdapter;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n};\n\n/**\n * Returns an `extractFn` callback for `distill()` that invokes an LLM to\n * extract structured memories from raw input.\n *\n * The system prompt should instruct the LLM to return JSON matching\n * `Extraction<TMem>` shape: `{ upsert: [{ key, value }], remove?: [key] }`.\n */\nexport function llmExtractor<TRaw, TMem>(\n\tsystemPrompt: string,\n\topts: LLMExtractorOptions,\n): (raw: TRaw, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>> {\n\treturn (raw: TRaw, existing: ReadonlyMap<string, TMem>) => {\n\t\tconst existingKeys = [...existing.keys()].slice(0, 100); // sample for dedup\n\t\tconst messages: ChatMessage[] = [\n\t\t\t{ role: \"system\", content: systemPrompt },\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: JSON.stringify({\n\t\t\t\t\tinput: raw,\n\t\t\t\t\texistingKeys,\n\t\t\t\t}),\n\t\t\t},\n\t\t];\n\t\t// Wrap the adapter call in a producer that parses the JSON response\n\t\treturn producer<Extraction<TMem>>((_deps, actions) => {\n\t\t\tlet active = true;\n\t\t\tconst result = opts.adapter.invoke(messages, {\n\t\t\t\tmodel: opts.model,\n\t\t\t\ttemperature: opts.temperature ?? 0,\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t});\n\t\t\t// result is NodeInput — could be a Promise, Node, etc.\n\t\t\tconst resolved = fromAny(result);\n\t\t\tconst unsub = resolved.subscribe((msgs) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tlet done = false;\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst response = msg[1] as LLMResponse;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst parsed = JSON.parse(response.content) as Extraction<TMem>;\n\t\t\t\t\t\t\tactions.emit(parsed);\n\t\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tactions.down([\n\t\t\t\t\t\t\t\t[ERROR, new Error(\"llmExtractor: failed to parse LLM response as JSON\")],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tactions.down([[ERROR, msg[1]]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Forward unknown message types (spec §1.3.6)\n\t\t\t\t\t\tactions.down([[msg[0], msg[1]]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tactive = false;\n\t\t\t};\n\t\t});\n\t};\n}\n\nexport type LLMConsolidatorOptions = LLMExtractorOptions;\n\n/**\n * Returns a `consolidateFn` callback for `distill()` that invokes an LLM to\n * cluster and merge related memories.\n */\nexport function llmConsolidator<TMem>(\n\tsystemPrompt: string,\n\topts: LLMConsolidatorOptions,\n): (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>> {\n\treturn (entries: ReadonlyMap<string, TMem>) => {\n\t\tconst entriesArray = [...entries.entries()].map(([key, value]) => ({ key, value }));\n\t\tconst messages: ChatMessage[] = [\n\t\t\t{ role: \"system\", content: systemPrompt },\n\t\t\t{ role: \"user\", content: JSON.stringify({ memories: entriesArray }) },\n\t\t];\n\t\treturn producer<Extraction<TMem>>((_deps, actions) => {\n\t\t\tlet active = true;\n\t\t\tconst result = opts.adapter.invoke(messages, {\n\t\t\t\tmodel: opts.model,\n\t\t\t\ttemperature: opts.temperature ?? 0,\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t});\n\t\t\tconst resolved = fromAny(result);\n\t\t\tconst unsub = resolved.subscribe((msgs) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tlet done = false;\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst response = msg[1] as LLMResponse;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst parsed = JSON.parse(response.content) as Extraction<TMem>;\n\t\t\t\t\t\t\tactions.emit(parsed);\n\t\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tactions.down([\n\t\t\t\t\t\t\t\t[ERROR, new Error(\"llmConsolidator: failed to parse LLM response as JSON\")],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tactions.down([[ERROR, msg[1]]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Forward unknown message types (spec §1.3.6)\n\t\t\t\t\t\tactions.down([[msg[0], msg[1]]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tactive = false;\n\t\t\t};\n\t\t});\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// 3D Admission Scoring\n// ---------------------------------------------------------------------------\n\n/** Scores for the three admission dimensions. Each 0–1. */\nexport type AdmissionScores = {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n};\n\nexport type AdmissionScore3DOptions = {\n\t/** Custom scoring function. Default: rule-based (all dimensions 0.5). */\n\tscoreFn?: (raw: unknown) => AdmissionScores;\n\t/** Minimum persistence score to admit (default 0.3). */\n\tpersistenceThreshold?: number;\n\t/** Minimum personalValue score to admit (default 0.3). */\n\tpersonalValueThreshold?: number;\n\t/** Require structure score > 0 to admit (default false). */\n\trequireStructured?: boolean;\n};\n\n/**\n * Default 3D admission scorer. Returns middle scores for all dimensions.\n * Override with `scoreFn` for LLM-backed or domain-specific scoring.\n */\nfunction defaultAdmissionScorer(_raw: unknown): AdmissionScores {\n\treturn { persistence: 0.5, structure: 0.5, personalValue: 0.5 };\n}\n\n/**\n * Creates a 3D admission filter function compatible with `agentMemory`'s\n * `admissionFilter` option. Scores each candidate on persistence, structure,\n * and personalValue, then applies thresholds.\n */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions = {}): (raw: unknown) => boolean {\n\tconst scoreFn = opts.scoreFn ?? defaultAdmissionScorer;\n\tconst pThresh = opts.persistenceThreshold ?? 0.3;\n\tconst pvThresh = opts.personalValueThreshold ?? 0.3;\n\tconst reqStructured = opts.requireStructured ?? false;\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = scoreFn(raw);\n\t\tif (scores.persistence < pThresh) return false;\n\t\tif (scores.personalValue < pvThresh) return false;\n\t\tif (reqStructured && scores.structure <= 0) return false;\n\t\treturn true;\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Memory Tiers\n// ---------------------------------------------------------------------------\n\nexport type MemoryTier = \"permanent\" | \"active\" | \"archived\";\n\nexport type MemoryTiersOptions<TMem> = {\n\t/** Exponential decay rate per second for active tier.\n\t * Default: 7-day half-life ≈ ln(2)/(7×86400) ≈ 0.00000114. */\n\tdecayRate?: number;\n\t/** Max entries in the active tier before archiving lowest-scored (default 1000). */\n\tmaxActive?: number;\n\t/** Score threshold below which active entries get archived (default 0.1). */\n\tarchiveThreshold?: number;\n\t/** Predicate: true → entry belongs in permanent tier (default: never). */\n\tpermanentFilter?: (key: string, mem: TMem) => boolean;\n\t/** Persistence adapter for the archive tier. Omit to disable archiving. */\n\tarchiveAdapter?: AutoCheckpointAdapter;\n\t/** Auto-checkpoint options for archive adapter. */\n\tarchiveCheckpointOptions?: GraphAutoCheckpointOptions;\n};\n\nconst DEFAULT_DECAY_RATE = Math.LN2 / (7 * 86_400); // 7-day half-life\n\nexport type MemoryTiersBundle<TMem> = {\n\t/** Permanent tier: never evicted. */\n\treadonly permanent: LightCollectionBundle<TMem>;\n\t/** Active entries node (reactive, holds ReactiveMapSnapshot). */\n\treadonly activeEntries: Node<unknown>;\n\t/** Archive checkpoint handle (null if no adapter). */\n\treadonly archiveHandle: GraphAutoCheckpointHandle | null;\n\t/** Classify a key into its current tier. */\n\ttierOf: (key: string) => MemoryTier;\n\t/** Move a key to the permanent tier. */\n\tmarkPermanent: (key: string, value: TMem) => void;\n};\n\n// ---------------------------------------------------------------------------\n// Retrieval Pipeline\n// ---------------------------------------------------------------------------\n\nexport type RetrievalQuery = {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n};\n\nexport type RetrievalPipelineOptions<TMem> = {\n\t/** Max candidates from vector search (default 20). */\n\ttopK?: number;\n\t/** KG expansion depth in hops (default 1). */\n\tgraphDepth?: number;\n\t/** Token budget for final packing (default 2000). */\n\tbudget?: number;\n\t/** Cost function for budget packing. */\n\tcost: (mem: TMem) => number;\n\t/** Score function for ranking. */\n\tscore: (mem: TMem, context: unknown) => number;\n};\n\n/** A single entry in the retrieval result, with causal trace metadata. */\nexport type RetrievalEntry<TMem> = {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n};\n\n/** Causal trace for a retrieval run. */\nexport type RetrievalTrace<TMem> = {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n};\n\n// ---------------------------------------------------------------------------\n// agentMemory\n// ---------------------------------------------------------------------------\n\nexport type AgentMemoryOptions<TMem = unknown> = {\n\tgraph?: GraphOptions;\n\t/** LLM adapter for extraction and consolidation. */\n\tadapter?: LLMAdapter;\n\t/** System prompt for the extractor LLM. */\n\textractPrompt?: string;\n\t/** Custom extractFn (overrides adapter + extractPrompt). */\n\textractFn?: (raw: unknown, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;\n\t/** System prompt for the consolidation LLM. */\n\tconsolidatePrompt?: string;\n\t/** Custom consolidateFn (overrides adapter + consolidatePrompt). */\n\tconsolidateFn?: (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;\n\t/** Reactive trigger for consolidation (caller supplies e.g. `fromTimer`). */\n\tconsolidateTrigger?: NodeInput<unknown>;\n\t/** Score function for budget packing (required). */\n\tscore: (mem: TMem, context: unknown) => number;\n\t/** Cost function for budget packing (required). */\n\tcost: (mem: TMem) => number;\n\t/** Token budget for compact view (default 2000). */\n\tbudget?: number;\n\t/** Context node for scoring. */\n\tcontext?: NodeInput<unknown>;\n\t/** Admission filter (default: admit all). */\n\tadmissionFilter?: (candidate: unknown) => boolean;\n\t/** Vector index dimensions (> 0 enables vector index for retrieval). */\n\tvectorDimensions?: number;\n\n\t// --- In-factory composition (new) ---\n\n\t/** Extract embedding vector from a memory entry (enables vector index). */\n\tembedFn?: (mem: TMem) => readonly number[] | undefined;\n\t/** Enable knowledge graph for entity/relation tracking. */\n\tenableKnowledgeGraph?: boolean;\n\t/** Extract entities and relations from a memory entry. */\n\tentityFn?: (\n\t\tkey: string,\n\t\tmem: TMem,\n\t) =>\n\t\t| {\n\t\t\t\tentities?: Array<{ id: string; value: unknown }>;\n\t\t\t\trelations?: Array<{ from: string; to: string; relation: string; weight?: number }>;\n\t\t }\n\t\t| undefined;\n\n\t/** 3-tier storage configuration. Omit to use single-tier (existing behavior). */\n\ttiers?: MemoryTiersOptions<TMem>;\n\n\t/** Retrieval pipeline configuration. Requires vector index or knowledge graph. */\n\tretrieval?: {\n\t\t/** Max candidates from vector search (default 20). */\n\t\ttopK?: number;\n\t\t/** KG expansion depth in hops (default 1). */\n\t\tgraphDepth?: number;\n\t};\n\n\t/** Periodic reflection/consolidation configuration. */\n\treflection?: {\n\t\t/** Interval in ms between consolidation runs (default 300_000 = 5 min). */\n\t\tinterval?: number;\n\t\t/** Enable/disable periodic reflection (default true when consolidateFn is available). */\n\t\tenabled?: boolean;\n\t};\n};\n\nexport type AgentMemoryGraph<TMem = unknown> = Graph & {\n\treadonly distillBundle: DistillBundle<TMem>;\n\treadonly compact: Node<Array<{ key: string; value: TMem; score: number }>>;\n\treadonly size: Node<number>;\n\t/** Vector index bundle (null if not enabled). */\n\treadonly vectors: VectorIndexBundle<TMem> | null;\n\t/** Knowledge graph (null if not enabled). */\n\treadonly kg: KnowledgeGraphGraph<unknown, string> | null;\n\t/** Memory tiers bundle (null if not configured). */\n\treadonly memoryTiers: MemoryTiersBundle<TMem> | null;\n\t/** Retrieval result node (null if no retrieval pipeline configured). */\n\treadonly retrieval: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null;\n\t/** Latest retrieval trace for observability (null if no retrieval pipeline). */\n\treadonly retrievalTrace: Node<RetrievalTrace<TMem> | null> | null;\n\t/** Execute a retrieval query (null if no retrieval pipeline). */\n\treadonly retrieve: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null;\n};\n\n/**\n * Pre-wired agentic memory graph. Composes `distill()` with optional\n * `knowledgeGraph()`, `vectorIndex()`, `lightCollection()` (permanent tier),\n * `decay()`, and `autoCheckpoint()` (archive tier). Supports 3D admission\n * scoring, a default retrieval pipeline, periodic reflection, and\n * retrieval observability traces.\n */\n\n/** Extract the key→value map from a reactive_map snapshot. */\nfunction extractStoreMap<TMem>(snapshot: unknown): ReadonlyMap<string, TMem> {\n\tif (\n\t\tsnapshot &&\n\t\ttypeof snapshot === \"object\" &&\n\t\t\"value\" in (snapshot as object) &&\n\t\ttypeof (snapshot as { value?: unknown }).value === \"object\" &&\n\t\t(snapshot as { value?: unknown }).value !== null &&\n\t\t\"map\" in ((snapshot as { value: object }).value as object)\n\t) {\n\t\treturn (\n\t\t\t((snapshot as { value: { map: ReadonlyMap<string, TMem> } }).value.map as ReadonlyMap<\n\t\t\t\tstring,\n\t\t\t\tTMem\n\t\t\t>) ?? new Map<string, TMem>()\n\t\t);\n\t}\n\treturn new Map<string, TMem>();\n}\n\nexport function agentMemory<TMem = unknown>(\n\tname: string,\n\tsource: NodeInput<unknown>,\n\topts: AgentMemoryOptions<TMem>,\n): AgentMemoryGraph<TMem> {\n\tconst graph = new Graph(name, opts.graph);\n\tconst keepaliveSubs: Array<() => void> = [];\n\n\t// --- Extract function resolution ---\n\tlet rawExtractFn: (\n\t\traw: unknown,\n\t\texisting: ReadonlyMap<string, TMem>,\n\t) => NodeInput<Extraction<TMem>>;\n\tif (opts.extractFn) {\n\t\trawExtractFn = opts.extractFn;\n\t} else if (opts.adapter && opts.extractPrompt) {\n\t\trawExtractFn = llmExtractor<unknown, TMem>(opts.extractPrompt, { adapter: opts.adapter });\n\t} else {\n\t\tthrow new Error(\"agentMemory: provide either extractFn or adapter + extractPrompt\");\n\t}\n\tconst extractFn = (\n\t\traw: unknown,\n\t\texisting: ReadonlyMap<string, TMem>,\n\t): NodeInput<Extraction<TMem>> => {\n\t\tif (raw == null) return { upsert: [] };\n\t\treturn rawExtractFn(raw, existing);\n\t};\n\n\t// --- Admission filter ---\n\tlet filteredSource = source;\n\tif (opts.admissionFilter) {\n\t\tconst srcNode = fromAny(source);\n\t\tconst filter = opts.admissionFilter;\n\t\tfilteredSource = derived(\n\t\t\t[srcNode],\n\t\t\t([raw]) => {\n\t\t\t\tif (filter(raw)) return raw;\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{ name: \"admissionFilter\", describeKind: \"derived\" },\n\t\t);\n\t}\n\n\t// --- Consolidation ---\n\tlet consolidateFn:\n\t\t| ((entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>)\n\t\t| undefined;\n\tif (opts.consolidateFn) {\n\t\tconsolidateFn = opts.consolidateFn;\n\t} else if (opts.adapter && opts.consolidatePrompt) {\n\t\tconsolidateFn = llmConsolidator<TMem>(opts.consolidatePrompt, { adapter: opts.adapter });\n\t}\n\n\t// --- Reflection: default consolidateTrigger from fromTimer ---\n\tlet consolidateTrigger = opts.consolidateTrigger;\n\tif (!consolidateTrigger && consolidateFn && opts.reflection?.enabled !== false) {\n\t\tconst interval = opts.reflection?.interval ?? 300_000;\n\t\tconsolidateTrigger = fromTimer(interval, { period: interval });\n\t}\n\n\t// --- Build distill bundle ---\n\tconst distillOpts: DistillOptions<TMem> = {\n\t\tscore: opts.score,\n\t\tcost: opts.cost,\n\t\tbudget: opts.budget ?? 2000,\n\t\tcontext: opts.context,\n\t\tconsolidate: consolidateFn,\n\t\tconsolidateTrigger,\n\t};\n\tconst distillBundle = distill<unknown, TMem>(filteredSource, extractFn, distillOpts);\n\n\tgraph.add(\"store\", distillBundle.store.node);\n\tgraph.add(\"compact\", distillBundle.compact);\n\tgraph.add(\"size\", distillBundle.size);\n\tgraph.connect(\"store\", \"compact\");\n\tgraph.connect(\"store\", \"size\");\n\n\t// --- Vector index (optional) ---\n\tlet vectors: VectorIndexBundle<TMem> | null = null;\n\tif (opts.vectorDimensions && opts.vectorDimensions > 0 && opts.embedFn) {\n\t\tvectors = vectorIndex<TMem>({ dimension: opts.vectorDimensions });\n\t\tgraph.add(\"vectorIndex\", vectors.entries);\n\t}\n\n\t// --- Knowledge graph (optional) ---\n\tlet kg: KnowledgeGraphGraph<unknown, string> | null = null;\n\tif (opts.enableKnowledgeGraph) {\n\t\tkg = knowledgeGraph<unknown, string>(`${name}-kg`);\n\t\tgraph.mount(\"kg\", kg);\n\t}\n\n\t// --- 3-tier storage (optional) ---\n\tlet memoryTiersBundle: MemoryTiersBundle<TMem> | null = null;\n\tif (opts.tiers) {\n\t\tconst tiersOpts = opts.tiers;\n\t\tconst decayRate = tiersOpts.decayRate ?? DEFAULT_DECAY_RATE;\n\t\tconst maxActive = tiersOpts.maxActive ?? 1000;\n\t\tconst archiveThreshold = tiersOpts.archiveThreshold ?? 0.1;\n\t\tconst permanentFilter = tiersOpts.permanentFilter ?? (() => false);\n\n\t\t// Permanent tier\n\t\tconst permanent = lightCollection<TMem>({ name: \"permanent\" });\n\t\tgraph.add(\"permanent\", permanent.entries);\n\n\t\t// Track which keys are permanent\n\t\tconst permanentKeys = new Set<string>();\n\n\t\tconst tierOf = (key: string): MemoryTier => {\n\t\t\tif (permanentKeys.has(key)) return \"permanent\";\n\t\t\tconst storeMap = extractStoreMap<TMem>(distillBundle.store.node.get());\n\t\t\tif (storeMap.has(key)) return \"active\";\n\t\t\treturn \"archived\";\n\t\t};\n\n\t\tconst markPermanent = (key: string, value: TMem): void => {\n\t\t\tpermanentKeys.add(key);\n\t\t\tpermanent.upsert(key, value);\n\t\t};\n\n\t\t// Track entry creation times for accurate decay age calculation\n\t\tconst entryCreatedAtNs = new Map<string, number>();\n\n\t\t// Post-extraction hook: classify into tiers and archive low-scored entries\n\t\tconst storeNode = distillBundle.store.node;\n\t\tconst contextNode = opts.context ? fromAny(opts.context) : state<unknown>(null);\n\t\tconst tierClassifier = effect([storeNode, contextNode], ([snapshot, ctx]) => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(snapshot);\n\t\t\tconst nowNs = monotonicNs();\n\t\t\tconst toArchive: string[] = [];\n\t\t\tconst toPermanent: Array<{ key: string; value: TMem }> = [];\n\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\t// Track creation time for new entries\n\t\t\t\tif (!entryCreatedAtNs.has(key)) {\n\t\t\t\t\tentryCreatedAtNs.set(key, nowNs);\n\t\t\t\t}\n\n\t\t\t\t// Check permanent classification\n\t\t\t\tif (permanentFilter(key, mem)) {\n\t\t\t\t\ttoPermanent.push({ key, value: mem });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Compute decayed score for active tier\n\t\t\t\tconst baseScore = opts.score(mem, ctx);\n\t\t\t\tconst createdNs = entryCreatedAtNs.get(key) ?? nowNs;\n\t\t\t\tconst ageSeconds = Number(nowNs - createdNs) / 1e9;\n\t\t\t\tconst decayed = decay(baseScore, ageSeconds, decayRate);\n\t\t\t\tif (decayed < archiveThreshold) {\n\t\t\t\t\ttoArchive.push(key);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Clean up creation times for removed entries\n\t\t\tfor (const key of entryCreatedAtNs.keys()) {\n\t\t\t\tif (!storeMap.has(key)) entryCreatedAtNs.delete(key);\n\t\t\t}\n\n\t\t\t// Move to permanent\n\t\t\tfor (const { key, value } of toPermanent) {\n\t\t\t\tif (!permanentKeys.has(key)) {\n\t\t\t\t\tmarkPermanent(key, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Archive and evict from active (respect maxActive, excluding permanent keys)\n\t\t\tconst activeCount = storeMap.size - permanentKeys.size;\n\t\t\tif (activeCount > maxActive) {\n\t\t\t\tconst scored = [...storeMap.entries()]\n\t\t\t\t\t.filter(([k]) => !permanentKeys.has(k))\n\t\t\t\t\t.map(([k, m]) => ({ key: k, score: opts.score(m, ctx) }))\n\t\t\t\t\t.sort((a, b) => a.score - b.score);\n\t\t\t\tconst excess = activeCount - maxActive;\n\t\t\t\tfor (let i = 0; i < excess && i < scored.length; i++) {\n\t\t\t\t\tconst sk = scored[i]!.key;\n\t\t\t\t\tif (!toArchive.includes(sk)) toArchive.push(sk);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Evict archived keys from active store\n\t\t\tif (toArchive.length > 0) {\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const key of toArchive) {\n\t\t\t\t\t\tdistillBundle.store.delete(key);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tkeepaliveSubs.push(tierClassifier.subscribe(() => undefined));\n\n\t\t// Archive checkpoint\n\t\tlet archiveHandle: GraphAutoCheckpointHandle | null = null;\n\t\tif (tiersOpts.archiveAdapter) {\n\t\t\tarchiveHandle = graph.autoCheckpoint(\n\t\t\t\ttiersOpts.archiveAdapter,\n\t\t\t\ttiersOpts.archiveCheckpointOptions,\n\t\t\t);\n\t\t}\n\n\t\tmemoryTiersBundle = {\n\t\t\tpermanent,\n\t\t\tactiveEntries: storeNode,\n\t\t\tarchiveHandle,\n\t\t\ttierOf,\n\t\t\tmarkPermanent,\n\t\t};\n\t}\n\n\t// --- Post-extraction hooks: vector + KG indexing ---\n\tif (vectors || kg) {\n\t\tconst embedFn = opts.embedFn;\n\t\tconst entityFn = opts.entityFn;\n\t\tconst storeNode = distillBundle.store.node;\n\n\t\tconst indexer = effect([storeNode], ([snapshot]) => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(snapshot);\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\t// Vector indexing\n\t\t\t\tif (vectors && embedFn) {\n\t\t\t\t\tconst vec = embedFn(mem);\n\t\t\t\t\tif (vec) vectors.upsert(key, vec, mem);\n\t\t\t\t}\n\t\t\t\t// Knowledge graph entity/relation extraction\n\t\t\t\tif (kg && entityFn) {\n\t\t\t\t\tconst extracted = entityFn(key, mem);\n\t\t\t\t\tif (extracted) {\n\t\t\t\t\t\tfor (const ent of extracted.entities ?? []) {\n\t\t\t\t\t\t\tkg.upsertEntity(ent.id, ent.value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const rel of extracted.relations ?? []) {\n\t\t\t\t\t\t\tkg.link(rel.from, rel.to, rel.relation as string, rel.weight);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tkeepaliveSubs.push(indexer.subscribe(() => undefined));\n\t}\n\n\t// --- Retrieval pipeline (optional) ---\n\tlet retrievalNode: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null = null;\n\tlet retrievalTraceNode: Node<RetrievalTrace<TMem> | null> | null = null;\n\tlet retrieveFn: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null = null;\n\n\tif (vectors || kg) {\n\t\tconst topK = opts.retrieval?.topK ?? 20;\n\t\tconst graphDepth = opts.retrieval?.graphDepth ?? 1;\n\t\tconst budget = opts.budget ?? 2000;\n\t\tconst costFn = opts.cost;\n\t\tconst scoreFn = opts.score;\n\n\t\t// Query input node — updated via retrieve()\n\t\tconst queryInput = state<RetrievalQuery | null>(null, {\n\t\t\tname: \"retrievalQuery\",\n\t\t\tdescribeKind: \"state\",\n\t\t});\n\t\tgraph.add(\"retrievalQuery\", queryInput);\n\n\t\tconst contextNode = opts.context ? fromAny(opts.context) : state<unknown>(null);\n\t\tconst traceState = state<RetrievalTrace<TMem> | null>(null, {\n\t\t\tname: \"retrievalTrace\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"retrieval_trace\"),\n\t\t});\n\t\tgraph.add(\"retrievalTrace\", traceState);\n\t\tretrievalTraceNode = traceState;\n\n\t\tconst storeNode = distillBundle.store.node;\n\n\t\t// Last trace captured during retrieval (populated by retrieve())\n\t\tlet lastTrace: RetrievalTrace<TMem> | null = null;\n\n\t\tconst retrievalDerived = derived<ReadonlyArray<RetrievalEntry<TMem>>>(\n\t\t\t[queryInput, storeNode, contextNode],\n\t\t\t([query, snapshot, ctx]) => {\n\t\t\t\tif (!query) return [];\n\t\t\t\tconst q = query as RetrievalQuery;\n\t\t\t\tconst storeMap = extractStoreMap<TMem>(snapshot);\n\n\t\t\t\tconst candidateMap = new Map<\n\t\t\t\t\tstring,\n\t\t\t\t\t{ value: TMem; sources: Set<\"vector\" | \"graph\" | \"store\"> }\n\t\t\t\t>();\n\n\t\t\t\t// Stage 1: Vector search\n\t\t\t\tlet vectorCandidates: VectorSearchResult<TMem>[] = [];\n\t\t\t\tif (vectors && q.vector) {\n\t\t\t\t\tvectorCandidates = vectors.search(q.vector, topK) as VectorSearchResult<TMem>[];\n\t\t\t\t\tfor (const vc of vectorCandidates) {\n\t\t\t\t\t\tconst mem = storeMap.get(vc.id);\n\t\t\t\t\t\tif (mem) {\n\t\t\t\t\t\t\tcandidateMap.set(vc.id, { value: mem, sources: new Set([\"vector\"]) });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Stage 2: KG expansion\n\t\t\t\tconst graphExpanded: string[] = [];\n\t\t\t\tif (kg) {\n\t\t\t\t\tconst seedIds = [...(q.entityIds ?? []), ...[...candidateMap.keys()]];\n\t\t\t\t\tconst visited = new Set<string>();\n\t\t\t\t\tlet frontier = seedIds;\n\t\t\t\t\tfor (let depth = 0; depth < graphDepth; depth++) {\n\t\t\t\t\t\tconst nextFrontier: string[] = [];\n\t\t\t\t\t\tfor (const id of frontier) {\n\t\t\t\t\t\t\tif (visited.has(id)) continue;\n\t\t\t\t\t\t\tvisited.add(id);\n\t\t\t\t\t\t\tconst related = kg.related(id);\n\t\t\t\t\t\t\tfor (const edge of related) {\n\t\t\t\t\t\t\t\tconst targetId = edge.to;\n\t\t\t\t\t\t\t\tif (!visited.has(targetId)) {\n\t\t\t\t\t\t\t\t\tnextFrontier.push(targetId);\n\t\t\t\t\t\t\t\t\tconst mem = storeMap.get(targetId);\n\t\t\t\t\t\t\t\t\tif (mem) {\n\t\t\t\t\t\t\t\t\t\tconst existing = candidateMap.get(targetId);\n\t\t\t\t\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\t\t\t\t\texisting.sources.add(\"graph\");\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tcandidateMap.set(targetId, { value: mem, sources: new Set([\"graph\"]) });\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tgraphExpanded.push(targetId);\n\t\t\t\t\t\t\t\t\t}\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\tfrontier = nextFrontier;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Also include direct store matches not yet in candidates\n\t\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\t\tif (!candidateMap.has(key)) {\n\t\t\t\t\t\tcandidateMap.set(key, { value: mem, sources: new Set([\"store\"]) });\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Stage 3: Score and rank\n\t\t\t\tconst ranked: RetrievalEntry<TMem>[] = [];\n\t\t\t\tfor (const [key, { value, sources }] of candidateMap) {\n\t\t\t\t\tconst score = scoreFn(value, ctx);\n\t\t\t\t\tranked.push({ key, value, score, sources: [...sources] });\n\t\t\t\t}\n\t\t\t\tranked.sort((a, b) => b.score - a.score);\n\n\t\t\t\t// Stage 4: Budget packing\n\t\t\t\tconst packed: RetrievalEntry<TMem>[] = [];\n\t\t\t\tlet usedBudget = 0;\n\t\t\t\tfor (const entry of ranked) {\n\t\t\t\t\tconst c = costFn(entry.value);\n\t\t\t\t\tif (usedBudget + c > budget && packed.length > 0) break;\n\t\t\t\t\tpacked.push(entry);\n\t\t\t\t\tusedBudget += c;\n\t\t\t\t}\n\n\t\t\t\t// Capture trace (no side-effect — stored for retrieval by retrieve())\n\t\t\t\tlastTrace = { vectorCandidates, graphExpanded, ranked, packed };\n\n\t\t\t\treturn packed;\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"retrieval\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"retrieval_pipeline\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tgraph.add(\"retrieval\", retrievalDerived);\n\t\tgraph.connect(\"retrievalQuery\", \"retrieval\");\n\t\tgraph.connect(\"store\", \"retrieval\");\n\t\tkeepaliveSubs.push(retrievalDerived.subscribe(() => undefined));\n\t\tretrievalNode = retrievalDerived;\n\n\t\tretrieveFn = (query: RetrievalQuery): ReadonlyArray<RetrievalEntry<TMem>> => {\n\t\t\tqueryInput.down([[DATA, query]]);\n\t\t\tconst result = retrievalDerived.get() as ReadonlyArray<RetrievalEntry<TMem>>;\n\t\t\t// Update trace node outside derived callback (avoids reactive glitch)\n\t\t\tif (lastTrace) {\n\t\t\t\ttraceState.down([[DATA, lastTrace]]);\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\t}\n\n\t// --- Cleanup ---\n\tconst origDestroy = graph.destroy.bind(graph);\n\tgraph.destroy = () => {\n\t\tfor (const unsub of keepaliveSubs) unsub();\n\t\tkeepaliveSubs.length = 0;\n\t\torigDestroy();\n\t};\n\n\treturn Object.assign(graph, {\n\t\tdistillBundle,\n\t\tcompact: distillBundle.compact,\n\t\tsize: distillBundle.size,\n\t\tvectors,\n\t\tkg,\n\t\tmemoryTiers: memoryTiersBundle,\n\t\tretrieval: retrievalNode,\n\t\tretrievalTrace: retrievalTraceNode,\n\t\tretrieve: retrieveFn,\n\t}) as AgentMemoryGraph<TMem>;\n}\n\n// ---------------------------------------------------------------------------\n// agentLoop\n// ---------------------------------------------------------------------------\n\nexport type AgentLoopOptions = {\n\tgraph?: GraphOptions;\n\tadapter: LLMAdapter;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n\tmaxTurns?: number;\n\tstopWhen?: (response: LLMResponse) => boolean;\n\tonToolCall?: (call: ToolCall) => void;\n\tmaxMessages?: number;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n};\n\nexport class AgentLoopGraph extends Graph {\n\treadonly chat: ChatStreamGraph;\n\treadonly tools: ToolRegistryGraph;\n\treadonly status: Node<AgentLoopStatus>;\n\treadonly turnCount: Node<number>;\n\treadonly lastResponse: Node<LLMResponse | null>;\n\tprivate readonly _statusState: Node<AgentLoopStatus>;\n\tprivate readonly _turnCountState: Node<number>;\n\tprivate readonly _adapter: LLMAdapter;\n\tprivate readonly _maxTurns: number;\n\tprivate readonly _stopWhen?: (response: LLMResponse) => boolean;\n\tprivate readonly _onToolCall?: (call: ToolCall) => void;\n\tprivate readonly _systemPrompt?: string;\n\tprivate readonly _model?: string;\n\tprivate readonly _temperature?: number;\n\tprivate readonly _maxTokens?: number;\n\tprivate _running = false;\n\tprivate _abortController: AbortController | null = null;\n\n\tconstructor(name: string, opts: AgentLoopOptions) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis._adapter = opts.adapter;\n\t\tthis._maxTurns = opts.maxTurns ?? 10;\n\t\tthis._stopWhen = opts.stopWhen;\n\t\tthis._onToolCall = opts.onToolCall;\n\t\tthis._systemPrompt = opts.systemPrompt;\n\t\tthis._model = opts.model;\n\t\tthis._temperature = opts.temperature;\n\t\tthis._maxTokens = opts.maxTokens;\n\n\t\t// Mount chat subgraph\n\t\tthis.chat = chatStream(`${name}-chat`, { maxMessages: opts.maxMessages });\n\t\tthis.mount(\"chat\", this.chat);\n\n\t\t// Mount tool registry subgraph\n\t\tthis.tools = toolRegistry(`${name}-tools`);\n\t\tthis.mount(\"tools\", this.tools);\n\n\t\t// Register initial tools\n\t\tif (opts.tools) {\n\t\t\tfor (const tool of opts.tools) {\n\t\t\t\tthis.tools.register(tool);\n\t\t\t}\n\t\t}\n\n\t\t// Status state\n\t\tthis._statusState = state<AgentLoopStatus>(\"idle\", {\n\t\t\tname: \"status\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_status\"),\n\t\t});\n\t\tthis.status = this._statusState;\n\t\tthis.add(\"status\", this.status);\n\n\t\t// Turn count\n\t\tthis._turnCountState = state<number>(0, {\n\t\t\tname: \"turnCount\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_turn_count\"),\n\t\t});\n\t\tthis.turnCount = this._turnCountState;\n\t\tthis.add(\"turnCount\", this.turnCount);\n\n\t\t// Last LLM response\n\t\tthis.lastResponse = state<LLMResponse | null>(null, {\n\t\t\tname: \"lastResponse\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_last_response\"),\n\t\t});\n\t\tthis.add(\"lastResponse\", this.lastResponse);\n\t}\n\n\t/**\n\t * Start the agent loop with a user message. The loop runs reactively:\n\t * think (LLM call) → act (tool execution) → repeat until done.\n\t *\n\t * Messages accumulate across calls. Call `chat.clear()` before `run()`\n\t * to reset conversation history.\n\t */\n\tasync run(userMessage: string): Promise<LLMResponse | null> {\n\t\tif (this._running) throw new Error(\"agentLoop: already running\");\n\t\tthis._running = true;\n\t\tthis._abortController = new AbortController();\n\t\tconst { signal } = this._abortController;\n\n\t\tbatch(() => {\n\t\t\tthis._statusState.down([[DATA, \"idle\" as AgentLoopStatus]]);\n\t\t\tthis._turnCountState.down([[DATA, 0]]);\n\t\t});\n\t\tthis.chat.append(\"user\", userMessage);\n\n\t\ttry {\n\t\t\tlet turns = 0;\n\t\t\twhile (turns < this._maxTurns) {\n\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\t\t\t\tturns++;\n\t\t\t\tbatch(() => {\n\t\t\t\t\tthis._turnCountState.down([[DATA, turns]]);\n\t\t\t\t\tthis._statusState.down([[DATA, \"thinking\" as AgentLoopStatus]]);\n\t\t\t\t});\n\n\t\t\t\t// Invoke LLM\n\t\t\t\tconst msgs = this.chat.allMessages();\n\t\t\t\tconst toolSchemas = (this.tools.schemas.get() as readonly ToolDefinition[]) ?? [];\n\t\t\t\tconst response = await this._invokeLLM(msgs, toolSchemas, signal);\n\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\n\t\t\t\t(this.lastResponse as Node<LLMResponse | null>).down([[DATA, response]]);\n\n\t\t\t\t// Append assistant message\n\t\t\t\tthis.chat.append(\"assistant\", response.content, {\n\t\t\t\t\ttoolCalls: response.toolCalls,\n\t\t\t\t});\n\n\t\t\t\t// Check stop conditions\n\t\t\t\tif (this._shouldStop(response)) {\n\t\t\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\t\t\tthis._running = false;\n\t\t\t\t\tthis._abortController = null;\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Execute tool calls if present\n\t\t\t\tif (response.toolCalls && response.toolCalls.length > 0) {\n\t\t\t\t\tthis._statusState.down([[DATA, \"acting\" as AgentLoopStatus]]);\n\t\t\t\t\tfor (const call of response.toolCalls) {\n\t\t\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\t\t\t\t\t\tthis._onToolCall?.(call);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await this.tools.execute(call.name, call.arguments);\n\t\t\t\t\t\t\tthis.chat.appendToolResult(call.id, JSON.stringify(result));\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tthis.chat.appendToolResult(call.id, JSON.stringify({ error: String(err) }));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// No tool calls and not explicitly stopped → done\n\t\t\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\t\t\tthis._running = false;\n\t\t\t\t\tthis._abortController = null;\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Max turns reached\n\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\tthis._running = false;\n\t\t\tthis._abortController = null;\n\t\t\treturn this.lastResponse.get() as LLMResponse | null;\n\t\t} catch (err) {\n\t\t\tthis._statusState.down([[DATA, \"error\" as AgentLoopStatus]]);\n\t\t\tthis._running = false;\n\t\t\tthis._abortController = null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate async _invokeLLM(\n\t\tmsgs: readonly ChatMessage[],\n\t\ttools: readonly ToolDefinition[],\n\t\tsignal?: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tconst result = this._adapter.invoke(msgs, {\n\t\t\ttools: tools.length > 0 ? tools : undefined,\n\t\t\tsystemPrompt: this._systemPrompt,\n\t\t\tmodel: this._model,\n\t\t\ttemperature: this._temperature,\n\t\t\tmaxTokens: this._maxTokens,\n\t\t\tsignal,\n\t\t});\n\t\t// Null/undefined guard\n\t\tif (result == null) {\n\t\t\tthrow new Error(\"_invokeLLM: adapter.invoke() returned null or undefined\");\n\t\t}\n\t\t// String guard — fromAny would iterate characters\n\t\tif (typeof result === \"string\") {\n\t\t\tthrow new Error(\"_invokeLLM: adapter.invoke() returned a string, expected LLMResponse\");\n\t\t}\n\t\t// If result is already an LLMResponse (sync adapter), return directly\n\t\tif (\n\t\t\ttypeof result === \"object\" &&\n\t\t\t\"content\" in result &&\n\t\t\t!(\"subscribe\" in result) &&\n\t\t\t!(\"then\" in result)\n\t\t) {\n\t\t\treturn result as LLMResponse;\n\t\t}\n\t\t// If result is a Promise, await it then check for LLMResponse\n\t\tif (isPromiseLike(result)) {\n\t\t\tconst awaited = await result;\n\t\t\tif (\n\t\t\t\ttypeof awaited === \"object\" &&\n\t\t\t\tawaited !== null &&\n\t\t\t\t\"content\" in awaited &&\n\t\t\t\t!(\"subscribe\" in awaited)\n\t\t\t) {\n\t\t\t\treturn awaited as LLMResponse;\n\t\t\t}\n\t\t\treturn firstDataFromNode(fromAny(awaited as NodeInput<LLMResponse>)) as Promise<LLMResponse>;\n\t\t}\n\t\t// If result is a Node or async iterable, resolve via fromAny + firstDataFromNode\n\t\treturn firstDataFromNode(fromAny(result)) as Promise<LLMResponse>;\n\t}\n\n\tprivate _shouldStop(response: LLMResponse): boolean {\n\t\tif (\n\t\t\tresponse.finishReason === \"end_turn\" &&\n\t\t\t(!response.toolCalls || response.toolCalls.length === 0)\n\t\t)\n\t\t\treturn true;\n\t\tif (this._stopWhen?.(response)) return true;\n\t\treturn false;\n\t}\n\n\toverride destroy(): void {\n\t\tif (this._abortController) {\n\t\t\tthis._abortController.abort();\n\t\t\tthis._abortController = null;\n\t\t}\n\t\tthis._running = false;\n\t\tsuper.destroy();\n\t}\n}\n\nexport function agentLoop(name: string, opts: AgentLoopOptions): AgentLoopGraph {\n\treturn new AgentLoopGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// 5.4 — LLM tool integration\n// ---------------------------------------------------------------------------\n\n/** OpenAI function-calling tool schema. */\nexport type OpenAIToolSchema = {\n\treadonly type: \"function\";\n\treadonly function: {\n\t\treadonly name: string;\n\t\treadonly description: string;\n\t\treadonly parameters: Record<string, unknown>;\n\t};\n};\n\n/** MCP (Model Context Protocol) tool schema. */\nexport type McpToolSchema = {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly inputSchema: Record<string, unknown>;\n};\n\n/** Result of {@link knobsAsTools}. */\nexport type KnobsAsToolsResult = {\n\t/** OpenAI function-calling tool schemas. */\n\treadonly openai: readonly OpenAIToolSchema[];\n\t/** MCP tool schemas. */\n\treadonly mcp: readonly McpToolSchema[];\n\t/** GraphReFly ToolDefinitions with handlers that call `graph.set()`. */\n\treadonly definitions: readonly ToolDefinition[];\n};\n\n/**\n * Build a JSON Schema `properties.value` descriptor from a node's meta fields.\n *\n * Maps `meta.type`, `meta.range`, `meta.values`, `meta.format`, and `meta.unit`\n * to a JSON Schema property definition.\n */\nfunction metaToJsonSchema(meta: Record<string, unknown>): Record<string, unknown> {\n\tconst schema: Record<string, unknown> = {};\n\n\tconst metaType = meta.type as string | undefined;\n\tif (metaType === \"enum\" && Array.isArray(meta.values)) {\n\t\tschema.type = \"string\";\n\t\tschema.enum = meta.values;\n\t} else if (metaType === \"integer\") {\n\t\tschema.type = \"integer\";\n\t} else if (metaType === \"number\") {\n\t\tschema.type = \"number\";\n\t} else if (metaType === \"boolean\") {\n\t\tschema.type = \"boolean\";\n\t} else if (metaType === \"string\") {\n\t\tschema.type = \"string\";\n\t} else {\n\t\t// Unknown or unspecified — accept anything\n\t\tschema.type = [\"string\", \"number\", \"boolean\"];\n\t}\n\n\tif (Array.isArray(meta.range) && meta.range.length === 2) {\n\t\tschema.minimum = meta.range[0];\n\t\tschema.maximum = meta.range[1];\n\t}\n\n\tif (typeof meta.format === \"string\") {\n\t\tschema.description = `Format: ${meta.format}`;\n\t}\n\n\tif (typeof meta.unit === \"string\") {\n\t\tif (schema.description) {\n\t\t\tschema.description += ` (${meta.unit})`;\n\t\t} else {\n\t\t\tschema.description = `Unit: ${meta.unit}`;\n\t\t}\n\t}\n\n\treturn schema;\n}\n\n/**\n * Derive tool schemas from a graph's writable (knob) nodes.\n *\n * Knobs are state nodes whose `meta.access` is `\"llm\"`, `\"both\"`, or absent\n * (default: writable). Each knob becomes a tool that calls `graph.set()`.\n *\n * Speaks **domain language** (spec §5.4): the returned schemas use node names\n * and meta descriptions — no protocol internals exposed.\n *\n * @param graph - The graph to introspect.\n * @param actor - Optional actor for guard-scoped describe.\n * @returns OpenAI, MCP, and GraphReFly tool schemas.\n */\nexport function knobsAsTools(graph: Graph, actor?: Actor): KnobsAsToolsResult {\n\tconst described = graph.describe({ actor });\n\tconst openai: OpenAIToolSchema[] = [];\n\tconst mcp: McpToolSchema[] = [];\n\tconst definitions: ToolDefinition[] = [];\n\n\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\t// Only state nodes are writable knobs\n\t\tif (node.type !== \"state\") continue;\n\n\t\t// Skip meta companion nodes (§2.3)\n\t\tif (path.includes(\"::__meta__::\")) continue;\n\n\t\t// Skip terminal-state nodes (§1.3.4 — no further messages after COMPLETE/ERROR)\n\t\tif (node.status === \"completed\" || node.status === \"errored\") continue;\n\n\t\t// Skip if access explicitly excludes LLM\n\t\tconst access = node.meta.access as string | undefined;\n\t\tif (access === \"human\" || access === \"system\") continue;\n\n\t\tconst description = (node.meta.description as string) ?? `Set the value of ${path}`;\n\t\tconst valueSchema = metaToJsonSchema(node.meta);\n\n\t\tconst parameterSchema: Record<string, unknown> = {\n\t\t\ttype: \"object\",\n\t\t\trequired: [\"value\"],\n\t\t\tproperties: {\n\t\t\t\tvalue: valueSchema,\n\t\t\t},\n\t\t\tadditionalProperties: false,\n\t\t};\n\n\t\t// OpenAI requires [a-zA-Z0-9_-] in function names; sanitize :: separators\n\t\tconst sanitizedName = path.replace(/::/g, \"__\");\n\n\t\topenai.push({\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: sanitizedName,\n\t\t\t\tdescription,\n\t\t\t\tparameters: parameterSchema,\n\t\t\t},\n\t\t});\n\n\t\tmcp.push({\n\t\t\tname: path,\n\t\t\tdescription,\n\t\t\tinputSchema: parameterSchema,\n\t\t});\n\n\t\tconst graphRef = graph;\n\t\tconst actorRef = actor;\n\t\tconst nv = node.v;\n\t\tdefinitions.push({\n\t\t\tname: path,\n\t\t\tdescription,\n\t\t\tparameters: parameterSchema,\n\t\t\thandler(args: Record<string, unknown>) {\n\t\t\t\tgraphRef.set(path, args.value, actorRef ? { actor: actorRef } : undefined);\n\t\t\t\treturn args.value;\n\t\t\t},\n\t\t\t...(nv != null ? { version: { id: nv.id, version: nv.version } } : {}),\n\t\t});\n\t}\n\n\treturn { openai, mcp, definitions };\n}\n\n// ---------------------------------------------------------------------------\n// gaugesAsContext\n// ---------------------------------------------------------------------------\n\nexport type GaugesAsContextOptions = {\n\t/** Group gauges by `meta.tags` (default true). */\n\tgroupByTags?: boolean;\n\t/** Separator between gauge lines (default \"\\n\"). */\n\tseparator?: string;\n\t/**\n\t * V0 delta mode (§6.0b): only include nodes whose `v.version` exceeds\n\t * the corresponding entry in this map. Nodes without V0 or not in the\n\t * map are always included. Callers maintain this map across calls.\n\t *\n\t * The `id` field guards against node replacement: if a node is removed\n\t * and re-added under the same name (new id), it is always included.\n\t */\n\tsinceVersion?: ReadonlyMap<string, { id: string; version: number }>;\n};\n\n/**\n * Format a graph's readable (gauge) nodes as a context string for LLM\n * system prompts.\n *\n * Gauges are nodes with `meta.description` or `meta.format`. Values are\n * formatted using `meta.format` and `meta.unit` hints.\n *\n * @param graph - The graph to introspect.\n * @param actor - Optional actor for guard-scoped describe.\n * @param options - Formatting options.\n * @returns A formatted string ready for system prompt injection.\n */\nexport function gaugesAsContext(\n\tgraph: Graph,\n\tactor?: Actor,\n\toptions?: GaugesAsContextOptions,\n): string {\n\tconst described = graph.describe({ actor });\n\tconst groupByTags = options?.groupByTags ?? true;\n\tconst separator = options?.separator ?? \"\\n\";\n\n\ttype GaugeEntry = { path: string; description: string; formatted: string };\n\tconst entries: GaugeEntry[] = [];\n\n\tconst sinceVersion = options?.sinceVersion;\n\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\tconst desc = node.meta.description as string | undefined;\n\t\tconst format = node.meta.format as string | undefined;\n\t\t// Must have description or format to be a gauge\n\t\tif (!desc && !format) continue;\n\t\t// V0 delta filter: skip nodes unchanged since last seen version (§6.0b).\n\t\tif (sinceVersion != null && node.v != null) {\n\t\t\tconst lastSeen = sinceVersion.get(path);\n\t\t\tif (lastSeen != null && lastSeen.id === node.v.id && node.v.version <= lastSeen.version)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tconst label = desc ?? path;\n\t\tconst value = node.value;\n\t\tconst unit = node.meta.unit as string | undefined;\n\n\t\tlet formatted: string;\n\t\tif (format === \"currency\" && typeof value === \"number\") {\n\t\t\tformatted = `$${value.toFixed(2)}`;\n\t\t} else if (format === \"percentage\" && typeof value === \"number\") {\n\t\t\tformatted = `${(value * 100).toFixed(1)}%`;\n\t\t} else if (value === undefined || value === null) {\n\t\t\tformatted = \"(no value)\";\n\t\t} else {\n\t\t\tformatted = String(value);\n\t\t}\n\n\t\tif (unit && format !== \"currency\" && format !== \"percentage\") {\n\t\t\tformatted = `${formatted} ${unit}`;\n\t\t}\n\n\t\tentries.push({ path, description: label, formatted });\n\t}\n\n\tif (entries.length === 0) return \"\";\n\n\tif (groupByTags) {\n\t\tconst tagGroups = new Map<string, GaugeEntry[]>();\n\t\tconst ungrouped: GaugeEntry[] = [];\n\n\t\tfor (const entry of entries) {\n\t\t\tconst node = described.nodes[entry.path]!;\n\t\t\tconst tags = node.meta.tags as string[] | undefined;\n\t\t\tif (tags && tags.length > 0) {\n\t\t\t\t// Use first tag for grouping to avoid duplicating entries across groups\n\t\t\t\tconst tag = tags[0]!;\n\t\t\t\tlet group = tagGroups.get(tag);\n\t\t\t\tif (!group) {\n\t\t\t\t\tgroup = [];\n\t\t\t\t\ttagGroups.set(tag, group);\n\t\t\t\t}\n\t\t\t\tgroup.push(entry);\n\t\t\t} else {\n\t\t\t\tungrouped.push(entry);\n\t\t\t}\n\t\t}\n\n\t\tif (tagGroups.size === 0) {\n\t\t\treturn entries.map((e) => `- ${e.description}: ${e.formatted}`).join(separator);\n\t\t}\n\n\t\tconst sections: string[] = [];\n\t\tfor (const [tag, group] of [...tagGroups.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n\t\t\tsections.push(\n\t\t\t\t`[${tag}]${separator}${group.map((e) => `- ${e.description}: ${e.formatted}`).join(separator)}`,\n\t\t\t);\n\t\t}\n\t\tif (ungrouped.length > 0) {\n\t\t\tsections.push(ungrouped.map((e) => `- ${e.description}: ${e.formatted}`).join(separator));\n\t\t}\n\t\treturn sections.join(separator + separator);\n\t}\n\n\treturn entries.map((e) => `- ${e.description}: ${e.formatted}`).join(separator);\n}\n\n// ---------------------------------------------------------------------------\n// validateGraphDef\n// ---------------------------------------------------------------------------\n\n/** Validation result from {@link validateGraphDef}. */\nexport type GraphDefValidation = {\n\treadonly valid: boolean;\n\treadonly errors: readonly string[];\n};\n\nconst VALID_NODE_TYPES = new Set([\"state\", \"derived\", \"producer\", \"operator\", \"effect\"]);\n\n/**\n * Validate an LLM-generated graph definition before passing to\n * `Graph.fromSnapshot()`.\n *\n * Checks:\n * - Required fields: `name`, `nodes`, `edges`\n * - Node types are valid enum values\n * - Edge `from`/`to` reference existing nodes\n * - No duplicate edge entries\n *\n * @param def - The graph definition to validate (parsed JSON).\n * @returns Validation result with errors array.\n */\nexport function validateGraphDef(def: unknown): GraphDefValidation {\n\tconst errors: string[] = [];\n\n\tif (def == null || typeof def !== \"object\") {\n\t\treturn { valid: false, errors: [\"Definition must be a non-null object\"] };\n\t}\n\n\tconst d = def as Record<string, unknown>;\n\n\tif (typeof d.name !== \"string\" || d.name.length === 0) {\n\t\terrors.push(\"Missing or empty 'name' field\");\n\t}\n\n\tif (d.nodes == null || typeof d.nodes !== \"object\" || Array.isArray(d.nodes)) {\n\t\terrors.push(\"Missing or invalid 'nodes' field (must be an object)\");\n\t\treturn { valid: false, errors };\n\t}\n\n\tconst nodeNames = new Set(Object.keys(d.nodes as object));\n\n\tfor (const [name, raw] of Object.entries(d.nodes as Record<string, unknown>)) {\n\t\tif (raw == null || typeof raw !== \"object\") {\n\t\t\terrors.push(`Node \"${name}\": must be an object`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = raw as Record<string, unknown>;\n\t\tif (typeof node.type !== \"string\" || !VALID_NODE_TYPES.has(node.type)) {\n\t\t\terrors.push(\n\t\t\t\t`Node \"${name}\": invalid type \"${String(node.type)}\" (expected: ${[...VALID_NODE_TYPES].join(\", \")})`,\n\t\t\t);\n\t\t}\n\t\tif (Array.isArray(node.deps)) {\n\t\t\tfor (const dep of node.deps) {\n\t\t\t\tif (typeof dep === \"string\" && !nodeNames.has(dep)) {\n\t\t\t\t\terrors.push(`Node \"${name}\": dep \"${dep}\" does not reference an existing node`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!Array.isArray(d.edges)) {\n\t\tif (d.edges !== undefined) {\n\t\t\terrors.push(\"'edges' must be an array\");\n\t\t}\n\t\t// edges are optional — no error if absent\n\t} else {\n\t\tconst seen = new Set<string>();\n\t\tfor (let i = 0; i < (d.edges as unknown[]).length; i++) {\n\t\t\tconst edge = (d.edges as unknown[])[i];\n\t\t\tif (edge == null || typeof edge !== \"object\") {\n\t\t\t\terrors.push(`Edge [${i}]: must be an object`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst e = edge as Record<string, unknown>;\n\t\t\tif (typeof e.from !== \"string\" || !nodeNames.has(e.from)) {\n\t\t\t\terrors.push(`Edge [${i}]: 'from' \"${String(e.from)}\" does not reference an existing node`);\n\t\t\t}\n\t\t\tif (typeof e.to !== \"string\" || !nodeNames.has(e.to)) {\n\t\t\t\terrors.push(`Edge [${i}]: 'to' \"${String(e.to)}\" does not reference an existing node`);\n\t\t\t}\n\t\t\tconst key = `${e.from}->${e.to}`;\n\t\t\tif (seen.has(key)) {\n\t\t\t\terrors.push(`Edge [${i}]: duplicate edge ${key}`);\n\t\t\t}\n\t\t\tseen.add(key);\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// graphFromSpec\n// ---------------------------------------------------------------------------\n\nexport type GraphFromSpecOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Callback to construct topology before values are applied (passed to `Graph.fromSnapshot`). */\n\tbuild?: (g: Graph) => void;\n\t/** Extra instructions appended to the system prompt. */\n\tsystemPromptExtra?: string;\n};\n\n/** Strip markdown code fences, handling trailing commentary after closing fence. */\nfunction stripFences(text: string): string {\n\tconst match = text.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```[\\s\\S]*$/);\n\treturn match ? match[1]! : text;\n}\n\nconst GRAPH_FROM_SPEC_SYSTEM_PROMPT = `You are a graph architect for GraphReFly, a reactive graph protocol.\n\nGiven a natural-language description, produce a JSON graph definition with this structure:\n\n{\n \"name\": \"<graph_name>\",\n \"nodes\": {\n \"<node_name>\": {\n \"type\": \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\",\n \"value\": <initial_value_or_null>,\n \"deps\": [\"<dep_node_name>\", ...],\n \"meta\": {\n \"description\": \"<human-readable purpose>\",\n \"type\": \"string\" | \"number\" | \"boolean\" | \"integer\" | \"enum\",\n \"range\": [min, max],\n \"values\": [\"a\", \"b\"],\n \"format\": \"currency\" | \"percentage\" | \"status\",\n \"access\": \"human\" | \"llm\" | \"both\" | \"system\",\n \"unit\": \"<unit>\",\n \"tags\": [\"<tag>\"]\n }\n }\n },\n \"edges\": [\n { \"from\": \"<source_node>\", \"to\": \"<target_node>\" }\n ]\n}\n\nRules:\n- \"state\" nodes have no deps and hold user/LLM-writable values (knobs).\n- \"derived\" nodes have deps and compute from them.\n- \"effect\" nodes have deps but produce side effects (no return value).\n- \"producer\" nodes have no deps but generate values asynchronously.\n- Edges wire output of one node as input to another. They must match deps.\n- meta.description is required for every node.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/**\n * Ask an LLM to compose a Graph from a natural-language description.\n *\n * The LLM returns a JSON graph definition which is validated and then\n * constructed via `Graph.fromSnapshot()`.\n *\n * @param naturalLanguage - The problem/use-case description.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options and optional `build` callback for node factories.\n * @returns A constructed Graph.\n * @throws On invalid LLM output or validation failure.\n */\nexport async function graphFromSpec(\n\tnaturalLanguage: string,\n\tadapter: LLMAdapter,\n\topts?: GraphFromSpecOptions,\n): Promise<Graph> {\n\tconst systemPrompt = opts?.systemPromptExtra\n\t\t? `${GRAPH_FROM_SPEC_SYSTEM_PROMPT}\\n\\n${opts.systemPromptExtra}`\n\t\t: GRAPH_FROM_SPEC_SYSTEM_PROMPT;\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{ role: \"user\", content: naturalLanguage },\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\tconst response = (await resolveToolHandlerResult(rawResult)) as LLMResponse;\n\tlet content = response.content.trim();\n\n\t// Strip markdown fences if present (handles trailing commentary after ```)\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`graphFromSpec: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateGraphDef(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`graphFromSpec: invalid graph definition:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tconst def = parsed as Record<string, unknown>;\n\t// Ensure version field is present for fromSnapshot envelope check\n\tif (def.version === undefined) def.version = 1;\n\tif (!Array.isArray(def.subgraphs)) def.subgraphs = [];\n\treturn Graph.fromSnapshot(def as GraphPersistSnapshot, opts?.build);\n}\n\n// ---------------------------------------------------------------------------\n// suggestStrategy\n// ---------------------------------------------------------------------------\n\n/** A single operation in a strategy plan. */\nexport type StrategyOperation =\n\t| {\n\t\t\treadonly type: \"add_node\";\n\t\t\treadonly name: string;\n\t\t\treadonly nodeType: string;\n\t\t\treadonly meta?: Record<string, unknown>;\n\t\t\treadonly initial?: unknown;\n\t }\n\t| { readonly type: \"remove_node\"; readonly name: string }\n\t| { readonly type: \"connect\"; readonly from: string; readonly to: string }\n\t| { readonly type: \"disconnect\"; readonly from: string; readonly to: string }\n\t| { readonly type: \"set_value\"; readonly name: string; readonly value: unknown }\n\t| {\n\t\t\treadonly type: \"update_meta\";\n\t\t\treadonly name: string;\n\t\t\treadonly key: string;\n\t\t\treadonly value: unknown;\n\t };\n\n/** Structured strategy plan returned by {@link suggestStrategy}. */\nexport type StrategyPlan = {\n\treadonly summary: string;\n\treadonly operations: readonly StrategyOperation[];\n\treadonly reasoning: string;\n};\n\nexport type SuggestStrategyOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\tactor?: Actor;\n};\n\nconst SUGGEST_STRATEGY_SYSTEM_PROMPT = `You are a reactive graph optimizer for GraphReFly.\n\nGiven a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.\n\nReturn ONLY valid JSON with this structure:\n{\n \"summary\": \"<one-line summary of the strategy>\",\n \"reasoning\": \"<explanation of why these changes help>\",\n \"operations\": [\n { \"type\": \"add_node\", \"name\": \"<name>\", \"nodeType\": \"state|derived|effect|producer|operator\", \"meta\": {...}, \"initial\": <value> },\n { \"type\": \"remove_node\", \"name\": \"<name>\" },\n { \"type\": \"connect\", \"from\": \"<source>\", \"to\": \"<target>\" },\n { \"type\": \"disconnect\", \"from\": \"<source>\", \"to\": \"<target>\" },\n { \"type\": \"set_value\", \"name\": \"<name>\", \"value\": <new_value> },\n { \"type\": \"update_meta\", \"name\": \"<name>\", \"key\": \"<meta_key>\", \"value\": <new_value> }\n ]\n}\n\nRules:\n- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).\n- Keep changes minimal — prefer the smallest set of operations that solves the problem.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/**\n * Ask an LLM to analyze a graph and suggest topology/parameter changes\n * to solve a stated problem.\n *\n * Returns a structured plan — does NOT auto-apply. The caller reviews\n * and selectively applies operations.\n *\n * @param graph - The graph to analyze.\n * @param problem - Natural-language problem statement.\n * @param adapter - LLM adapter for the analysis call.\n * @param opts - Model and actor options.\n * @returns A structured strategy plan.\n * @throws On invalid LLM output.\n */\nexport async function suggestStrategy(\n\tgraph: Graph,\n\tproblem: string,\n\tadapter: LLMAdapter,\n\topts?: SuggestStrategyOptions,\n): Promise<StrategyPlan> {\n\tconst described = graph.describe({ actor: opts?.actor });\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: SUGGEST_STRATEGY_SYSTEM_PROMPT },\n\t\t{\n\t\t\trole: \"user\",\n\t\t\tcontent: JSON.stringify({\n\t\t\t\tgraph: described,\n\t\t\t\tproblem,\n\t\t\t}),\n\t\t},\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\tconst response = (await resolveToolHandlerResult(rawResult)) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = content.replace(/^```(?:json)?\\s*/, \"\").replace(/\\s*```$/, \"\");\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`suggestStrategy: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst plan = parsed as Record<string, unknown>;\n\n\tif (typeof plan.summary !== \"string\") {\n\t\tthrow new Error(\"suggestStrategy: missing 'summary' in response\");\n\t}\n\tif (typeof plan.reasoning !== \"string\") {\n\t\tthrow new Error(\"suggestStrategy: missing 'reasoning' in response\");\n\t}\n\tif (!Array.isArray(plan.operations)) {\n\t\tthrow new Error(\"suggestStrategy: missing 'operations' array in response\");\n\t}\n\n\treturn {\n\t\tsummary: plan.summary,\n\t\treasoning: plan.reasoning,\n\t\toperations: plan.operations as readonly StrategyOperation[],\n\t};\n}\n","/**\n * Memory patterns (roadmap §4.3).\n *\n * Domain-layer helpers composed from GraphRefly primitives. `vectorIndex` uses\n * an exact-search backend by default; an HNSW adapter can be injected as an\n * optional dependency.\n */\n\nimport { monotonicNs } from \"../core/clock.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { Graph } from \"../graph/graph.js\";\n\nexport type CollectionPolicy = \"fifo\" | \"lru\";\nexport type VectorBackend = \"flat\" | \"hnsw\";\n\nexport type LightCollectionEntry<T> = {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: number;\n\treadonly lastAccessNs: number;\n};\n\nexport type LightCollectionOptions = {\n\tname?: string;\n\tmaxSize?: number;\n\tpolicy?: CollectionPolicy;\n};\n\nexport type LightCollectionBundle<T> = {\n\treadonly entries: Node<ReadonlyMap<string, LightCollectionEntry<T>>>;\n\tupsert: (id: string, value: T) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tget: (id: string) => T | undefined;\n\thas: (id: string) => boolean;\n};\n\nexport type CollectionEntry<T> = LightCollectionEntry<T> & {\n\treadonly baseScore: number;\n};\n\nexport type RankedCollectionEntry<T> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionOptions<T> = {\n\tmaxSize?: number;\n\tpolicy?: CollectionPolicy;\n\t/**\n\t * Produces a base score at insert/update time.\n\t */\n\tscore?: (value: T) => number;\n\t/**\n\t * Exponential decay rate per second. 0 disables decay.\n\t */\n\tdecayRate?: number;\n\t/**\n\t * Minimum score floor after decay.\n\t */\n\tminScore?: number;\n};\n\nexport type CollectionGraph<T> = Graph & {\n\tupsert: (id: string, value: T, opts?: { score?: number }) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tgetItem: (id: string) => CollectionEntry<T> | undefined;\n};\n\nexport type VectorRecord<TMeta> = {\n\treadonly id: string;\n\treadonly vector: readonly number[];\n\treadonly meta?: TMeta;\n};\n\nexport type VectorSearchResult<TMeta> = {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n};\n\nexport type HnswAdapter<TMeta> = {\n\tupsert: (id: string, vector: readonly number[], meta?: TMeta) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tsearch: (query: readonly number[], k: number) => ReadonlyArray<VectorSearchResult<TMeta>>;\n};\n\nexport type VectorIndexOptions<TMeta> = {\n\tbackend?: VectorBackend;\n\tdimension?: number;\n\t/**\n\t * Optional dependency seam for HNSW.\n\t */\n\thnswFactory?: () => HnswAdapter<TMeta>;\n};\n\nexport type VectorIndexBundle<TMeta> = {\n\treadonly backend: VectorBackend;\n\treadonly entries: Node<ReadonlyMap<string, VectorRecord<TMeta>>>;\n\tupsert: (id: string, vector: readonly number[], meta?: TMeta) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tsearch: (query: readonly number[], k?: number) => ReadonlyArray<VectorSearchResult<TMeta>>;\n};\n\nexport type KnowledgeEdge<TRelation extends string = string> = {\n\treadonly from: string;\n\treadonly to: string;\n\treadonly relation: TRelation;\n\treadonly weight: number;\n};\n\nexport type KnowledgeGraphGraph<TEntity, TRelation extends string = string> = Graph & {\n\tupsertEntity: (id: string, value: TEntity) => void;\n\tremoveEntity: (id: string) => void;\n\tlink: (from: string, to: string, relation: TRelation, weight?: number) => void;\n\tunlink: (from: string, to: string, relation?: TRelation) => void;\n\trelated: (id: string, relation?: TRelation) => ReadonlyArray<KnowledgeEdge<TRelation>>;\n};\n\nexport function decay(\n\tbaseScore: number,\n\tageSeconds: number,\n\tratePerSecond: number,\n\tminScore = 0,\n): number {\n\tif (!Number.isFinite(baseScore)) return minScore;\n\tif (!Number.isFinite(ageSeconds) || ageSeconds <= 0) return Math.max(minScore, baseScore);\n\tif (!Number.isFinite(ratePerSecond) || ratePerSecond <= 0) return Math.max(minScore, baseScore);\n\tconst decayed = baseScore * Math.exp(-ratePerSecond * ageSeconds);\n\treturn Math.max(minScore, decayed);\n}\n\nfunction assertMaxSize(maxSize: number | undefined): void {\n\tif (maxSize !== undefined && maxSize < 1) {\n\t\tthrow new RangeError(\"maxSize must be >= 1\");\n\t}\n}\n\nfunction copyMap<K, V>(m: ReadonlyMap<K, V>): Map<K, V> {\n\treturn new Map(m);\n}\n\nfunction readMap<K, V>(node: Node<ReadonlyMap<K, V>>): ReadonlyMap<K, V> {\n\treturn node.get() ?? new Map<K, V>();\n}\n\nfunction readArray<T>(node: Node<ReadonlyArray<T>>): ReadonlyArray<T> {\n\treturn node.get() ?? [];\n}\n\nfunction cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\treturn dot / Math.sqrt(na * nb);\n}\n\nexport function lightCollection<T>(opts: LightCollectionOptions = {}): LightCollectionBundle<T> {\n\tconst maxSize = opts.maxSize;\n\tconst policy = opts.policy ?? \"fifo\";\n\tassertMaxSize(maxSize);\n\n\tconst entries = state<ReadonlyMap<string, LightCollectionEntry<T>>>(new Map(), {\n\t\tname: opts.name,\n\t\tdescribeKind: \"state\",\n\t});\n\n\tfunction evictIfNeeded(next: Map<string, LightCollectionEntry<T>>): void {\n\t\tif (maxSize === undefined) return;\n\t\twhile (next.size > maxSize) {\n\t\t\tlet victim: LightCollectionEntry<T> | undefined;\n\t\t\tfor (const entry of next.values()) {\n\t\t\t\tif (!victim) {\n\t\t\t\t\tvictim = entry;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lhs = policy === \"lru\" ? entry.lastAccessNs : entry.createdAtNs;\n\t\t\t\tconst rhs = policy === \"lru\" ? victim.lastAccessNs : victim.createdAtNs;\n\t\t\t\tif (lhs < rhs) victim = entry;\n\t\t\t}\n\t\t\tif (!victim) break;\n\t\t\tnext.delete(victim.id);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, LightCollectionEntry<T>>): void {\n\t\tentries.down([[DATA, next]]);\n\t}\n\n\treturn {\n\t\tentries,\n\t\tupsert(id, value) {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst current = readMap(entries);\n\t\t\tconst prev = current.get(id);\n\t\t\tconst next = copyMap(current);\n\t\t\tnext.set(id, {\n\t\t\t\tid,\n\t\t\t\tvalue,\n\t\t\t\tcreatedAtNs: prev?.createdAtNs ?? now,\n\t\t\t\tlastAccessNs: now,\n\t\t\t});\n\t\t\tevictIfNeeded(next);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id) {\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(entries).size === 0) return;\n\t\t\tcommit(new Map());\n\t\t},\n\t\tget(id) {\n\t\t\tconst current = readMap(entries);\n\t\t\tconst found = current.get(id);\n\t\t\tif (!found) return undefined;\n\t\t\tif (policy === \"lru\") {\n\t\t\t\tconst now = monotonicNs();\n\t\t\t\tconst next = copyMap(current);\n\t\t\t\tnext.set(id, { ...found, lastAccessNs: now });\n\t\t\t\tcommit(next);\n\t\t\t}\n\t\t\treturn found.value;\n\t\t},\n\t\thas(id) {\n\t\t\treturn readMap(entries).has(id);\n\t\t},\n\t};\n}\n\nexport function collection<T>(name: string, opts: CollectionOptions<T> = {}): CollectionGraph<T> {\n\tconst maxSize = opts.maxSize;\n\tconst policy = opts.policy ?? \"lru\";\n\tconst decayRate = opts.decayRate ?? 0;\n\tconst minScore = opts.minScore ?? 0;\n\tconst scoreFn = opts.score ?? (() => 1);\n\tassertMaxSize(maxSize);\n\n\tconst graph = new Graph(name);\n\tconst items = state<ReadonlyMap<string, CollectionEntry<T>>>(new Map(), {\n\t\tname: \"items\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst ranked = derived(\n\t\t[items],\n\t\t([snapshot]) => {\n\t\t\tconst typed = (snapshot ?? new Map()) as ReadonlyMap<string, CollectionEntry<T>>;\n\t\t\tconst now = monotonicNs();\n\t\t\tconst out = [...typed.values()].map((entry) => {\n\t\t\t\tconst ageSeconds = (now - entry.lastAccessNs) / 1_000_000_000;\n\t\t\t\treturn {\n\t\t\t\t\t...entry,\n\t\t\t\t\tscore: decay(entry.baseScore, ageSeconds, decayRate, minScore),\n\t\t\t\t};\n\t\t\t});\n\t\t\tout.sort((a, b) => b.score - a.score || b.lastAccessNs - a.lastAccessNs);\n\t\t\treturn out;\n\t\t},\n\t\t{ name: \"ranked\", describeKind: \"derived\" },\n\t);\n\tconst size = derived(\n\t\t[items],\n\t\t([snapshot]) => ((snapshot ?? new Map()) as ReadonlyMap<string, CollectionEntry<T>>).size,\n\t\t{\n\t\t\tname: \"size\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: 0,\n\t\t},\n\t);\n\tvoid ranked.subscribe(() => undefined);\n\tvoid size.subscribe(() => undefined);\n\n\tgraph.add(\"items\", items);\n\tgraph.add(\"ranked\", ranked);\n\tgraph.add(\"size\", size);\n\tgraph.connect(\"items\", \"ranked\");\n\tgraph.connect(\"items\", \"size\");\n\n\tfunction effective(entry: CollectionEntry<T>, now: number): number {\n\t\tconst ageSeconds = (now - entry.lastAccessNs) / 1_000_000_000;\n\t\treturn decay(entry.baseScore, ageSeconds, decayRate, minScore);\n\t}\n\n\tfunction evictIfNeeded(next: Map<string, CollectionEntry<T>>): void {\n\t\tif (maxSize === undefined) return;\n\t\twhile (next.size > maxSize) {\n\t\t\tconst now = monotonicNs();\n\t\t\tlet victim: CollectionEntry<T> | undefined;\n\t\t\tlet victimScore = Number.POSITIVE_INFINITY;\n\t\t\tfor (const entry of next.values()) {\n\t\t\t\tconst score = effective(entry, now);\n\t\t\t\tif (score < victimScore) {\n\t\t\t\t\tvictim = entry;\n\t\t\t\t\tvictimScore = score;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (score === victimScore && victim) {\n\t\t\t\t\tconst lhs = policy === \"lru\" ? entry.lastAccessNs : entry.createdAtNs;\n\t\t\t\t\tconst rhs = policy === \"lru\" ? victim.lastAccessNs : victim.createdAtNs;\n\t\t\t\t\tif (lhs < rhs) victim = entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!victim) break;\n\t\t\tnext.delete(victim.id);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, CollectionEntry<T>>): void {\n\t\titems.down([[DATA, next]]);\n\t}\n\n\tconst out = Object.assign(graph, {\n\t\tupsert(id: string, value: T, upsertOpts?: { score?: number }) {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst current = readMap(items);\n\t\t\tconst prev = current.get(id);\n\t\t\tconst baseScore = upsertOpts?.score ?? scoreFn(value);\n\t\t\tconst next = copyMap(current);\n\t\t\tnext.set(id, {\n\t\t\t\tid,\n\t\t\t\tvalue,\n\t\t\t\tbaseScore,\n\t\t\t\tcreatedAtNs: prev?.createdAtNs ?? now,\n\t\t\t\tlastAccessNs: now,\n\t\t\t});\n\t\t\tevictIfNeeded(next);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id: string) {\n\t\t\tconst next = copyMap(readMap(items));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(items).size === 0) return;\n\t\t\tcommit(new Map());\n\t\t},\n\t\tgetItem(id: string): CollectionEntry<T> | undefined {\n\t\t\tconst current = readMap(items);\n\t\t\tconst found = current.get(id);\n\t\t\tif (!found) return undefined;\n\t\t\tif (policy === \"lru\") {\n\t\t\t\tconst next = copyMap(current);\n\t\t\t\tnext.set(id, { ...found, lastAccessNs: monotonicNs() });\n\t\t\t\tcommit(next);\n\t\t\t}\n\t\t\treturn found;\n\t\t},\n\t}) as CollectionGraph<T>;\n\treturn out;\n}\n\nexport function vectorIndex<TMeta>(opts: VectorIndexOptions<TMeta> = {}): VectorIndexBundle<TMeta> {\n\tconst backend = opts.backend ?? \"flat\";\n\tconst dimension = opts.dimension;\n\tlet hnsw: HnswAdapter<TMeta> | undefined;\n\tif (backend === \"hnsw\") {\n\t\thnsw = opts.hnswFactory?.();\n\t\tif (!hnsw) {\n\t\t\tthrow new Error(\n\t\t\t\t'vectorIndex backend \"hnsw\" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.',\n\t\t\t);\n\t\t}\n\t}\n\n\tconst entries = state<ReadonlyMap<string, VectorRecord<TMeta>>>(new Map(), {\n\t\tdescribeKind: \"state\",\n\t\tname: \"vector-index\",\n\t});\n\n\tfunction assertDimension(vector: readonly number[]): void {\n\t\tif (dimension !== undefined && vector.length !== dimension) {\n\t\t\tthrow new RangeError(\n\t\t\t\t`vector dimension mismatch: expected ${dimension}, got ${vector.length}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, VectorRecord<TMeta>>): void {\n\t\tentries.down([[DATA, next]]);\n\t}\n\n\treturn {\n\t\tbackend,\n\t\tentries,\n\t\tupsert(id, vector, meta) {\n\t\t\tassertDimension(vector);\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tnext.set(id, { id, vector: [...vector], meta });\n\t\t\tif (backend === \"hnsw\") hnsw!.upsert(id, vector, meta);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id) {\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tif (backend === \"hnsw\") hnsw!.remove(id);\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(entries).size === 0) return;\n\t\t\tif (backend === \"hnsw\") hnsw!.clear();\n\t\t\tcommit(new Map());\n\t\t},\n\t\tsearch(query, k = 5) {\n\t\t\tassertDimension(query);\n\t\t\tif (k <= 0) return [];\n\t\t\tif (backend === \"hnsw\") return hnsw!.search(query, k);\n\t\t\tconst ranked = [...readMap(entries).values()]\n\t\t\t\t.map((row) => ({\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tscore: cosineSimilarity(query, row.vector),\n\t\t\t\t\tmeta: row.meta,\n\t\t\t\t}))\n\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t.slice(0, k);\n\t\t\treturn ranked;\n\t\t},\n\t};\n}\n\nexport function knowledgeGraph<TEntity, TRelation extends string = string>(\n\tname: string,\n): KnowledgeGraphGraph<TEntity, TRelation> {\n\tconst graph = new Graph(name);\n\tconst entities = state<ReadonlyMap<string, TEntity>>(new Map(), {\n\t\tname: \"entities\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst edges = state<ReadonlyArray<KnowledgeEdge<TRelation>>>([], {\n\t\tname: \"edges\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst adjacency = derived(\n\t\t[edges],\n\t\t([rows]) => {\n\t\t\tconst typed = (rows ?? []) as ReadonlyArray<KnowledgeEdge<TRelation>>;\n\t\t\tconst out = new Map<string, ReadonlyArray<KnowledgeEdge<TRelation>>>();\n\t\t\tfor (const edge of typed) {\n\t\t\t\tconst prev = out.get(edge.from) ?? [];\n\t\t\t\tout.set(edge.from, Object.freeze([...prev, edge]));\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t\t{ name: \"adjacency\", describeKind: \"derived\", initial: new Map() },\n\t);\n\tvoid adjacency.subscribe(() => undefined);\n\n\tgraph.add(\"entities\", entities);\n\tgraph.add(\"edges\", edges);\n\tgraph.add(\"adjacency\", adjacency);\n\tgraph.connect(\"edges\", \"adjacency\");\n\n\tfunction commitEntities(next: Map<string, TEntity>): void {\n\t\tentities.down([[DATA, next]]);\n\t}\n\n\tfunction commitEdges(next: ReadonlyArray<KnowledgeEdge<TRelation>>): void {\n\t\tedges.down([[DATA, next]]);\n\t}\n\n\tconst out = Object.assign(graph, {\n\t\tupsertEntity(id: string, value: TEntity) {\n\t\t\tconst next = copyMap(readMap(entities));\n\t\t\tnext.set(id, value);\n\t\t\tcommitEntities(next);\n\t\t},\n\t\tremoveEntity(id: string) {\n\t\t\tconst nextEntities = copyMap(readMap(entities));\n\t\t\tconst existed = nextEntities.delete(id);\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst nextEdges = currentEdges.filter((edge) => edge.from !== id && edge.to !== id);\n\t\t\tif (!existed && nextEdges.length === currentEdges.length) return;\n\t\t\tcommitEntities(nextEntities);\n\t\t\tcommitEdges(nextEdges);\n\t\t},\n\t\tlink(from: string, to: string, relation: TRelation, weight = 1) {\n\t\t\tconst key = `${from}\\u0000${to}\\u0000${relation}`;\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst existing = new Set(\n\t\t\t\tcurrentEdges.map((edge) => `${edge.from}\\u0000${edge.to}\\u0000${edge.relation}`),\n\t\t\t);\n\t\t\tconst next = [...currentEdges];\n\t\t\tif (existing.has(key)) {\n\t\t\t\tfor (let i = 0; i < next.length; i += 1) {\n\t\t\t\t\tconst edge = next[i]!;\n\t\t\t\t\tif (edge.from === from && edge.to === to && edge.relation === relation) {\n\t\t\t\t\t\tnext[i] = { ...edge, weight };\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnext.push({ from, to, relation, weight });\n\t\t\t}\n\t\t\tcommitEdges(next);\n\t\t},\n\t\tunlink(from: string, to: string, relation?: TRelation) {\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst next = currentEdges.filter((edge) =>\n\t\t\t\trelation === undefined\n\t\t\t\t\t? !(edge.from === from && edge.to === to)\n\t\t\t\t\t: !(edge.from === from && edge.to === to && edge.relation === relation),\n\t\t\t);\n\t\t\tif (next.length === currentEdges.length) return;\n\t\t\tcommitEdges(next);\n\t\t},\n\t\trelated(id: string, relation?: TRelation): ReadonlyArray<KnowledgeEdge<TRelation>> {\n\t\t\treturn readArray(edges).filter(\n\t\t\t\t(edge) =>\n\t\t\t\t\t(edge.from === id || edge.to === id) &&\n\t\t\t\t\t(relation === undefined || edge.relation === relation),\n\t\t\t);\n\t\t},\n\t}) as KnowledgeGraphGraph<TEntity, TRelation>;\n\treturn out;\n}\n","/**\n * Messaging patterns (roadmap §4.2).\n *\n * Pulsar-inspired messaging features modeled as graph factories:\n * - `topic()` for append-only topic streams\n * - `subscription()` for cursor-based consumers\n * - `jobQueue()` for queue claim/ack flow\n */\n\nimport { DATA, derived, type Node, node, state } from \"../core/index.js\";\nimport { type ReactiveListSnapshot, reactiveList } from \"../extra/reactive-list.js\";\nimport { type ReactiveLogSnapshot, reactiveLog } from \"../extra/reactive-log.js\";\nimport { type ReactiveMapSnapshot, reactiveMap } from \"../extra/reactive-map.js\";\nimport { Graph, type GraphOptions } from \"../graph/index.js\";\n\ntype MessagingMeta = {\n\tmessaging?: true;\n\tmessaging_type?: string;\n};\n\nconst DEFAULT_MAX_PER_PUMP = 2_147_483_647;\n\nfunction requireNonNegativeInt(value: number, label: string): number {\n\tif (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n\t\tthrow new Error(`${label} must be a non-negative integer`);\n\t}\n\treturn value;\n}\n\n/**\n * Keep a derived node's dep wiring alive for `get()` without a user sink.\n * Returns the unsubscribe handle so callers can clean up.\n */\nfunction keepalive(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => {});\n}\n\nfunction messagingMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn {\n\t\tmessaging: true,\n\t\tmessaging_type: kind,\n\t\t...(extra ?? {}),\n\t} satisfies MessagingMeta;\n}\n\nexport type TopicOptions = {\n\tgraph?: GraphOptions;\n\tretainedLimit?: number;\n};\n\nexport class TopicGraph<T> extends Graph {\n\tprivate readonly _log;\n\tprivate readonly _keepaliveDisposers: Array<() => void> = [];\n\treadonly events: Node<ReactiveLogSnapshot<T>>;\n\treadonly latest: Node<T | undefined>;\n\n\tconstructor(name: string, opts: TopicOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._log = reactiveLog<T>([], { name: \"events\", maxSize: opts.retainedLimit });\n\t\tthis.events = this._log.entries;\n\t\tthis.add(\"events\", this.events);\n\t\tthis.latest = derived<T | undefined>(\n\t\t\t[this.events],\n\t\t\t([snapshot]) => {\n\t\t\t\tconst entries = (snapshot as ReactiveLogSnapshot<T>).value.entries;\n\t\t\t\treturn entries.length === 0 ? undefined : entries[entries.length - 1];\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"latest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"topic_latest\"),\n\t\t\t\tinitial: undefined,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"latest\", this.latest);\n\t\tthis.connect(\"events\", \"latest\");\n\t\tthis._keepaliveDisposers.push(keepalive(this.latest));\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const dispose of this._keepaliveDisposers) dispose();\n\t\tthis._keepaliveDisposers.length = 0;\n\t\tsuper.destroy();\n\t}\n\n\tpublish(value: T): void {\n\t\tthis._log.append(value);\n\t}\n\n\tretained(): readonly T[] {\n\t\tconst snapshot = this.events.get() as ReactiveLogSnapshot<T>;\n\t\treturn snapshot.value.entries;\n\t}\n}\n\nexport type SubscriptionOptions = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n};\n\nexport class SubscriptionGraph<T> extends Graph {\n\tprivate readonly _keepaliveDisposers: Array<() => void> = [];\n\treadonly source: Node<ReactiveLogSnapshot<T>>;\n\treadonly cursor: Node<number>;\n\treadonly available: Node<readonly T[]>;\n\n\tconstructor(name: string, topicGraph: TopicGraph<T>, opts: SubscriptionOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst initialCursor = requireNonNegativeInt(opts.cursor ?? 0, \"subscription cursor\");\n\t\tthis.mount(\"topic\", topicGraph);\n\t\tconst topicEvents = topicGraph.events;\n\t\tthis.source = derived([topicEvents], ([snapshot]) => snapshot as ReactiveLogSnapshot<T>, {\n\t\t\tname: \"source\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: messagingMeta(\"subscription_source\"),\n\t\t\tinitial: topicEvents.get() as ReactiveLogSnapshot<T>,\n\t\t});\n\t\tthis.add(\"source\", this.source);\n\t\tthis.cursor = state(initialCursor, {\n\t\t\tname: \"cursor\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"subscription_cursor\"),\n\t\t});\n\t\tthis.add(\"cursor\", this.cursor);\n\t\tthis.available = derived(\n\t\t\t[this.source, this.cursor],\n\t\t\t([sourceSnapshot, cursor]) => {\n\t\t\t\tconst entries = (sourceSnapshot as ReactiveLogSnapshot<T>).value.entries;\n\t\t\t\tconst start = Math.max(0, Math.trunc((cursor as number) ?? 0));\n\t\t\t\treturn entries.slice(start);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"available\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"subscription_available\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tthis.add(\"available\", this.available);\n\t\tthis.connect(\"topic::events\", \"source\");\n\t\tthis.connect(\"source\", \"available\");\n\t\tthis.connect(\"cursor\", \"available\");\n\t\tthis._keepaliveDisposers.push(keepalive(this.source));\n\t\tthis._keepaliveDisposers.push(keepalive(this.available));\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const dispose of this._keepaliveDisposers) dispose();\n\t\tthis._keepaliveDisposers.length = 0;\n\t\tsuper.destroy();\n\t}\n\n\tack(count?: number): number {\n\t\tconst available = this.available.get() as readonly T[];\n\t\tconst requested =\n\t\t\tcount === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(count, \"subscription ack count\");\n\t\tconst step = Math.min(requested, available.length);\n\t\tif (step <= 0) return this.cursor.get() as number;\n\t\tconst next = (this.cursor.get() as number) + step;\n\t\tthis.cursor.down([[DATA, next]]);\n\t\treturn next;\n\t}\n\n\tpull(limit?: number, opts: { ack?: boolean } = {}): readonly T[] {\n\t\tconst available = this.available.get() as readonly T[];\n\t\tconst max =\n\t\t\tlimit === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(limit, \"subscription pull limit\");\n\t\tconst out = available.slice(0, max);\n\t\tif (opts.ack && out.length > 0) this.ack(out.length);\n\t\treturn out;\n\t}\n}\n\nexport type JobState = \"queued\" | \"inflight\";\n\nexport type JobEnvelope<T> = {\n\tid: string;\n\tpayload: T;\n\tattempts: number;\n\tmetadata: Readonly<Record<string, unknown>>;\n\tstate: JobState;\n};\n\nexport type JobQueueOptions = {\n\tgraph?: GraphOptions;\n};\n\nexport class JobQueueGraph<T> extends Graph {\n\tprivate readonly _pending;\n\tprivate readonly _jobs;\n\tprivate readonly _keepaliveDisposers: Array<() => void> = [];\n\tprivate _seq = 0;\n\treadonly pending: Node<ReactiveListSnapshot<string>>;\n\treadonly jobs: Node<ReactiveMapSnapshot<string, JobEnvelope<T>>>;\n\treadonly depth: Node<number>;\n\n\tconstructor(name: string, opts: JobQueueOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._pending = reactiveList<string>([], { name: \"pending\" });\n\t\tthis._jobs = reactiveMap<string, JobEnvelope<T>>({ name: \"jobs\" });\n\t\tthis.pending = this._pending.items;\n\t\tthis.jobs = this._jobs.node;\n\t\tthis.add(\"pending\", this.pending);\n\t\tthis.add(\"jobs\", this.jobs);\n\t\tthis.depth = derived(\n\t\t\t[this.pending],\n\t\t\t([snapshot]) => (snapshot as ReactiveListSnapshot<string>).value.items.length,\n\t\t\t{\n\t\t\t\tname: \"depth\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"queue_depth\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"depth\", this.depth);\n\t\tthis.connect(\"pending\", \"depth\");\n\t\tthis._keepaliveDisposers.push(keepalive(this.depth));\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const dispose of this._keepaliveDisposers) dispose();\n\t\tthis._keepaliveDisposers.length = 0;\n\t\tsuper.destroy();\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\tconst id = opts.id ?? `${this.name}-${++this._seq}`;\n\t\tif (this._jobs.get(id) !== undefined) {\n\t\t\tthrow new Error(`jobQueue(\"${this.name}\"): duplicate job id \"${id}\"`);\n\t\t}\n\t\tconst job: JobEnvelope<T> = {\n\t\t\tid,\n\t\t\tpayload,\n\t\t\tattempts: 0,\n\t\t\tmetadata: Object.freeze({ ...(opts.metadata ?? {}) }),\n\t\t\tstate: \"queued\",\n\t\t};\n\t\tthis._jobs.set(id, job);\n\t\tthis._pending.append(id);\n\t\treturn id;\n\t}\n\n\tclaim(limit = 1): readonly JobEnvelope<T>[] {\n\t\tconst max = requireNonNegativeInt(limit, \"job queue claim limit\");\n\t\tif (max === 0) return [];\n\t\tconst out: JobEnvelope<T>[] = [];\n\t\twhile (out.length < max) {\n\t\t\tconst snapshot = this.pending.get() as ReactiveListSnapshot<string>;\n\t\t\tconst ids = snapshot.value.items;\n\t\t\tif (ids.length === 0) break;\n\t\t\tconst id = this._pending.pop(0);\n\t\t\tconst job = this._jobs.get(id);\n\t\t\tif (!job || job.state !== \"queued\") continue;\n\t\t\tconst inflight: JobEnvelope<T> = {\n\t\t\t\t...job,\n\t\t\t\tstate: \"inflight\",\n\t\t\t\tattempts: job.attempts + 1,\n\t\t\t};\n\t\t\tthis._jobs.set(id, inflight);\n\t\t\tout.push(inflight);\n\t\t}\n\t\treturn out;\n\t}\n\n\tack(id: string): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n\n\tnack(id: string, opts: { requeue?: boolean } = {}): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tif (opts.requeue ?? true) {\n\t\t\tthis._jobs.set(id, { ...job, state: \"queued\" });\n\t\t\tthis._pending.append(id);\n\t\t\treturn true;\n\t\t}\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n}\n\nexport type JobFlowOptions = {\n\tgraph?: GraphOptions;\n\tstages?: readonly string[];\n\tmaxPerPump?: number;\n};\n\nexport class JobFlowGraph<T> extends Graph {\n\tprivate readonly _stageNames: readonly string[];\n\tprivate readonly _queues = new Map<string, JobQueueGraph<T>>();\n\tprivate readonly _keepaliveDisposers: Array<() => void> = [];\n\tprivate readonly _completed;\n\treadonly completed: Node<ReactiveLogSnapshot<JobEnvelope<T>>>;\n\treadonly completedCount: Node<number>;\n\n\tconstructor(name: string, opts: JobFlowOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst stages = (opts.stages ?? [\"incoming\", \"processing\", \"done\"]).map((v) => v.trim());\n\t\tif (stages.length < 2) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): requires at least 2 stages`);\n\t\t}\n\t\tconst unique = new Set(stages);\n\t\tif (unique.size !== stages.length) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): stage names must be unique`);\n\t\t}\n\t\tthis._stageNames = Object.freeze([...stages]);\n\t\tfor (const stage of this._stageNames) {\n\t\t\tconst q = jobQueue<T>(`${name}-${stage}`);\n\t\t\tthis._queues.set(stage, q);\n\t\t\tthis.mount(stage, q);\n\t\t}\n\t\tthis._completed = reactiveLog<JobEnvelope<T>>([], { name: \"completed\" });\n\t\tthis.completed = this._completed.entries;\n\t\tthis.add(\"completed\", this.completed);\n\t\tthis.completedCount = derived(\n\t\t\t[this.completed],\n\t\t\t([snapshot]) => (snapshot as ReactiveLogSnapshot<JobEnvelope<T>>).value.entries.length,\n\t\t\t{\n\t\t\t\tname: \"completedCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"job_flow_completed_count\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"completedCount\", this.completedCount);\n\t\tthis.connect(\"completed\", \"completedCount\");\n\t\tthis._keepaliveDisposers.push(keepalive(this.completedCount));\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"job flow maxPerPump\"),\n\t\t);\n\t\tfor (let i = 0; i < this._stageNames.length; i += 1) {\n\t\t\tconst stage = this._stageNames[i] as string;\n\t\t\tconst current = this.queue(stage);\n\t\t\tconst next =\n\t\t\t\ti + 1 < this._stageNames.length ? this.queue(this._stageNames[i + 1] as string) : null;\n\t\t\tconst pump = node<unknown>(\n\t\t\t\t[current.pending],\n\t\t\t\t() => {\n\t\t\t\t\tlet moved = 0;\n\t\t\t\t\twhile (moved < maxPerPump) {\n\t\t\t\t\t\tconst claim = current.claim(1);\n\t\t\t\t\t\tif (claim.length === 0) break;\n\t\t\t\t\t\tconst job = claim[0] as JobEnvelope<T>;\n\t\t\t\t\t\tif (!job) break;\n\t\t\t\t\t\tif (next) {\n\t\t\t\t\t\t\tnext.enqueue(job.payload, {\n\t\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\t\t...job.metadata,\n\t\t\t\t\t\t\t\t\tjob_flow_from: stage,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis._completed.append(job);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrent.ack(job.id);\n\t\t\t\t\t\tmoved += 1;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `pump_${stage}`,\n\t\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\t\tmeta: messagingMeta(\"job_flow_pump\"),\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.add(`pump_${stage}`, pump);\n\t\t\tthis.connect(`${stage}::pending`, `pump_${stage}`);\n\t\t\tthis._keepaliveDisposers.push(keepalive(pump));\n\t\t}\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const dispose of this._keepaliveDisposers) dispose();\n\t\tthis._keepaliveDisposers.length = 0;\n\t\tsuper.destroy();\n\t}\n\n\tstages(): readonly string[] {\n\t\treturn this._stageNames;\n\t}\n\n\tqueue(stage: string): JobQueueGraph<T> {\n\t\tconst q = this._queues.get(stage);\n\t\tif (!q) throw new Error(`jobFlow(\"${this.name}\"): unknown stage \"${stage}\"`);\n\t\treturn q;\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\treturn this.queue(this._stageNames[0] as string).enqueue(payload, opts);\n\t}\n\n\tretainedCompleted(): readonly JobEnvelope<T>[] {\n\t\tconst snapshot = this.completed.get() as ReactiveLogSnapshot<JobEnvelope<T>>;\n\t\treturn snapshot.value.entries;\n\t}\n}\n\nexport type TopicBridgeOptions<TIn, TOut> = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n\tmaxPerPump?: number;\n\tmap?: (value: TIn) => TOut | undefined;\n};\n\nexport class TopicBridgeGraph<TIn, TOut = TIn> extends Graph {\n\tprivate readonly _sourceSub;\n\tprivate readonly _target;\n\tprivate readonly _keepaliveDisposers: Array<() => void> = [];\n\treadonly bridgedCount: Node<number>;\n\n\tconstructor(\n\t\tname: string,\n\t\tsourceTopic: TopicGraph<TIn>,\n\t\ttargetTopic: TopicGraph<TOut>,\n\t\topts: TopicBridgeOptions<TIn, TOut> = {},\n\t) {\n\t\tsuper(name, opts.graph);\n\t\tthis._sourceSub = subscription<TIn>(`${name}-subscription`, sourceTopic, {\n\t\t\tcursor: opts.cursor,\n\t\t});\n\t\tthis._target = targetTopic;\n\t\tthis.mount(\"subscription\", this._sourceSub);\n\t\tthis.bridgedCount = state(0, {\n\t\t\tname: \"bridgedCount\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"topic_bridge_count\"),\n\t\t});\n\t\tthis.add(\"bridgedCount\", this.bridgedCount);\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"topic bridge maxPerPump\"),\n\t\t);\n\t\tconst mapValue = opts.map ?? ((value: TIn) => value as unknown as TOut);\n\t\tconst pump = node<unknown>(\n\t\t\t[this._sourceSub.available],\n\t\t\t() => {\n\t\t\t\tconst available = this._sourceSub.pull(maxPerPump, { ack: true });\n\t\t\t\tif (available.length === 0) return;\n\t\t\t\tlet bridged = 0;\n\t\t\t\tfor (const value of available) {\n\t\t\t\t\tconst mapped = mapValue(value as TIn);\n\t\t\t\t\tif (mapped === undefined) continue;\n\t\t\t\t\tthis._target.publish(mapped);\n\t\t\t\t\tbridged += 1;\n\t\t\t\t}\n\t\t\t\tif (bridged > 0) {\n\t\t\t\t\tconst current = this.bridgedCount.get() as number;\n\t\t\t\t\tthis.bridgedCount.down([[DATA, current + bridged]]);\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"pump\",\n\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\tmeta: messagingMeta(\"topic_bridge_pump\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"pump\", pump);\n\t\tthis.connect(\"subscription::available\", \"pump\");\n\t\tthis._keepaliveDisposers.push(keepalive(pump));\n\t}\n\n\toverride destroy(): void {\n\t\tfor (const dispose of this._keepaliveDisposers) dispose();\n\t\tthis._keepaliveDisposers.length = 0;\n\t\tsuper.destroy();\n\t}\n}\n\n/**\n * Creates a Pulsar-inspired topic graph (append-only retained stream + latest value).\n */\nexport function topic<T>(name: string, opts?: TopicOptions): TopicGraph<T> {\n\treturn new TopicGraph<T>(name, opts);\n}\n\n/**\n * Creates a cursor-based subscription graph over a topic.\n */\nexport function subscription<T>(\n\tname: string,\n\ttopicGraph: TopicGraph<T>,\n\topts?: SubscriptionOptions,\n): SubscriptionGraph<T> {\n\treturn new SubscriptionGraph<T>(name, topicGraph, opts);\n}\n\n/**\n * Creates a Pulsar-inspired job queue graph with claim/ack/nack workflow.\n */\nexport function jobQueue<T>(name: string, opts?: JobQueueOptions): JobQueueGraph<T> {\n\treturn new JobQueueGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous multi-stage queue chain graph.\n */\nexport function jobFlow<T>(name: string, opts?: JobFlowOptions): JobFlowGraph<T> {\n\treturn new JobFlowGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous cursor-based topic relay graph.\n */\nexport function topicBridge<TIn, TOut = TIn>(\n\tname: string,\n\tsourceTopic: TopicGraph<TIn>,\n\ttargetTopic: TopicGraph<TOut>,\n\topts?: TopicBridgeOptions<TIn, TOut>,\n): TopicBridgeGraph<TIn, TOut> {\n\treturn new TopicBridgeGraph<TIn, TOut>(name, sourceTopic, targetTopic, opts);\n}\n","/**\n * Orchestration patterns (roadmap §4.1).\n *\n * Domain-layer helpers that build workflow shapes on top of core + extra primitives.\n * Exported under the `patterns.orchestration` namespace to avoid collisions with\n * Phase 2 operator names (for example `gate`, `forEach`).\n */\n\nimport { COMPLETE, DATA, ERROR, type Message, type Messages, RESOLVED } from \"../core/messages.js\";\nimport { type Node, type NodeActions, type NodeFn, type NodeOptions, node } from \"../core/node.js\";\nimport { GRAPH_META_SEGMENT, Graph, type GraphOptions } from \"../graph/graph.js\";\n\nexport type StepRef = string | Node<unknown>;\n\ntype OrchestrationMeta = {\n\torchestration?: true;\n\torchestration_type?: string;\n};\n\nexport type OrchestrationStepOptions = Omit<NodeOptions, \"describeKind\" | \"name\" | \"meta\"> & {\n\tdeps?: ReadonlyArray<StepRef>;\n\tmeta?: Record<string, unknown> & OrchestrationMeta;\n};\n\nexport type BranchResult<T> = {\n\tbranch: \"then\" | \"else\";\n\tvalue: T;\n};\n\nexport type SensorControls<T> = {\n\tnode: Node<T>;\n\tpush(value: T): void;\n\terror(err: unknown): void;\n\tcomplete(): void;\n};\n\nexport type LoopOptions = Omit<OrchestrationStepOptions, \"deps\"> & {\n\titerations?: number | StepRef;\n};\n\nexport type WaitOptions = Omit<OrchestrationStepOptions, \"deps\">;\n\nexport type SubPipelineBuilder = (sub: Graph) => void;\n\nfunction resolveDep(graph: Graph, dep: StepRef): { node: Node<unknown>; path?: string } {\n\tif (typeof dep === \"string\") {\n\t\treturn { node: graph.resolve(dep), path: dep };\n\t}\n\tconst path = findRegisteredNodePath(graph, dep);\n\tif (!path) {\n\t\tthrow new Error(\n\t\t\t\"orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first\",\n\t\t);\n\t}\n\treturn { node: dep, path };\n}\n\nfunction findRegisteredNodePath(graph: Graph, target: Node<unknown>): string | undefined {\n\tconst described = graph.describe();\n\tconst metaSegment = `::${GRAPH_META_SEGMENT}::`;\n\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\ttry {\n\t\t\tif (graph.resolve(path) === target) return path;\n\t\t} catch {\n\t\t\t/* ignore stale path while scanning */\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction registerStep(\n\tgraph: Graph,\n\tname: string,\n\tstep: Node<unknown>,\n\tdepPaths: ReadonlyArray<string>,\n): void {\n\tgraph.add(name, step);\n\tfor (const path of depPaths) {\n\t\tgraph.connect(path, name);\n\t}\n}\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn {\n\t\torchestration: true,\n\t\torchestration_type: kind,\n\t\t...(meta ?? {}),\n\t};\n}\n\nfunction coerceLoopIterations(raw: unknown): number {\n\tconst parseString = (value: string): number => {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed.length === 0) return 0;\n\t\treturn Number(trimmed);\n\t};\n\tlet parsed: number;\n\tif (typeof raw === \"string\") {\n\t\tparsed = parseString(raw);\n\t} else if (raw === null) {\n\t\tparsed = 0;\n\t} else {\n\t\tparsed = Number(raw);\n\t}\n\tif (!Number.isFinite(parsed)) return 1;\n\treturn Math.max(0, Math.trunc(parsed));\n}\n\n/**\n * Creates an orchestration graph container.\n */\nexport function pipeline(name: string, opts?: GraphOptions): Graph {\n\treturn new Graph(name, opts);\n}\n\n/**\n * Registers a workflow task node.\n */\nexport function task<T>(\n\tgraph: Graph,\n\tname: string,\n\trun: NodeFn<T>,\n\topts?: OrchestrationStepOptions,\n): Node<T> {\n\tconst depRefs = opts?.deps ?? [];\n\tconst deps = depRefs.map((dep) => resolveDep(graph, dep));\n\tconst { deps: _deps, ...nodeOpts } = opts ?? {};\n\tconst step = node<T>(\n\t\tdeps.map((d) => d.node),\n\t\trun,\n\t\t{\n\t\t\t...nodeOpts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"task\", opts?.meta),\n\t\t},\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\tdeps.flatMap((d) => (d.path ? [d.path] : [])),\n\t);\n\treturn step;\n}\n\n/**\n * Emits tagged branch outcomes (`then` / `else`) for each source value.\n */\nexport function branch<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tpredicate: (value: T) => boolean,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<BranchResult<T>> {\n\tconst src = resolveDep(graph, source);\n\tconst step = node<BranchResult<T>>(\n\t\t[src.node],\n\t\t([value]) => ({\n\t\t\tbranch: predicate(value as T) ? \"then\" : \"else\",\n\t\t\tvalue: value as T,\n\t\t}),\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"branch\", opts?.meta),\n\t\t},\n\t);\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n\n/**\n * Forwards source values only while `control` is truthy.\n */\nexport function gate<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tcontrol: StepRef,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst ctrl = resolveDep(graph, control);\n\tconst step = node<T>(\n\t\t[src.node, ctrl.node],\n\t\t(_deps, actions) => {\n\t\t\tconst opened = ctrl.node.get();\n\t\t\tif (!opened) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn src.node.get() as T;\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"operator\",\n\t\t\tmeta: baseMeta(\"gate\", opts?.meta),\n\t\t},\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, ctrl.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\nexport type ApprovalOptions = Omit<OrchestrationStepOptions, \"deps\"> & {\n\tisApproved?: (value: unknown) => boolean;\n};\n\n/**\n * Human/LLM approval gate over a source value.\n */\nexport function approval<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tapprover: StepRef,\n\topts?: ApprovalOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst ctrl = resolveDep(graph, approver);\n\tconst isApproved = opts?.isApproved ?? ((value: unknown) => Boolean(value));\n\tconst step = node<T>(\n\t\t[src.node, ctrl.node],\n\t\t(_deps, actions: NodeActions) => {\n\t\t\tif (!isApproved(ctrl.node.get())) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn src.node.get() as T;\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"operator\",\n\t\t\tmeta: baseMeta(\"approval\", opts?.meta),\n\t\t},\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, ctrl.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\n/**\n * Registers a workflow side-effect step. The step remains graph-observable and forwards messages.\n */\nexport function forEach<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\trun: (value: T, actions: NodeActions) => void,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tlet terminated = false;\n\tconst step = node<T>([src.node], () => undefined, {\n\t\t...opts,\n\t\tname,\n\t\tdescribeKind: \"effect\",\n\t\tcompleteWhenDepsComplete: false,\n\t\tmeta: baseMeta(\"forEach\", opts?.meta),\n\t\tonMessage(msg: Message, depIndex: number, actions: NodeActions) {\n\t\t\tif (terminated) return true;\n\t\t\tif (depIndex !== 0) {\n\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\tif (msg[0] === COMPLETE || msg[0] === ERROR) terminated = true;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (msg[0] === DATA) {\n\t\t\t\ttry {\n\t\t\t\t\trun(msg[1] as T, actions);\n\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tterminated = true;\n\t\t\t\t\tactions.down([[ERROR, err]] satisfies Messages);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tactions.down([msg] satisfies Messages);\n\t\t\tif (msg[0] === COMPLETE || msg[0] === ERROR) terminated = true;\n\t\t\treturn true;\n\t\t},\n\t});\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n\n/**\n * Registers a join step that emits a tuple of latest dependency values.\n */\nexport function join<T extends readonly unknown[]>(\n\tgraph: Graph,\n\tname: string,\n\tdeps: { [K in keyof T]: StepRef },\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst resolved = deps.map((dep) => resolveDep(graph, dep));\n\tconst step = node<T>(\n\t\tresolved.map((d) => d.node),\n\t\t(values) => values as T,\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"join\", opts?.meta),\n\t\t},\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\tresolved.flatMap((d) => (d.path ? [d.path] : [])),\n\t);\n\treturn step;\n}\n\n/**\n * Registers a loop step that applies `iterate` to each source value N times.\n */\nexport function loop<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\titerate: (value: T, iteration: number, actions: NodeActions) => T,\n\topts?: LoopOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst iterRef = opts?.iterations;\n\tconst iterDep =\n\t\ttypeof iterRef === \"number\" || iterRef === undefined ? undefined : resolveDep(graph, iterRef);\n\tconst staticIterations = typeof iterRef === \"number\" ? iterRef : undefined;\n\tconst step = node<T>(\n\t\titerDep ? [src.node, iterDep.node] : [src.node],\n\t\t(_deps, actions) => {\n\t\t\tlet current = src.node.get() as T;\n\t\t\tconst rawCount = staticIterations ?? iterDep?.node.get() ?? 1;\n\t\t\tconst count = coerceLoopIterations(rawCount);\n\t\t\tfor (let i = 0; i < count; i += 1) {\n\t\t\t\tcurrent = iterate(current, i, actions);\n\t\t\t}\n\t\t\treturn current;\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"loop\", opts?.meta),\n\t\t},\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, iterDep?.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\n/**\n * Mounts and returns a child workflow graph.\n */\nexport function subPipeline(\n\tgraph: Graph,\n\tname: string,\n\tchildOrBuild?: Graph | SubPipelineBuilder,\n\topts?: GraphOptions,\n): Graph {\n\tconst child = childOrBuild instanceof Graph ? childOrBuild : pipeline(name, opts);\n\tif (typeof childOrBuild === \"function\") {\n\t\tchildOrBuild(child);\n\t}\n\tgraph.mount(name, child);\n\treturn child;\n}\n\n/**\n * Registers a producer-style sensor source and returns imperative controls.\n */\nexport function sensor<T>(\n\tgraph: Graph,\n\tname: string,\n\tinitial?: T,\n\topts?: Omit<NodeOptions, \"name\" | \"describeKind\" | \"meta\"> & {\n\t\tmeta?: Record<string, unknown>;\n\t},\n): SensorControls<T> {\n\tconst source = node<T>([], () => undefined, {\n\t\t...opts,\n\t\tname,\n\t\tinitial,\n\t\tdescribeKind: \"producer\",\n\t\tmeta: baseMeta(\"sensor\", opts?.meta),\n\t});\n\tregisterStep(graph, name, source as unknown as Node<unknown>, []);\n\treturn {\n\t\tnode: source,\n\t\tpush(value: T) {\n\t\t\tsource.down([[DATA, value]] satisfies Messages);\n\t\t},\n\t\terror(err: unknown) {\n\t\t\tsource.down([[ERROR, err]] satisfies Messages);\n\t\t},\n\t\tcomplete() {\n\t\t\tsource.down([[COMPLETE]] satisfies Messages);\n\t\t},\n\t};\n}\n\n/**\n * Registers a delayed-forwarding step (value-level wait).\n */\nexport function wait<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tms: number,\n\topts?: WaitOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst timers = new Set<ReturnType<typeof setTimeout>>();\n\tlet terminated = false;\n\tlet completed = false;\n\tconst step = node<T>(\n\t\t[src.node],\n\t\t() => {\n\t\t\tfor (const id of timers) clearTimeout(id);\n\t\t\ttimers.clear();\n\t\t\treturn () => {\n\t\t\t\tfor (const id of timers) clearTimeout(id);\n\t\t\t\ttimers.clear();\n\t\t\t\tterminated = true;\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tinitial: src.node.get() as T,\n\t\t\tdescribeKind: \"operator\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tmeta: baseMeta(\"wait\", opts?.meta),\n\t\t\tonMessage(msg: Message, depIndex: number, actions: NodeActions) {\n\t\t\t\tif (terminated) return true;\n\t\t\t\tif (depIndex !== 0) {\n\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\tif (msg[0] === COMPLETE || msg[0] === ERROR) terminated = true;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\tconst id = setTimeout(() => {\n\t\t\t\t\t\ttimers.delete(id);\n\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t\tif (completed && timers.size === 0) {\n\t\t\t\t\t\t\tactions.down([[COMPLETE]] satisfies Messages);\n\t\t\t\t\t\t}\n\t\t\t\t\t}, ms);\n\t\t\t\t\ttimers.add(id);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\tterminated = true;\n\t\t\t\t\tcompleted = true;\n\t\t\t\t\tif (timers.size === 0) {\n\t\t\t\t\t\tactions.down([[COMPLETE]] satisfies Messages);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === ERROR) {\n\t\t\t\t\tterminated = true;\n\t\t\t\t\tfor (const id of timers) clearTimeout(id);\n\t\t\t\t\ttimers.clear();\n\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n\n/**\n * Registers an error-recovery step for a source.\n */\nexport function onFailure<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\trecover: (err: unknown, actions: NodeActions) => T,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tlet terminated = false;\n\tconst step = node<T>([src.node], () => undefined, {\n\t\t...opts,\n\t\tname,\n\t\tdescribeKind: \"operator\",\n\t\tcompleteWhenDepsComplete: false,\n\t\tmeta: baseMeta(\"onFailure\", opts?.meta),\n\t\tonMessage(msg: Message, _depIndex: number, actions: NodeActions) {\n\t\t\tif (terminated) return true;\n\t\t\tif (msg[0] === ERROR) {\n\t\t\t\ttry {\n\t\t\t\t\tactions.emit(recover(msg[1], actions));\n\t\t\t\t} catch (err) {\n\t\t\t\t\tterminated = true;\n\t\t\t\t\tactions.down([[ERROR, err]] satisfies Messages);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tactions.down([msg] satisfies Messages);\n\t\t\tif (msg[0] === COMPLETE) terminated = true;\n\t\t\treturn true;\n\t\t},\n\t});\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n","/**\n * Reactive layout pattern — standalone subpath export.\n *\n * ```ts\n * import { reactiveLayout, CliMeasureAdapter } from \"@graphrefly/graphrefly-ts/reactive-layout\";\n * ```\n */\n\nexport * from \"./measurement-adapters.js\";\nexport * from \"./reactive-block-layout.js\";\nexport * from \"./reactive-layout.js\";\n","/**\n * MeasurementAdapter implementations (roadmap §7.1 — pluggable backends).\n *\n * All adapters implement {@link MeasurementAdapter} from `reactive-layout.ts`.\n * Sync constructors, sync `measureSegment()` — no async, no polling.\n */\n\nimport type { MeasurementAdapter } from \"./reactive-layout.js\";\n\n// ---------------------------------------------------------------------------\n// Shared: East Asian Width detection for CLI adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Return the display-cell width of a single codepoint in a monospace terminal.\n * Fullwidth / wide CJK → 2 cells; combining marks → 0 cells; everything else → 1 cell.\n *\n * Approximates UAX #11 East_Asian_Width (W/F → 2). Not a full EAW table —\n * covers CJK, Hangul, fullwidth forms, common emoji, and Extensions B-G.\n * Python's `unicodedata.east_asian_width()` is authoritative; this tracks it\n * closely but may diverge on rare/ambiguous codepoints.\n */\nfunction cellWidth(code: number): 0 | 1 | 2 {\n\t// Combining marks (Mn, Mc, Me) → 0 cells\n\tif (\n\t\t(code >= 0x0300 && code <= 0x036f) || // Combining Diacritical Marks\n\t\t(code >= 0x0483 && code <= 0x0489) || // Cyrillic combining marks\n\t\t(code >= 0x0591 && code <= 0x05bd) || // Hebrew combining marks\n\t\t(code >= 0x0610 && code <= 0x061a) || // Arabic combining marks\n\t\t(code >= 0x064b && code <= 0x065f) || // Arabic combining marks\n\t\t(code >= 0x0670 && code === 0x0670) || // Arabic superscript alef\n\t\t(code >= 0x06d6 && code <= 0x06dc) || // Arabic combining marks\n\t\t(code >= 0x06df && code <= 0x06e4) || // Arabic combining marks\n\t\t(code >= 0x06e7 && code <= 0x06e8) || // Arabic combining marks\n\t\t(code >= 0x06ea && code <= 0x06ed) || // Arabic combining marks\n\t\t(code >= 0x0730 && code <= 0x074a) || // Syriac combining marks\n\t\t(code >= 0x07a6 && code <= 0x07b0) || // Thaana combining marks\n\t\t(code >= 0x0900 && code <= 0x0903) || // Devanagari combining marks\n\t\t(code >= 0x093a && code <= 0x094f) || // Devanagari combining marks\n\t\t(code >= 0x0951 && code <= 0x0957) || // Devanagari combining marks\n\t\t(code >= 0x0962 && code <= 0x0963) || // Devanagari combining marks\n\t\t(code >= 0x0981 && code <= 0x0983) || // Bengali combining marks\n\t\t(code >= 0x09bc && code <= 0x09cd) || // Bengali combining marks\n\t\t(code >= 0x0a01 && code <= 0x0a03) || // Gurmukhi combining marks\n\t\t(code >= 0x0a3c && code <= 0x0a51) || // Gurmukhi combining marks\n\t\t(code >= 0x0a70 && code <= 0x0a71) || // Gurmukhi combining marks\n\t\t(code >= 0x0a75 && code === 0x0a75) || // Gurmukhi combining mark\n\t\t(code >= 0x0e31 && code === 0x0e31) || // Thai combining mark\n\t\t(code >= 0x0e34 && code <= 0x0e3a) || // Thai combining marks\n\t\t(code >= 0x0e47 && code <= 0x0e4e) || // Thai combining marks\n\t\t(code >= 0x0eb1 && code === 0x0eb1) || // Lao combining mark\n\t\t(code >= 0x0eb4 && code <= 0x0ebc) || // Lao combining marks\n\t\t(code >= 0x0ec8 && code <= 0x0ece) || // Lao combining marks\n\t\t(code >= 0x1dc0 && code <= 0x1dff) || // Combining Diacritical Marks Supplement\n\t\t(code >= 0x20d0 && code <= 0x20ff) || // Combining Diacritical Marks for Symbols\n\t\t(code >= 0xfe00 && code <= 0xfe0f) || // Variation Selectors\n\t\t(code >= 0xfe20 && code <= 0xfe2f) || // Combining Half Marks\n\t\tcode === 0x200d // Zero Width Joiner\n\t) {\n\t\treturn 0;\n\t}\n\t// Wide / fullwidth → 2 cells\n\tif (\n\t\t(code >= 0x1100 && code <= 0x115f) || // Hangul Jamo\n\t\t(code >= 0x231a && code <= 0x231b) || // Watch, Hourglass\n\t\t(code >= 0x2329 && code <= 0x232a) || // Angle brackets\n\t\t(code >= 0x23e9 && code <= 0x23f3) || // Media control symbols\n\t\t(code >= 0x23f8 && code <= 0x23fa) || // Media control symbols\n\t\t(code >= 0x25fd && code <= 0x25fe) || // Medium squares\n\t\t(code >= 0x2614 && code <= 0x2615) || // Umbrella, Hot Beverage\n\t\t(code >= 0x2648 && code <= 0x2653) || // Zodiac symbols\n\t\tcode === 0x267f || // Wheelchair\n\t\tcode === 0x2693 || // Anchor\n\t\tcode === 0x26a1 || // High Voltage\n\t\t(code >= 0x26aa && code <= 0x26ab) || // Medium circles\n\t\t(code >= 0x26bd && code <= 0x26be) || // Soccer, Baseball\n\t\t(code >= 0x26c4 && code <= 0x26c5) || // Snowman, Sun behind cloud\n\t\tcode === 0x26ce || // Ophiuchus\n\t\tcode === 0x26d4 || // No Entry\n\t\tcode === 0x26ea || // Church\n\t\t(code >= 0x26f2 && code <= 0x26f3) || // Fountain, Golf\n\t\tcode === 0x26f5 || // Sailboat\n\t\tcode === 0x26fa || // Tent\n\t\tcode === 0x26fd || // Fuel Pump\n\t\tcode === 0x2702 || // Scissors\n\t\tcode === 0x2705 || // Check Mark\n\t\t(code >= 0x2708 && code <= 0x270d) || // Airplane...Writing Hand\n\t\tcode === 0x270f || // Pencil\n\t\t(code >= 0x2753 && code <= 0x2755) || // Question marks\n\t\tcode === 0x2757 || // Exclamation\n\t\t(code >= 0x2795 && code <= 0x2797) || // Plus, Minus, Divide\n\t\tcode === 0x27b0 || // Curly Loop\n\t\tcode === 0x27bf || // Double Curly Loop\n\t\t(code >= 0x2934 && code <= 0x2935) || // Arrows\n\t\t(code >= 0x2b05 && code <= 0x2b07) || // Arrows\n\t\t(code >= 0x2b1b && code <= 0x2b1c) || // Squares\n\t\tcode === 0x2b50 || // Star\n\t\tcode === 0x2b55 || // Circle\n\t\t(code >= 0x2e80 && code <= 0x303e) || // CJK Radicals, Symbols, Punctuation\n\t\t(code >= 0x3040 && code <= 0x309f) || // Hiragana\n\t\t(code >= 0x30a0 && code <= 0x30ff) || // Katakana\n\t\t(code >= 0x3105 && code <= 0x312f) || // Bopomofo\n\t\t(code >= 0x3131 && code <= 0x318e) || // Hangul Compatibility Jamo\n\t\t(code >= 0x3190 && code <= 0x31e3) || // Kanbun, CJK Strokes\n\t\t(code >= 0x31f0 && code <= 0x321e) || // Katakana Phonetic Extensions\n\t\t(code >= 0x3220 && code <= 0x3247) || // Enclosed CJK\n\t\t(code >= 0x3250 && code <= 0x4dbf) || // CJK Extensions + Unified block\n\t\t(code >= 0x4e00 && code <= 0x9fff) || // CJK Unified Ideographs\n\t\t(code >= 0xa960 && code <= 0xa97c) || // Hangul Jamo Extended-A\n\t\t(code >= 0xac00 && code <= 0xd7a3) || // Hangul Syllables\n\t\t(code >= 0xf900 && code <= 0xfaff) || // CJK Compatibility Ideographs\n\t\t(code >= 0xfe10 && code <= 0xfe19) || // Vertical forms\n\t\t(code >= 0xfe30 && code <= 0xfe6b) || // CJK Compatibility Forms\n\t\t(code >= 0xff01 && code <= 0xff60) || // Fullwidth Forms (excl. halfwidth)\n\t\t(code >= 0xffe0 && code <= 0xffe6) || // Fullwidth Signs\n\t\t(code >= 0x1f004 && code === 0x1f004) || // Mahjong Red Dragon\n\t\tcode === 0x1f0cf || // Joker\n\t\t(code >= 0x1f170 && code <= 0x1f171) || // A/B buttons\n\t\tcode === 0x1f17e || // O button\n\t\tcode === 0x1f17f || // P button\n\t\tcode === 0x1f18e || // AB button\n\t\t(code >= 0x1f191 && code <= 0x1f19a) || // Squared symbols\n\t\t(code >= 0x1f1e0 && code <= 0x1f1ff) || // Regional Indicator Symbols\n\t\t(code >= 0x1f200 && code <= 0x1f202) || // Enclosed ideographic\n\t\tcode === 0x1f21a || // Squared CJK\n\t\tcode === 0x1f22f || // Squared CJK\n\t\t(code >= 0x1f232 && code <= 0x1f23a) || // Squared CJK\n\t\t(code >= 0x1f250 && code <= 0x1f251) || // Circled ideographic\n\t\t(code >= 0x1f300 && code <= 0x1f9ff) || // Misc Symbols / Emoticons / Emoji\n\t\t(code >= 0x1fa00 && code <= 0x1faff) || // Chess, Symbols Extended-A\n\t\t(code >= 0x1fb00 && code <= 0x1fbff) || // Symbols for Legacy Computing\n\t\t(code >= 0x20000 && code <= 0x2fffd) || // CJK Extension B-F (excl. nonchars)\n\t\t(code >= 0x30000 && code <= 0x3fffd) // CJK Extension G+ (excl. nonchars)\n\t) {\n\t\treturn 2;\n\t}\n\treturn 1;\n}\n\n/**\n * Count total display cells for a string in a monospace terminal.\n *\n * Combining marks contribute 0 cells; CJK/fullwidth contribute 2.\n * Does not handle ZWJ emoji sequences (multi-codepoint clusters that\n * render as a single glyph) — terminal support for these varies widely.\n */\nfunction countCells(text: string): number {\n\tlet cells = 0;\n\tfor (const ch of text) {\n\t\tcells += cellWidth(ch.codePointAt(0)!);\n\t}\n\treturn cells;\n}\n\n// ---------------------------------------------------------------------------\n// CliMeasureAdapter\n// ---------------------------------------------------------------------------\n\nexport type CliMeasureAdapterOptions = {\n\t/** Pixel width per terminal cell (default: 8). */\n\tcellPx?: number;\n};\n\n/**\n * Monospace terminal measurement adapter.\n *\n * Width = cell count × `cellPx`. CJK / fullwidth characters count as 2 cells.\n * No external dependencies. Works in any JS environment.\n */\nexport class CliMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly cellPx: number;\n\n\tconstructor(opts?: CliMeasureAdapterOptions) {\n\t\tthis.cellPx = opts?.cellPx ?? 8;\n\t}\n\n\tmeasureSegment(text: string, _font: string): { width: number } {\n\t\treturn { width: countCells(text) * this.cellPx };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// PrecomputedAdapter\n// ---------------------------------------------------------------------------\n\nexport type PrecomputedAdapterOptions = {\n\t/**\n\t * Pre-computed metrics: `{ font: { segment: widthPx } }`.\n\t * Outer key is the CSS font string; inner key is the text segment.\n\t */\n\tmetrics: Record<string, Record<string, number>>;\n\t/**\n\t * Fallback when a segment is not found in the metrics map.\n\t * - `\"per-char\"`: sum individual character widths from the same font map (default)\n\t * - `\"error\"`: throw an error for unknown segments\n\t */\n\tfallback?: \"per-char\" | \"error\";\n};\n\nclass PrecomputedAdapterKeyError extends Error {\n\tname = \"KeyError\";\n}\n\n/**\n * Pre-computed measurement adapter for SSR / snapshot replay.\n *\n * Reads from a static metrics object — zero measurement at runtime.\n * Ideal for server-side rendering or replaying snapshotted layouts.\n */\nexport class PrecomputedAdapter implements MeasurementAdapter {\n\tprivate readonly metrics: Record<string, Record<string, number>>;\n\tprivate readonly fallback: \"per-char\" | \"error\";\n\n\tconstructor(opts: PrecomputedAdapterOptions) {\n\t\tthis.metrics = opts.metrics;\n\t\tconst fb = opts.fallback ?? \"per-char\";\n\t\tif (fb !== \"per-char\" && fb !== \"error\") {\n\t\t\t// Keep parity with Python: validate at runtime.\n\t\t\tthrow new Error(\n\t\t\t\t`fallback must be 'per-char' or 'error', got ${JSON.stringify(opts.fallback)}`,\n\t\t\t);\n\t\t}\n\t\tthis.fallback = fb;\n\t}\n\n\tmeasureSegment(text: string, font: string): { width: number } {\n\t\tconst fontMap = this.metrics[font];\n\t\tif (fontMap) {\n\t\t\tconst w = fontMap[text];\n\t\t\tif (w !== undefined) return { width: w };\n\t\t}\n\n\t\tif (this.fallback === \"error\") {\n\t\t\tthrow new PrecomputedAdapterKeyError(\n\t\t\t\t`PrecomputedAdapter: no metrics for segment ${JSON.stringify(text)} in font ${JSON.stringify(font)}`,\n\t\t\t);\n\t\t}\n\n\t\t// per-char fallback: sum individual character widths\n\t\tlet total = 0;\n\t\tif (fontMap) {\n\t\t\tfor (const ch of text) {\n\t\t\t\tconst cw = fontMap[ch];\n\t\t\t\tif (cw !== undefined) {\n\t\t\t\t\ttotal += cw;\n\t\t\t\t}\n\t\t\t\t// unknown char contributes 0 (best-effort)\n\t\t\t}\n\t\t}\n\t\treturn { width: total };\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// CanvasMeasureAdapter (browser)\n// ---------------------------------------------------------------------------\n\nexport type CanvasMeasureAdapterOptions = {\n\t/** Emoji width correction factor (default: 1, no correction). */\n\temojiCorrection?: number;\n};\n\n/**\n * Browser measurement adapter using `OffscreenCanvas.measureText()`.\n *\n * Lazily creates an OffscreenCanvas and 2D context on first call.\n * Requires a browser environment with OffscreenCanvas support.\n */\nexport class CanvasMeasureAdapter implements MeasurementAdapter {\n\tprivate ctx: OffscreenCanvasRenderingContext2D | null = null;\n\tprivate currentFont = \"\";\n\tprivate readonly emojiCorrection: number;\n\n\tconstructor(opts?: CanvasMeasureAdapterOptions) {\n\t\tthis.emojiCorrection = opts?.emojiCorrection ?? 1;\n\t}\n\n\tprivate getContext(): OffscreenCanvasRenderingContext2D {\n\t\tif (!this.ctx) {\n\t\t\tif (typeof OffscreenCanvas === \"undefined\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. \" +\n\t\t\t\t\t\t\"Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst canvas = new OffscreenCanvas(0, 0);\n\t\t\tconst ctx = canvas.getContext(\"2d\");\n\t\t\tif (!ctx) throw new Error(\"CanvasMeasureAdapter: failed to get 2d context\");\n\t\t\tthis.ctx = ctx;\n\t\t}\n\t\treturn this.ctx;\n\t}\n\n\tmeasureSegment(text: string, font: string): { width: number } {\n\t\tconst ctx = this.getContext();\n\t\tif (font !== this.currentFont) {\n\t\t\tctx.font = font;\n\t\t\tthis.currentFont = font;\n\t\t}\n\t\tlet width = ctx.measureText(text).width;\n\t\t// Apply emoji correction if configured\n\t\tif (this.emojiCorrection !== 1 && /\\p{Emoji_Presentation}/u.test(text)) {\n\t\t\twidth *= this.emojiCorrection;\n\t\t}\n\t\treturn { width };\n\t}\n\n\tclearCache(): void {\n\t\t// No segment cache; context font is the only state.\n\t\tthis.currentFont = \"\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// NodeCanvasMeasureAdapter (Node.js / CLI with canvas package)\n// ---------------------------------------------------------------------------\n\n/**\n * Canvas API subset expected from `@napi-rs/canvas` or `skia-canvas`.\n * Passed via dependency injection — no dynamic import, no polling.\n */\nexport type CanvasModule = {\n\tcreateCanvas(\n\t\twidth: number,\n\t\theight: number,\n\t): {\n\t\tgetContext(type: \"2d\"): {\n\t\t\tfont: string;\n\t\t\tmeasureText(text: string): { width: number };\n\t\t};\n\t};\n};\n\n/**\n * Node.js measurement adapter using an injected canvas module.\n *\n * ```ts\n * import * as canvas from \"@napi-rs/canvas\";\n * const adapter = new NodeCanvasMeasureAdapter(canvas);\n * ```\n *\n * Works with `@napi-rs/canvas`, `skia-canvas`, or any module exposing\n * `createCanvas(w, h).getContext(\"2d\").measureText(text)`.\n */\nexport class NodeCanvasMeasureAdapter implements MeasurementAdapter {\n\tprivate ctx: { font: string; measureText(text: string): { width: number } } | null = null;\n\tprivate currentFont = \"\";\n\tprivate readonly canvasModule: CanvasModule;\n\n\tconstructor(canvasModule: CanvasModule) {\n\t\tthis.canvasModule = canvasModule;\n\t}\n\n\tprivate getContext(): { font: string; measureText(text: string): { width: number } } {\n\t\tif (!this.ctx) {\n\t\t\tconst canvas = this.canvasModule.createCanvas(0, 0);\n\t\t\tconst ctx = canvas.getContext(\"2d\");\n\t\t\tif (!ctx) throw new Error(\"NodeCanvasMeasureAdapter: failed to get 2d context\");\n\t\t\tthis.ctx = ctx;\n\t\t}\n\t\treturn this.ctx;\n\t}\n\n\tmeasureSegment(text: string, font: string): { width: number } {\n\t\tconst ctx = this.getContext();\n\t\tif (font !== this.currentFont) {\n\t\t\tctx.font = font;\n\t\t\tthis.currentFont = font;\n\t\t}\n\t\treturn { width: ctx.measureText(text).width };\n\t}\n\n\tclearCache(): void {\n\t\tthis.currentFont = \"\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// SvgBoundsAdapter\n// ---------------------------------------------------------------------------\n\n/**\n * SVG measurement adapter — extracts dimensions from `viewBox` attribute\n * or explicit `width`/`height` attributes in the SVG string.\n *\n * Pure arithmetic: parses the SVG string for dimension attributes.\n * No DOM required. Works in any JS environment.\n *\n * Browser users who need `getBBox()` should pre-measure and pass explicit\n * `viewBox` on the content block instead.\n */\nexport class SvgBoundsAdapter {\n\tmeasureSvg(content: string): { width: number; height: number } {\n\t\t// Try viewBox first: viewBox=\"minX minY width height\"\n\t\tconst viewBoxMatch = content.match(/viewBox\\s*=\\s*[\"']([^\"']+)[\"']/);\n\t\tif (viewBoxMatch) {\n\t\t\tconst parts = viewBoxMatch[1]!.trim().split(/[\\s,]+/);\n\t\t\tif (parts.length >= 4) {\n\t\t\t\tconst w = Number.parseFloat(parts[2]!);\n\t\t\t\tconst h = Number.parseFloat(parts[3]!);\n\t\t\t\tif (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {\n\t\t\t\t\treturn { width: w, height: h };\n\t\t\t\t}\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Fall back to explicit width/height attributes\n\t\tconst widthMatch = content.match(/<svg[^>]*\\bwidth\\s*=\\s*[\"']?([\\d.]+)/);\n\t\tconst heightMatch = content.match(/<svg[^>]*\\bheight\\s*=\\s*[\"']?([\\d.]+)/);\n\t\tif (widthMatch && heightMatch) {\n\t\t\tconst w = Number.parseFloat(widthMatch[1]!);\n\t\t\tconst h = Number.parseFloat(heightMatch[1]!);\n\t\t\tif (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {\n\t\t\t\treturn { width: w, height: h };\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t\"SvgBoundsAdapter: svg width/height attributes are non-finite or not positive\",\n\t\t\t);\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t\"SvgBoundsAdapter: cannot determine dimensions — SVG has no viewBox or width/height attributes\",\n\t\t);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// ImageSizeAdapter\n// ---------------------------------------------------------------------------\n\n/**\n * Image measurement adapter — returns pre-registered dimensions by src key.\n *\n * Sync-only: dimensions must be provided upfront via the `sizes` map.\n * No I/O, no polling, no async. For browser use, pre-measure via\n * `Image.onload` and pass natural dimensions on the content block directly,\n * or register them here.\n *\n * ```ts\n * const adapter = new ImageSizeAdapter({\n * \"hero.png\": { width: 1200, height: 630 },\n * \"logo.svg\": { width: 120, height: 40 },\n * });\n * ```\n */\nexport class ImageSizeAdapter {\n\tprivate readonly sizes: Map<string, { width: number; height: number }>;\n\n\tconstructor(sizes: Record<string, { width: number; height: number }>) {\n\t\tthis.sizes = new Map(Object.entries(sizes));\n\t}\n\n\tmeasureImage(src: string): { width: number; height: number } {\n\t\tconst dims = this.sizes.get(src);\n\t\tif (!dims) {\n\t\t\tthrow new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(src)}`);\n\t\t}\n\t\treturn { width: dims.width, height: dims.height };\n\t}\n}\n","/**\n * Reactive text layout engine (roadmap §7.1 — Pretext parity).\n *\n * Pure-arithmetic text measurement and line breaking without DOM thrashing.\n * Inspired by [Pretext](https://github.com/chenglou/pretext), rebuilt as a\n * GraphReFly graph — inspectable via `describe()`, snapshotable, debuggable.\n *\n * Two-tier DX:\n * - `reactiveLayout({ adapter, text?, font?, lineHeight?, maxWidth?, name? })` — convenience factory\n * - `MeasurementAdapter` — pluggable backends (`measureSegment`; optional `clearCache`)\n */\nimport { emitWithBatch } from \"../../core/batch.js\";\nimport { monotonicNs } from \"../../core/clock.js\";\nimport { DATA, INVALIDATE, TEARDOWN } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { derived, state } from \"../../core/sugar.js\";\nimport { Graph } from \"../../graph/graph.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Pluggable measurement backend. */\nexport interface MeasurementAdapter {\n\tmeasureSegment(text: string, font: string): { width: number };\n\t/** Optional; adapters may omit for read-only / stateless measurement. */\n\tclearCache?(): void;\n}\n\n/** Mutable counters for `analyzeAndMeasure` cache hit ratio (hits / (hits + misses)). */\nexport type SegmentMeasureStats = { hits: number; misses: number };\n\n/** Break kind for each segment (ported from Pretext analysis.ts). */\nexport type SegmentBreakKind = \"text\" | \"space\" | \"zero-width-break\" | \"soft-hyphen\" | \"hard-break\";\n\n/** A measured text segment ready for line breaking. */\nexport type PreparedSegment = {\n\ttext: string;\n\twidth: number;\n\tkind: SegmentBreakKind;\n\t/** Grapheme widths for overflow-wrap: break-word (null if single grapheme). */\n\tgraphemeWidths: number[] | null;\n};\n\n/** A laid-out line with start/end cursors. */\nexport type LayoutLine = {\n\ttext: string;\n\twidth: number;\n\tstartSegment: number;\n\tstartGrapheme: number;\n\tendSegment: number;\n\tendGrapheme: number;\n};\n\n/** Per-character position for hit testing. */\nexport type CharPosition = {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tline: number;\n};\n\n/** Full layout result from the line-breaks derived node. */\nexport type LineBreaksResult = {\n\tlines: LayoutLine[];\n\tlineCount: number;\n};\n\n/** Result of the reactive layout graph's describe-accessible state. */\nexport type ReactiveLayoutBundle = {\n\tgraph: Graph;\n\t/** Set input text. */\n\tsetText: (text: string) => void;\n\t/** Set CSS font string. */\n\tsetFont: (font: string) => void;\n\t/** Set line height (px). */\n\tsetLineHeight: (lineHeight: number) => void;\n\t/** Set max width constraint (px). */\n\tsetMaxWidth: (maxWidth: number) => void;\n\t/** Segments node. */\n\tsegments: Node<PreparedSegment[]>;\n\t/** Line breaks node. */\n\tlineBreaks: Node<LineBreaksResult>;\n\t/** Total height node. */\n\theight: Node<number>;\n\t/** Per-character positions node. */\n\tcharPositions: Node<CharPosition[]>;\n};\n\n// ---------------------------------------------------------------------------\n// Text analysis (ported from Pretext analysis.ts — core subset)\n// ---------------------------------------------------------------------------\n\n// CJK detection (Unicode CJK Unified Ideographs + common ranges)\nfunction isCJK(s: string): boolean {\n\tfor (const ch of s) {\n\t\tconst c = ch.codePointAt(0)!;\n\t\tif (\n\t\t\t(c >= 0x4e00 && c <= 0x9fff) || // CJK Unified Ideographs\n\t\t\t(c >= 0x3400 && c <= 0x4dbf) || // CJK Extension A\n\t\t\t(c >= 0x3000 && c <= 0x303f) || // CJK Symbols and Punctuation\n\t\t\t(c >= 0x3040 && c <= 0x309f) || // Hiragana\n\t\t\t(c >= 0x30a0 && c <= 0x30ff) || // Katakana\n\t\t\t(c >= 0xac00 && c <= 0xd7af) || // Hangul\n\t\t\t(c >= 0xff00 && c <= 0xffef) // Fullwidth Forms\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n// Kinsoku: characters that cannot start a line (CJK punctuation)\nconst kinsokuStart = new Set([\n\t\"\\uff0c\",\n\t\"\\uff0e\",\n\t\"\\uff01\",\n\t\"\\uff1a\",\n\t\"\\uff1b\",\n\t\"\\uff1f\",\n\t\"\\u3001\",\n\t\"\\u3002\",\n\t\"\\u30fb\",\n\t\"\\uff09\",\n\t\"\\u3015\",\n\t\"\\u3009\",\n\t\"\\u300b\",\n\t\"\\u300d\",\n\t\"\\u300f\",\n\t\"\\u3011\",\n]);\n\n// Left-sticky punctuation (merges into preceding segment)\nconst leftStickyPunctuation = new Set([\n\t\".\",\n\t\",\",\n\t\"!\",\n\t\"?\",\n\t\":\",\n\t\";\",\n\t\")\",\n\t\"]\",\n\t\"}\",\n\t\"%\",\n\t'\"',\n\t\"\\u201d\",\n\t\"\\u2019\",\n\t\"\\u00bb\",\n\t\"\\u203a\",\n\t\"\\u2026\",\n]);\n\n/** Normalize collapsible whitespace (CSS white-space: normal). */\nfunction normalizeWhitespace(text: string): string {\n\treturn text.replace(/[\\t\\n\\r\\f ]+/g, \" \").replace(/^ | $/g, \"\");\n}\n\n/**\n * Segment text using Intl.Segmenter (word granularity) and classify break kinds.\n * Returns raw segmentation pieces before merging.\n */\nfunction segmentText(normalized: string): {\n\ttexts: string[];\n\tisWordLike: boolean[];\n\tkinds: SegmentBreakKind[];\n}[] {\n\tconst wordSegmenter = new Intl.Segmenter(undefined, { granularity: \"word\" });\n\tconst pieces: {\n\t\ttexts: string[];\n\t\tisWordLike: boolean[];\n\t\tkinds: SegmentBreakKind[];\n\t}[] = [];\n\n\tfor (const s of wordSegmenter.segment(normalized)) {\n\t\tconst text = s.segment;\n\t\tconst isWordLike = s.isWordLike ?? false;\n\n\t\t// Split segment by break-relevant characters\n\t\tconst texts: string[] = [];\n\t\tconst wordLikes: boolean[] = [];\n\t\tconst kinds: SegmentBreakKind[] = [];\n\n\t\tlet currentText = \"\";\n\t\tlet currentKind: SegmentBreakKind | null = null;\n\n\t\tfor (const ch of text) {\n\t\t\tlet kind: SegmentBreakKind;\n\t\t\tif (ch === \" \") kind = \"space\";\n\t\t\telse if (ch === \"\\u200b\") kind = \"zero-width-break\";\n\t\t\telse if (ch === \"\\u00ad\") kind = \"soft-hyphen\";\n\t\t\telse if (ch === \"\\n\") kind = \"hard-break\";\n\t\t\telse kind = \"text\";\n\n\t\t\tif (currentKind !== null && kind === currentKind) {\n\t\t\t\tcurrentText += ch;\n\t\t\t} else {\n\t\t\t\tif (currentKind !== null) {\n\t\t\t\t\ttexts.push(currentText);\n\t\t\t\t\twordLikes.push(currentKind === \"text\" && isWordLike);\n\t\t\t\t\tkinds.push(currentKind);\n\t\t\t\t}\n\t\t\t\tcurrentText = ch;\n\t\t\t\tcurrentKind = kind;\n\t\t\t}\n\t\t}\n\n\t\tif (currentKind !== null) {\n\t\t\ttexts.push(currentText);\n\t\t\twordLikes.push(currentKind === \"text\" && isWordLike);\n\t\t\tkinds.push(currentKind);\n\t\t}\n\n\t\tpieces.push({ texts, isWordLike: wordLikes, kinds });\n\t}\n\treturn pieces;\n}\n\n/**\n * Merge segmentation pieces: sticky punctuation, CJK per-grapheme splitting,\n * and produce the final measured segment list.\n */\nexport function analyzeAndMeasure(\n\ttext: string,\n\tfont: string,\n\tadapter: MeasurementAdapter,\n\tcache: Map<string, Map<string, number>>,\n\tstats?: SegmentMeasureStats,\n): PreparedSegment[] {\n\tconst normalized = normalizeWhitespace(text);\n\tif (normalized.length === 0) return [];\n\n\tconst pieces = segmentText(normalized);\n\tconst graphemeSegmenter = new Intl.Segmenter(undefined, {\n\t\tgranularity: \"grapheme\",\n\t});\n\n\t// Flatten pieces into a single segment list with merging\n\tconst rawTexts: string[] = [];\n\tconst rawKinds: SegmentBreakKind[] = [];\n\tconst rawWordLike: boolean[] = [];\n\n\tfor (const piece of pieces) {\n\t\tfor (let i = 0; i < piece.texts.length; i++) {\n\t\t\trawTexts.push(piece.texts[i]!);\n\t\t\trawKinds.push(piece.kinds[i]!);\n\t\t\trawWordLike.push(piece.isWordLike[i]!);\n\t\t}\n\t}\n\n\t// Merge: left-sticky punctuation and kinsoku-start into preceding text segment\n\tconst mergedTexts: string[] = [];\n\tconst mergedKinds: SegmentBreakKind[] = [];\n\tconst mergedWordLike: boolean[] = [];\n\n\tfor (let i = 0; i < rawTexts.length; i++) {\n\t\tconst t = rawTexts[i]!;\n\t\tconst k = rawKinds[i]!;\n\t\tconst wl = rawWordLike[i]!;\n\n\t\t// Merge left-sticky punctuation into preceding text\n\t\tif (\n\t\t\tk === \"text\" &&\n\t\t\t!wl &&\n\t\t\tmergedTexts.length > 0 &&\n\t\t\tmergedKinds[mergedKinds.length - 1] === \"text\"\n\t\t) {\n\t\t\tconst isSticky = t.length === 1 && (leftStickyPunctuation.has(t) || kinsokuStart.has(t));\n\t\t\tif (isSticky) {\n\t\t\t\tmergedTexts[mergedTexts.length - 1] += t;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Merge hyphen after word into preceding text (\"well-known\" stays together)\n\t\tif (\n\t\t\tt === \"-\" &&\n\t\t\tmergedTexts.length > 0 &&\n\t\t\tmergedKinds[mergedKinds.length - 1] === \"text\" &&\n\t\t\tmergedWordLike[mergedWordLike.length - 1]\n\t\t) {\n\t\t\tmergedTexts[mergedTexts.length - 1] += t;\n\t\t\tcontinue;\n\t\t}\n\n\t\tmergedTexts.push(t);\n\t\tmergedKinds.push(k);\n\t\tmergedWordLike.push(wl);\n\t}\n\n\t// Get or create font-specific cache\n\tlet fontCache = cache.get(font);\n\tif (!fontCache) {\n\t\tfontCache = new Map<string, number>();\n\t\tcache.set(font, fontCache);\n\t}\n\n\tfunction measureCached(seg: string): number {\n\t\tlet w = fontCache!.get(seg);\n\t\tif (w === undefined) {\n\t\t\tif (stats) stats.misses += 1;\n\t\t\tw = adapter.measureSegment(seg, font).width;\n\t\t\tfontCache!.set(seg, w);\n\t\t} else if (stats) {\n\t\t\tstats.hits += 1;\n\t\t}\n\t\treturn w;\n\t}\n\n\t// Build final prepared segments, splitting CJK into per-grapheme\n\tconst segments: PreparedSegment[] = [];\n\n\tfor (let i = 0; i < mergedTexts.length; i++) {\n\t\tconst t = mergedTexts[i]!;\n\t\tconst k = mergedKinds[i]!;\n\n\t\tif (k !== \"text\") {\n\t\t\t// Non-text segments: space, hard-break, soft-hyphen, zero-width-break\n\t\t\tsegments.push({\n\t\t\t\ttext: t,\n\t\t\t\twidth: k === \"space\" ? measureCached(\" \") * t.length : 0,\n\t\t\t\tkind: k,\n\t\t\t\tgraphemeWidths: null,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// CJK text: split into per-grapheme segments for line breaking\n\t\tif (isCJK(t)) {\n\t\t\tlet unitText = \"\";\n\t\t\tfor (const gs of graphemeSegmenter.segment(t)) {\n\t\t\t\tconst grapheme = gs.segment;\n\n\t\t\t\t// Kinsoku: line-start-prohibited chars stick to preceding unit\n\t\t\t\tif (unitText.length > 0 && kinsokuStart.has(grapheme)) {\n\t\t\t\t\tunitText += grapheme;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (unitText.length > 0) {\n\t\t\t\t\tconst w = measureCached(unitText);\n\t\t\t\t\tsegments.push({\n\t\t\t\t\t\ttext: unitText,\n\t\t\t\t\t\twidth: w,\n\t\t\t\t\t\tkind: \"text\",\n\t\t\t\t\t\tgraphemeWidths: null,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tunitText = grapheme;\n\t\t\t}\n\t\t\tif (unitText.length > 0) {\n\t\t\t\tconst w = measureCached(unitText);\n\t\t\t\tsegments.push({\n\t\t\t\t\ttext: unitText,\n\t\t\t\t\twidth: w,\n\t\t\t\t\tkind: \"text\",\n\t\t\t\t\tgraphemeWidths: null,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Non-CJK text: measure whole segment, pre-compute grapheme widths for break-word\n\t\tconst w = measureCached(t);\n\t\tlet graphemeWidths: number[] | null = null;\n\n\t\tif (mergedWordLike[i] && t.length > 1) {\n\t\t\tconst gWidths: number[] = [];\n\t\t\tfor (const gs of graphemeSegmenter.segment(t)) {\n\t\t\t\tgWidths.push(measureCached(gs.segment));\n\t\t\t}\n\t\t\tif (gWidths.length > 1) {\n\t\t\t\tgraphemeWidths = gWidths;\n\t\t\t}\n\t\t}\n\n\t\tsegments.push({ text: t, width: w, kind: \"text\", graphemeWidths });\n\t}\n\n\treturn segments;\n}\n\n// ---------------------------------------------------------------------------\n// Line breaking (greedy, ported from Pretext line-break.ts — core subset)\n// ---------------------------------------------------------------------------\n\n/**\n * Greedy line-breaking algorithm.\n *\n * Walks segments left to right, accumulating width. Breaks when a segment would\n * overflow maxWidth. Supports:\n * - Trailing space hang (spaces don't trigger breaks)\n * - overflow-wrap: break-word via grapheme widths\n * - Soft hyphens (break opportunity, adds visible hyphen width)\n * - Hard breaks (forced newline)\n */\nexport function computeLineBreaks(\n\tsegments: PreparedSegment[],\n\tmaxWidth: number,\n\tadapter: MeasurementAdapter,\n\tfont: string,\n\tcache: Map<string, Map<string, number>>,\n): LineBreaksResult {\n\tif (segments.length === 0) {\n\t\treturn { lines: [], lineCount: 0 };\n\t}\n\n\tconst lines: LayoutLine[] = [];\n\tlet lineW = 0;\n\tlet hasContent = false;\n\tlet lineStartSeg = 0;\n\tlet lineStartGrapheme = 0;\n\tlet lineEndSeg = 0;\n\tlet lineEndGrapheme = 0;\n\tlet pendingBreakSeg = -1;\n\tlet pendingBreakWidth = 0;\n\n\t// Measure hyphen for soft-hyphen support\n\tlet fontCache = cache.get(font);\n\tif (!fontCache) {\n\t\tfontCache = new Map<string, number>();\n\t\tcache.set(font, fontCache);\n\t}\n\tlet hyphenWidth = fontCache.get(\"-\");\n\tif (hyphenWidth === undefined) {\n\t\thyphenWidth = adapter.measureSegment(\"-\", font).width;\n\t\tfontCache.set(\"-\", hyphenWidth);\n\t}\n\n\tfunction emitLine(endSeg = lineEndSeg, endGrapheme = lineEndGrapheme, width = lineW) {\n\t\t// Build line text\n\t\tlet text = \"\";\n\t\tfor (let i = lineStartSeg; i < endSeg; i++) {\n\t\t\tconst seg = segments[i]!;\n\t\t\tif (seg.kind === \"soft-hyphen\" || seg.kind === \"hard-break\") continue;\n\t\t\tif (i === lineStartSeg && lineStartGrapheme > 0 && seg.graphemeWidths) {\n\t\t\t\t// Partial segment from grapheme break\n\t\t\t\tconst graphemeSegmenter = new Intl.Segmenter(undefined, {\n\t\t\t\t\tgranularity: \"grapheme\",\n\t\t\t\t});\n\t\t\t\tconst graphemes = [...graphemeSegmenter.segment(seg.text)].map((g) => g.segment);\n\t\t\t\ttext += graphemes.slice(lineStartGrapheme).join(\"\");\n\t\t\t} else {\n\t\t\t\ttext += seg.text;\n\t\t\t}\n\t\t}\n\t\t// Handle partial end segment\n\t\tif (endGrapheme > 0 && endSeg < segments.length) {\n\t\t\tconst seg = segments[endSeg]!;\n\t\t\tconst graphemeSegmenter = new Intl.Segmenter(undefined, {\n\t\t\t\tgranularity: \"grapheme\",\n\t\t\t});\n\t\t\tconst graphemes = [...graphemeSegmenter.segment(seg.text)].map((g) => g.segment);\n\t\t\tconst startG = lineStartSeg === endSeg ? lineStartGrapheme : 0;\n\t\t\ttext += graphemes.slice(startG, endGrapheme).join(\"\");\n\t\t}\n\t\t// Add visible hyphen if line ends at soft-hyphen\n\t\tif (\n\t\t\tendSeg > 0 &&\n\t\t\tsegments[endSeg - 1]?.kind === \"soft-hyphen\" &&\n\t\t\t!(lineStartSeg === endSeg && lineStartGrapheme > 0)\n\t\t) {\n\t\t\ttext += \"-\";\n\t\t}\n\n\t\tlines.push({\n\t\t\ttext,\n\t\t\twidth,\n\t\t\tstartSegment: lineStartSeg,\n\t\t\tstartGrapheme: lineStartGrapheme,\n\t\t\tendSegment: endSeg,\n\t\t\tendGrapheme,\n\t\t});\n\t\tlineW = 0;\n\t\thasContent = false;\n\t\tpendingBreakSeg = -1;\n\t\tpendingBreakWidth = 0;\n\t}\n\n\tfunction canBreakAfter(kind: SegmentBreakKind): boolean {\n\t\treturn kind === \"space\" || kind === \"zero-width-break\" || kind === \"soft-hyphen\";\n\t}\n\n\tfunction startLine(segIdx: number, graphemeIdx: number, width: number) {\n\t\thasContent = true;\n\t\tlineStartSeg = segIdx;\n\t\tlineStartGrapheme = graphemeIdx;\n\t\tlineEndSeg = segIdx + 1;\n\t\tlineEndGrapheme = 0;\n\t\tlineW = width;\n\t}\n\n\tfunction startLineAtGrapheme(segIdx: number, graphemeIdx: number, width: number) {\n\t\thasContent = true;\n\t\tlineStartSeg = segIdx;\n\t\tlineStartGrapheme = graphemeIdx;\n\t\tlineEndSeg = segIdx;\n\t\tlineEndGrapheme = graphemeIdx + 1;\n\t\tlineW = width;\n\t}\n\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tconst seg = segments[i]!;\n\n\t\t// Hard break: emit current line, start fresh\n\t\tif (seg.kind === \"hard-break\") {\n\t\t\tif (hasContent) {\n\t\t\t\temitLine();\n\t\t\t} else {\n\t\t\t\t// Empty line\n\t\t\t\tlines.push({\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\twidth: 0,\n\t\t\t\t\tstartSegment: i,\n\t\t\t\t\tstartGrapheme: 0,\n\t\t\t\t\tendSegment: i,\n\t\t\t\t\tendGrapheme: 0,\n\t\t\t\t});\n\t\t\t}\n\t\t\tlineStartSeg = i + 1;\n\t\t\tlineStartGrapheme = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst w = seg.width;\n\n\t\tif (!hasContent) {\n\t\t\t// First content on a new line\n\t\t\tif (w > maxWidth && seg.graphemeWidths) {\n\t\t\t\t// Word wider than maxWidth: break at grapheme level\n\t\t\t\tappendBreakableSegment(i, 0, seg.graphemeWidths);\n\t\t\t} else {\n\t\t\t\tstartLine(i, 0, w);\n\t\t\t}\n\t\t\tif (canBreakAfter(seg.kind)) {\n\t\t\t\tpendingBreakSeg = i + 1;\n\t\t\t\tpendingBreakWidth = seg.kind === \"space\" ? lineW - w : lineW;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst newW = lineW + w;\n\n\t\tif (newW > maxWidth + 0.005) {\n\t\t\t// Overflow\n\t\t\tif (canBreakAfter(seg.kind)) {\n\t\t\t\t// Trailing space: hang past edge, then break\n\t\t\t\tlineW += w;\n\t\t\t\tlineEndSeg = i + 1;\n\t\t\t\tlineEndGrapheme = 0;\n\t\t\t\temitLine(i + 1, 0, seg.kind === \"space\" ? lineW - w : lineW);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (pendingBreakSeg >= 0) {\n\t\t\t\t// Break at last break opportunity\n\t\t\t\temitLine(pendingBreakSeg, 0, pendingBreakWidth);\n\t\t\t\t// Don't advance i — re-process current segment on new line\n\t\t\t\ti--;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (w > maxWidth && seg.graphemeWidths) {\n\t\t\t\t// Break-word: split at grapheme level\n\t\t\t\temitLine();\n\t\t\t\tappendBreakableSegment(i, 0, seg.graphemeWidths);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// No break opportunity: force break before this segment\n\t\t\temitLine();\n\t\t\ti--;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Fits on current line\n\t\tlineW = newW;\n\t\tlineEndSeg = i + 1;\n\t\tlineEndGrapheme = 0;\n\n\t\tif (canBreakAfter(seg.kind)) {\n\t\t\tpendingBreakSeg = i + 1;\n\t\t\tpendingBreakWidth = seg.kind === \"space\" ? lineW - w : lineW;\n\t\t}\n\t}\n\n\tif (hasContent) {\n\t\temitLine();\n\t}\n\n\treturn { lines, lineCount: lines.length };\n\n\tfunction appendBreakableSegment(segIdx: number, startG: number, gWidths: number[]) {\n\t\tfor (let g = startG; g < gWidths.length; g++) {\n\t\t\tconst gw = gWidths[g]!;\n\t\t\tif (!hasContent) {\n\t\t\t\tstartLineAtGrapheme(segIdx, g, gw);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (lineW + gw > maxWidth + 0.005) {\n\t\t\t\temitLine();\n\t\t\t\tstartLineAtGrapheme(segIdx, g, gw);\n\t\t\t} else {\n\t\t\t\tlineW += gw;\n\t\t\t\tlineEndSeg = segIdx;\n\t\t\t\tlineEndGrapheme = g + 1;\n\t\t\t}\n\t\t}\n\t\t// If we consumed the whole segment, advance end past it\n\t\tif (hasContent && lineEndSeg === segIdx && lineEndGrapheme === gWidths.length) {\n\t\t\tlineEndSeg = segIdx + 1;\n\t\t\tlineEndGrapheme = 0;\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Character positions\n// ---------------------------------------------------------------------------\n\n/** Compute per-character x,y positions from line breaks and segments. */\nexport function computeCharPositions(\n\tlineBreaks: LineBreaksResult,\n\tsegments: PreparedSegment[],\n\tlineHeight: number,\n): CharPosition[] {\n\tconst positions: CharPosition[] = [];\n\tconst graphemeSegmenter = new Intl.Segmenter(undefined, {\n\t\tgranularity: \"grapheme\",\n\t});\n\n\tfor (let lineIdx = 0; lineIdx < lineBreaks.lines.length; lineIdx++) {\n\t\tconst line = lineBreaks.lines[lineIdx]!;\n\t\tconst y = lineIdx * lineHeight;\n\t\tlet x = 0;\n\n\t\tfor (let si = line.startSegment; si < segments.length; si++) {\n\t\t\tconst seg = segments[si]!;\n\t\t\tif (seg.kind === \"soft-hyphen\" || seg.kind === \"hard-break\") {\n\t\t\t\t// Skip non-visual segments but stop if past the line\n\t\t\t\tif (si >= line.endSegment && line.endGrapheme === 0) break;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst graphemes = [...graphemeSegmenter.segment(seg.text)].map((g) => g.segment);\n\t\t\tif (graphemes.length === 0) continue;\n\t\t\tconst startG = si === line.startSegment ? line.startGrapheme : 0;\n\n\t\t\t// Determine how many graphemes of this segment belong to this line\n\t\t\tlet endG: number;\n\t\t\tif (si < line.endSegment) {\n\t\t\t\t// Full segment is on this line\n\t\t\t\tendG = graphemes.length;\n\t\t\t} else if (si === line.endSegment && line.endGrapheme > 0) {\n\t\t\t\t// Partial segment (grapheme-level break)\n\t\t\t\tendG = line.endGrapheme;\n\t\t\t} else {\n\t\t\t\t// Past the line's content\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfor (let g = startG; g < endG; g++) {\n\t\t\t\tconst gWidth = seg.graphemeWidths ? seg.graphemeWidths[g]! : seg.width / graphemes.length;\n\t\t\t\tpositions.push({ x, y, width: gWidth, height: lineHeight, line: lineIdx });\n\t\t\t\tx += gWidth;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn positions;\n}\n\n// ---------------------------------------------------------------------------\n// Reactive graph factory\n// ---------------------------------------------------------------------------\n\nexport type ReactiveLayoutOptions = {\n\t/** Measurement backend (required). */\n\tadapter: MeasurementAdapter;\n\t/** Graph name (default: \"reactive-layout\"). */\n\tname?: string;\n\t/** Initial text. */\n\ttext?: string;\n\t/** Initial CSS font string. */\n\tfont?: string;\n\t/** Initial line height in px. */\n\tlineHeight?: number;\n\t/** Initial max width in px (clamped to ≥ 0). */\n\tmaxWidth?: number;\n};\n\n/**\n * Create a reactive text layout graph.\n *\n * ```\n * Graph(\"reactive-layout\")\n * ├── state(\"text\")\n * ├── state(\"font\")\n * ├── state(\"line-height\")\n * ├── state(\"max-width\")\n * ├── derived(\"segments\") — text + font → PreparedSegment[]\n * ├── derived(\"line-breaks\") — segments + max-width → LineBreaksResult\n * ├── derived(\"height\") — line-breaks → number\n * └── derived(\"char-positions\") — line-breaks + segments → CharPosition[]\n * ```\n */\nexport function reactiveLayout(opts: ReactiveLayoutOptions): ReactiveLayoutBundle {\n\tconst { adapter, name = \"reactive-layout\" } = opts;\n\tconst g = new Graph(name);\n\n\t// Shared measurement cache: Map<font, Map<segment, width>>\n\tconst measureCache = new Map<string, Map<string, number>>();\n\n\t// --- State nodes ---\n\tconst textNode = state<string>(opts.text ?? \"\", { name: \"text\" });\n\tconst fontNode = state<string>(opts.font ?? \"16px sans-serif\", {\n\t\tname: \"font\",\n\t});\n\tconst lineHeightNode = state<number>(opts.lineHeight ?? 20, {\n\t\tname: \"line-height\",\n\t});\n\tconst maxWidthNode = state<number>(Math.max(0, opts.maxWidth ?? 800), {\n\t\tname: \"max-width\",\n\t});\n\n\t// --- Derived: segments (text + font → PreparedSegment[]) ---\n\tfunction graphemeWidthsEqual(a: number[] | null, b: number[] | null): boolean {\n\t\tif (a === null || b === null) return a === b;\n\t\tif (a.length !== b.length) return false;\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (a[i] !== b[i]!) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tconst segmentsNode = derived<PreparedSegment[]>(\n\t\t[textNode, fontNode],\n\t\t([textVal, fontVal]) => {\n\t\t\tconst t0 = monotonicNs();\n\t\t\tconst measureStats: SegmentMeasureStats = { hits: 0, misses: 0 };\n\t\t\tconst result = analyzeAndMeasure(\n\t\t\t\ttextVal as string,\n\t\t\t\tfontVal as string,\n\t\t\t\tadapter,\n\t\t\t\tmeasureCache,\n\t\t\t\tmeasureStats,\n\t\t\t);\n\t\t\tconst elapsed = monotonicNs() - t0;\n\n\t\t\tconst lookups = measureStats.hits + measureStats.misses;\n\t\t\tconst hitRate = lookups === 0 ? 1 : measureStats.hits / lookups;\n\n\t\t\t// After parent `segments` auto-emits DATA/RESOLVED, deliver metrics\n\t\t\t// via phase-3 deferral so observers see the parent value first.\n\t\t\t// Phase-3 drains after all phase-2 work (parent settlements) completes\n\t\t\t// (parity with Python `defer_down` → `emit_with_batch_phase3`).\n\t\t\tconst meta = segmentsNode.meta;\n\t\t\tif (meta) {\n\t\t\t\tconst hr = hitRate;\n\t\t\t\tconst len = result.length;\n\t\t\t\tconst el = elapsed;\n\t\t\t\temitWithBatch((msgs) => meta[\"cache-hit-rate\"]?.down(msgs), [[DATA, hr]], 3);\n\t\t\t\temitWithBatch((msgs) => meta[\"segment-count\"]?.down(msgs), [[DATA, len]], 3);\n\t\t\t\temitWithBatch((msgs) => meta[\"layout-time-ns\"]?.down(msgs), [[DATA, el]], 3);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\t\t{\n\t\t\tname: \"segments\",\n\t\t\tmeta: {\n\t\t\t\t\"cache-hit-rate\": 0,\n\t\t\t\t\"segment-count\": 0,\n\t\t\t\t\"layout-time-ns\": 0,\n\t\t\t},\n\t\t\tonMessage(msg) {\n\t\t\t\tif (msg[0] === INVALIDATE || msg[0] === TEARDOWN) {\n\t\t\t\t\t// Local side-effect: clear closure-held cache that the node\n\t\t\t\t\t// cannot reach via its normal lifecycle. Return false so the\n\t\t\t\t\t// message still propagates via default dispatch (TEARDOWN\n\t\t\t\t\t// forwarding to meta/downstream, INVALIDATE clearing _cached).\n\t\t\t\t\tmeasureCache.clear();\n\t\t\t\t\tadapter.clearCache?.();\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst sa = a as PreparedSegment[] | null;\n\t\t\t\tconst sb = b as PreparedSegment[] | null;\n\t\t\t\tif (sa == null || sb == null) return sa === sb;\n\t\t\t\tif (sa.length !== sb.length) return false;\n\t\t\t\tfor (let i = 0; i < sa.length; i++) {\n\t\t\t\t\tconst pa = sa[i]!;\n\t\t\t\t\tconst pb = sb[i]!;\n\t\t\t\t\tif (\n\t\t\t\t\t\tpa.text !== pb.text ||\n\t\t\t\t\t\tpa.width !== pb.width ||\n\t\t\t\t\t\tpa.kind !== pb.kind ||\n\t\t\t\t\t\t!graphemeWidthsEqual(pa.graphemeWidths ?? null, pb.graphemeWidths ?? null)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\t// --- Derived: line-breaks (segments + max-width + font → LineBreaksResult) ---\n\tconst lineBreaksNode = derived<LineBreaksResult>(\n\t\t[segmentsNode, maxWidthNode, fontNode],\n\t\t([segs, mw, font]) => {\n\t\t\treturn computeLineBreaks(\n\t\t\t\tsegs as PreparedSegment[],\n\t\t\t\tmw as number,\n\t\t\t\tadapter,\n\t\t\t\tfont as string,\n\t\t\t\tmeasureCache,\n\t\t\t);\n\t\t},\n\t\t{\n\t\t\tname: \"line-breaks\",\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst la = a as LineBreaksResult | null;\n\t\t\t\tconst lb = b as LineBreaksResult | null;\n\t\t\t\tif (la == null || lb == null) return la === lb;\n\t\t\t\tif (la.lineCount !== lb.lineCount) return false;\n\t\t\t\tfor (let i = 0; i < la.lines.length; i++) {\n\t\t\t\t\tconst lineA = la.lines[i]!;\n\t\t\t\t\tconst lineB = lb.lines[i]!;\n\t\t\t\t\tif (\n\t\t\t\t\t\tlineA.text !== lineB.text ||\n\t\t\t\t\t\tlineA.width !== lineB.width ||\n\t\t\t\t\t\tlineA.startSegment !== lineB.startSegment ||\n\t\t\t\t\t\tlineA.startGrapheme !== lineB.startGrapheme ||\n\t\t\t\t\t\tlineA.endSegment !== lineB.endSegment ||\n\t\t\t\t\t\tlineA.endGrapheme !== lineB.endGrapheme\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\t// --- Derived: height ---\n\tconst heightNode = derived<number>(\n\t\t[lineBreaksNode, lineHeightNode],\n\t\t([lb, lh]) => (lb as LineBreaksResult).lineCount * (lh as number),\n\t\t{ name: \"height\" },\n\t);\n\n\t// --- Derived: char-positions ---\n\tconst charPositionsNode = derived<CharPosition[]>(\n\t\t[lineBreaksNode, segmentsNode, lineHeightNode],\n\t\t([lb, segs, lh]) => {\n\t\t\treturn computeCharPositions(lb as LineBreaksResult, segs as PreparedSegment[], lh as number);\n\t\t},\n\t\t{\n\t\t\tname: \"char-positions\",\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst ca = a as CharPosition[] | null;\n\t\t\t\tconst cb = b as CharPosition[] | null;\n\t\t\t\tif (ca == null || cb == null) return ca === cb;\n\t\t\t\tif (ca.length !== cb.length) return false;\n\t\t\t\tfor (let i = 0; i < ca.length; i++) {\n\t\t\t\t\tif (ca[i]!.x !== cb[i]!.x || ca[i]!.y !== cb[i]!.y || ca[i]!.width !== cb[i]!.width)\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\t// --- Register in graph ---\n\tg.add(\"text\", textNode);\n\tg.add(\"font\", fontNode);\n\tg.add(\"line-height\", lineHeightNode);\n\tg.add(\"max-width\", maxWidthNode);\n\tg.add(\"segments\", segmentsNode);\n\tg.add(\"line-breaks\", lineBreaksNode);\n\tg.add(\"height\", heightNode);\n\tg.add(\"char-positions\", charPositionsNode);\n\n\t// --- Edges (for describe() visibility) ---\n\tg.connect(\"text\", \"segments\");\n\tg.connect(\"font\", \"segments\");\n\tg.connect(\"segments\", \"line-breaks\");\n\tg.connect(\"max-width\", \"line-breaks\");\n\tg.connect(\"font\", \"line-breaks\");\n\tg.connect(\"line-breaks\", \"height\");\n\tg.connect(\"line-height\", \"height\");\n\tg.connect(\"line-breaks\", \"char-positions\");\n\tg.connect(\"segments\", \"char-positions\");\n\tg.connect(\"line-height\", \"char-positions\");\n\n\treturn {\n\t\tgraph: g,\n\t\tsetText: (text: string) => g.set(\"text\", text),\n\t\tsetFont: (font: string) => g.set(\"font\", font),\n\t\tsetLineHeight: (lh: number) => g.set(\"line-height\", lh),\n\t\tsetMaxWidth: (mw: number) => g.set(\"max-width\", Math.max(0, mw)),\n\t\tsegments: segmentsNode,\n\t\tlineBreaks: lineBreaksNode,\n\t\theight: heightNode,\n\t\tcharPositions: charPositionsNode,\n\t};\n}\n","/**\n * Reactive multi-content block layout engine (roadmap §7.1 — mixed content).\n *\n * Extends the text-only `reactiveLayout` with support for image and SVG blocks.\n * Pure-arithmetic layout over measured child sizes — no DOM, no async.\n *\n * Graph shape:\n * ```\n * Graph(\"reactive-block-layout\")\n * ├── state(\"blocks\") — ContentBlock[] input\n * ├── state(\"max-width\") — container constraint\n * ├── state(\"gap\") — vertical gap between blocks (px)\n * ├── derived(\"measured-blocks\") — blocks → MeasuredBlock[] (per-type measurement)\n * ├── derived(\"block-flow\") — measured-blocks + max-width + gap → PositionedBlock[]\n * ├── derived(\"total-height\") — block-flow → total height\n * └── meta: { block-count, layout-time-ns }\n * ```\n */\nimport { emitWithBatch } from \"../../core/batch.js\";\nimport { monotonicNs } from \"../../core/clock.js\";\nimport { DATA, INVALIDATE, TEARDOWN } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { derived, state } from \"../../core/sugar.js\";\nimport { Graph } from \"../../graph/graph.js\";\nimport {\n\tanalyzeAndMeasure,\n\ttype CharPosition,\n\tcomputeCharPositions,\n\tcomputeLineBreaks,\n\ttype LineBreaksResult,\n\ttype MeasurementAdapter,\n\ttype PreparedSegment,\n} from \"./reactive-layout.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Pluggable measurement backend for SVG content. */\nexport interface SvgMeasurer {\n\tmeasureSvg(content: string): { width: number; height: number };\n}\n\n/** Pluggable measurement backend for image content. */\nexport interface ImageMeasurer {\n\tmeasureImage(src: string): { width: number; height: number };\n}\n\n/** Adapters map for `reactiveBlockLayout`. */\nexport type BlockAdapters = {\n\t/** Text measurement adapter (required — delegates to `reactiveLayout` internals). */\n\ttext: MeasurementAdapter;\n\t/** SVG measurement (optional — required only if SVG blocks are present). */\n\tsvg?: SvgMeasurer;\n\t/** Image measurement (optional — required only if image blocks without explicit dimensions are present). */\n\timage?: ImageMeasurer;\n};\n\n/** A content block — text, image, or SVG. */\nexport type ContentBlock =\n\t| {\n\t\t\ttype: \"text\";\n\t\t\ttext: string;\n\t\t\tfont?: string;\n\t\t\tlineHeight?: number;\n\t }\n\t| {\n\t\t\ttype: \"image\";\n\t\t\tsrc: string;\n\t\t\t/** Natural width in px. Required if no ImageMeasurer adapter is provided. */\n\t\t\tnaturalWidth?: number;\n\t\t\t/** Natural height in px. Required if no ImageMeasurer adapter is provided. */\n\t\t\tnaturalHeight?: number;\n\t }\n\t| {\n\t\t\ttype: \"svg\";\n\t\t\tcontent: string;\n\t\t\t/** Explicit viewBox dimensions. Required if no SvgMeasurer adapter is provided. */\n\t\t\tviewBox?: { width: number; height: number };\n\t };\n\n/**\n * A block after measurement — knows its natural dimensions.\n *\n * **Equality note:** The reactive `measured-blocks` node uses dimension-only equality\n * (`type`, `width`, `height`, `index`). Inner text layout data (`textSegments`,\n * `textLineBreaks`, `textCharPositions`) is NOT compared for change detection.\n * If you need text-level reactivity, use `reactiveLayout()` directly per text block.\n */\nexport type MeasuredBlock = {\n\tindex: number;\n\ttype: \"text\" | \"image\" | \"svg\";\n\twidth: number;\n\theight: number;\n\t/** For text blocks: the inner layout results. */\n\ttextSegments?: PreparedSegment[];\n\ttextLineBreaks?: LineBreaksResult;\n\ttextCharPositions?: CharPosition[];\n};\n\n/** A block after flow — positioned in the container. */\nexport type PositionedBlock = MeasuredBlock & {\n\tx: number;\n\ty: number;\n};\n\n/** Options for `reactiveBlockLayout`. */\nexport type ReactiveBlockLayoutOptions = {\n\tadapters: BlockAdapters;\n\tname?: string;\n\tblocks?: ContentBlock[];\n\t/** Container max width in px (clamped to ≥ 0 on init and `setMaxWidth`). */\n\tmaxWidth?: number;\n\t/** Vertical gap between blocks in px (default 0). */\n\tgap?: number;\n\t/** Default font for text blocks that don't specify one. */\n\tdefaultFont?: string;\n\t/** Default line height for text blocks that don't specify one. */\n\tdefaultLineHeight?: number;\n};\n\n/** Result bundle from `reactiveBlockLayout`. */\nexport type ReactiveBlockLayoutBundle = {\n\tgraph: Graph;\n\tsetBlocks: (blocks: ContentBlock[]) => void;\n\tsetMaxWidth: (maxWidth: number) => void;\n\tsetGap: (gap: number) => void;\n\tmeasuredBlocks: Node<MeasuredBlock[]>;\n\tblockFlow: Node<PositionedBlock[]>;\n\ttotalHeight: Node<number>;\n};\n\n// ---------------------------------------------------------------------------\n// Block measurement (pure functions)\n// ---------------------------------------------------------------------------\n\n/**\n * Measure a single content block, returning natural (unconstrained) dimensions.\n * Text blocks use the text layout pipeline; image/SVG use adapters or explicit dims.\n */\nexport function measureBlock(\n\tblock: ContentBlock,\n\tmaxWidth: number,\n\tadapters: BlockAdapters,\n\tmeasureCache: Map<string, Map<string, number>>,\n\tdefaultFont: string,\n\tdefaultLineHeight: number,\n\tindex: number,\n): MeasuredBlock {\n\tswitch (block.type) {\n\t\tcase \"text\": {\n\t\t\tconst font = block.font ?? defaultFont;\n\t\t\tconst lineHeight = block.lineHeight ?? defaultLineHeight;\n\t\t\tconst segments = analyzeAndMeasure(block.text, font, adapters.text, measureCache);\n\t\t\tconst lineBreaks = computeLineBreaks(segments, maxWidth, adapters.text, font, measureCache);\n\t\t\tconst charPositions = computeCharPositions(lineBreaks, segments, lineHeight);\n\t\t\tconst height = lineBreaks.lineCount * lineHeight;\n\t\t\t// Width is the max line width (clamped to maxWidth)\n\t\t\tlet width = 0;\n\t\t\tfor (const line of lineBreaks.lines) {\n\t\t\t\tif (line.width > width) width = line.width;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\ttype: \"text\",\n\t\t\t\twidth: Math.min(width, maxWidth),\n\t\t\t\theight,\n\t\t\t\ttextSegments: segments,\n\t\t\t\ttextLineBreaks: lineBreaks,\n\t\t\t\ttextCharPositions: charPositions,\n\t\t\t};\n\t\t}\n\t\tcase \"image\": {\n\t\t\tlet w: number;\n\t\t\tlet h: number;\n\t\t\tif (block.naturalWidth != null && block.naturalHeight != null) {\n\t\t\t\tw = block.naturalWidth;\n\t\t\t\th = block.naturalHeight;\n\t\t\t} else if (adapters.image) {\n\t\t\t\tconst dims = adapters.image.measureImage(block.src);\n\t\t\t\tw = dims.width;\n\t\t\t\th = dims.height;\n\t\t\t} else {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Image block at index ${index} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Scale proportionally to fit maxWidth\n\t\t\tif (w > maxWidth) {\n\t\t\t\th = (h * maxWidth) / w;\n\t\t\t\tw = maxWidth;\n\t\t\t}\n\t\t\treturn { index, type: \"image\", width: w, height: h };\n\t\t}\n\t\tcase \"svg\": {\n\t\t\tlet w: number;\n\t\t\tlet h: number;\n\t\t\tif (block.viewBox) {\n\t\t\t\tw = block.viewBox.width;\n\t\t\t\th = block.viewBox.height;\n\t\t\t} else if (adapters.svg) {\n\t\t\t\tconst dims = adapters.svg.measureSvg(block.content);\n\t\t\t\tw = dims.width;\n\t\t\t\th = dims.height;\n\t\t\t} else {\n\t\t\t\tthrow new Error(`SVG block at index ${index} has no viewBox and no SvgMeasurer adapter`);\n\t\t\t}\n\t\t\t// Scale proportionally to fit maxWidth\n\t\t\tif (w > maxWidth) {\n\t\t\t\th = (h * maxWidth) / w;\n\t\t\t\tw = maxWidth;\n\t\t\t}\n\t\t\treturn { index, type: \"svg\", width: w, height: h };\n\t\t}\n\t}\n}\n\n/**\n * Measure all blocks in a content array.\n */\nexport function measureBlocks(\n\tblocks: ContentBlock[],\n\tmaxWidth: number,\n\tadapters: BlockAdapters,\n\tmeasureCache: Map<string, Map<string, number>>,\n\tdefaultFont: string,\n\tdefaultLineHeight: number,\n): MeasuredBlock[] {\n\treturn blocks.map((block, i) =>\n\t\tmeasureBlock(block, maxWidth, adapters, measureCache, defaultFont, defaultLineHeight, i),\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Block flow (pure function)\n// ---------------------------------------------------------------------------\n\n/**\n * Vertical stacking flow: blocks are placed top-to-bottom, left-aligned,\n * separated by `gap` pixels. Pure arithmetic over measured sizes.\n */\nexport function computeBlockFlow(measured: MeasuredBlock[], gap: number): PositionedBlock[] {\n\tconst result: PositionedBlock[] = [];\n\tlet y = 0;\n\tfor (let i = 0; i < measured.length; i++) {\n\t\tconst m = measured[i]!;\n\t\tresult.push({ ...m, x: 0, y });\n\t\ty += m.height + (i < measured.length - 1 ? gap : 0);\n\t}\n\treturn result;\n}\n\n/**\n * Compute total height from positioned blocks.\n */\nexport function computeTotalHeight(flow: PositionedBlock[]): number {\n\tif (flow.length === 0) return 0;\n\tconst last = flow[flow.length - 1]!;\n\treturn last.y + last.height;\n}\n\n// ---------------------------------------------------------------------------\n// Reactive graph factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a reactive block layout graph for mixed content (text + image + SVG).\n *\n * ```\n * Graph(\"reactive-block-layout\")\n * ├── state(\"blocks\") — ContentBlock[] input\n * ├── state(\"max-width\") — container constraint\n * ├── state(\"gap\") — vertical gap (px)\n * ├── derived(\"measured-blocks\") — blocks + max-width → MeasuredBlock[]\n * ├── derived(\"block-flow\") — measured-blocks + gap → PositionedBlock[]\n * ├── derived(\"total-height\") — block-flow → number\n * └── meta: { block-count, layout-time-ns }\n * ```\n */\nexport function reactiveBlockLayout(opts: ReactiveBlockLayoutOptions): ReactiveBlockLayoutBundle {\n\tconst {\n\t\tadapters,\n\t\tname = \"reactive-block-layout\",\n\t\tdefaultFont = \"16px sans-serif\",\n\t\tdefaultLineHeight = 20,\n\t} = opts;\n\tconst g = new Graph(name);\n\n\t// Shared text measurement cache (same structure as reactiveLayout)\n\tconst measureCache = new Map<string, Map<string, number>>();\n\n\t// --- State nodes ---\n\tconst blocksNode = state<ContentBlock[]>(opts.blocks ?? [], { name: \"blocks\" });\n\tconst maxWidthNode = state<number>(Math.max(0, opts.maxWidth ?? 800), { name: \"max-width\" });\n\tconst gapNode = state<number>(opts.gap ?? 0, { name: \"gap\" });\n\n\t// --- Derived: measured-blocks ---\n\tconst measuredBlocksNode = derived<MeasuredBlock[]>(\n\t\t[blocksNode, maxWidthNode],\n\t\t([blocksVal, mwVal]) => {\n\t\t\tconst t0 = monotonicNs();\n\t\t\tconst result = measureBlocks(\n\t\t\t\tblocksVal as ContentBlock[],\n\t\t\t\tmwVal as number,\n\t\t\t\tadapters,\n\t\t\t\tmeasureCache,\n\t\t\t\tdefaultFont,\n\t\t\t\tdefaultLineHeight,\n\t\t\t);\n\t\t\tconst elapsed = monotonicNs() - t0;\n\n\t\t\t// Phase-3 meta deferral (parity with reactiveLayout)\n\t\t\tconst meta = measuredBlocksNode.meta;\n\t\t\tif (meta) {\n\t\t\t\temitWithBatch((msgs) => meta[\"block-count\"]?.down(msgs), [[DATA, result.length]], 3);\n\t\t\t\temitWithBatch((msgs) => meta[\"layout-time-ns\"]?.down(msgs), [[DATA, elapsed]], 3);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\t\t{\n\t\t\tname: \"measured-blocks\",\n\t\t\tmeta: { \"block-count\": 0, \"layout-time-ns\": 0 },\n\t\t\tonMessage(msg, _depIndex, _actions) {\n\t\t\t\tif (msg[0] === INVALIDATE || msg[0] === TEARDOWN) {\n\t\t\t\t\t// Local side-effect only; return false so default dispatch\n\t\t\t\t\t// still propagates the message (TEARDOWN → meta/downstream).\n\t\t\t\t\tmeasureCache.clear();\n\t\t\t\t\tadapters.text.clearCache?.();\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t},\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst ma = a as MeasuredBlock[] | null;\n\t\t\t\tconst mb = b as MeasuredBlock[] | null;\n\t\t\t\tif (ma == null || mb == null) return ma === mb;\n\t\t\t\tif (ma.length !== mb.length) return false;\n\t\t\t\tfor (let i = 0; i < ma.length; i++) {\n\t\t\t\t\tconst ba = ma[i]!;\n\t\t\t\t\tconst bb = mb[i]!;\n\t\t\t\t\tif (\n\t\t\t\t\t\tba.type !== bb.type ||\n\t\t\t\t\t\tba.width !== bb.width ||\n\t\t\t\t\t\tba.height !== bb.height ||\n\t\t\t\t\t\tba.index !== bb.index\n\t\t\t\t\t)\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\t// --- Derived: block-flow ---\n\tconst blockFlowNode = derived<PositionedBlock[]>(\n\t\t[measuredBlocksNode, gapNode],\n\t\t([measured, gapVal]) => {\n\t\t\treturn computeBlockFlow(measured as MeasuredBlock[], gapVal as number);\n\t\t},\n\t\t{\n\t\t\tname: \"block-flow\",\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst fa = a as PositionedBlock[] | null;\n\t\t\t\tconst fb = b as PositionedBlock[] | null;\n\t\t\t\tif (fa == null || fb == null) return fa === fb;\n\t\t\t\tif (fa.length !== fb.length) return false;\n\t\t\t\tfor (let i = 0; i < fa.length; i++) {\n\t\t\t\t\tconst pa = fa[i]!;\n\t\t\t\t\tconst pb = fb[i]!;\n\t\t\t\t\tif (pa.x !== pb.x || pa.y !== pb.y || pa.width !== pb.width || pa.height !== pb.height)\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\t// --- Derived: total-height ---\n\tconst totalHeightNode = derived<number>(\n\t\t[blockFlowNode],\n\t\t([flow]) => computeTotalHeight(flow as PositionedBlock[]),\n\t\t{ name: \"total-height\" },\n\t);\n\n\t// --- Register in graph ---\n\tg.add(\"blocks\", blocksNode);\n\tg.add(\"max-width\", maxWidthNode);\n\tg.add(\"gap\", gapNode);\n\tg.add(\"measured-blocks\", measuredBlocksNode);\n\tg.add(\"block-flow\", blockFlowNode);\n\tg.add(\"total-height\", totalHeightNode);\n\n\t// --- Edges (for describe() visibility) ---\n\tg.connect(\"blocks\", \"measured-blocks\");\n\tg.connect(\"max-width\", \"measured-blocks\");\n\tg.connect(\"measured-blocks\", \"block-flow\");\n\tg.connect(\"gap\", \"block-flow\");\n\tg.connect(\"block-flow\", \"total-height\");\n\n\treturn {\n\t\tgraph: g,\n\t\tsetBlocks: (blocks: ContentBlock[]) => g.set(\"blocks\", blocks),\n\t\tsetMaxWidth: (mw: number) => g.set(\"max-width\", Math.max(0, mw)),\n\t\tsetGap: (gap: number) => g.set(\"gap\", gap),\n\t\tmeasuredBlocks: measuredBlocksNode,\n\t\tblockFlow: blockFlowNode,\n\t\ttotalHeight: totalHeightNode,\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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cAAc;AAEtC,SAAO;AAAA,IACN,OAAO;AAAA,IACP,WAAW,CAAC,WAA2B,EAAE,IAAI,UAAU,MAAM;AAAA,IAC7D,aAAa,CAAC,OAAe,EAAE,IAAI,aAAa,KAAK,IAAI,GAAG,EAAE,CAAC;AAAA,IAC/D,QAAQ,CAAC,QAAgB,EAAE,IAAI,OAAO,GAAG;AAAA,IACzC,gBAAgB;AAAA,IAChB,WAAW;AAAA,IACX,aAAa;AAAA,EACd;AACD;;;A7DrZO,IAAM,UAAU;","names":["map","action","action","action","atom","node","map","pull","atom","node","debounce","resolvePath","filter","import_common","import_core","node","node","filter","actor","wantsStructured","derived","stop","result","stream","text","edgeKey","depNeighbors","edgeNeighbors","buffer","first","node","pull","useStore","useSubscribe","useSubscribeRecord","useSubscribe","node","useStore","useSubscribeRecord","useStore","useSubscribe","useSubscribeRecord","useSubscribe","node","useStore","useSubscribeRecord","useStore","useSubscribe","useSubscribeRecord","useSubscribe","node","useStore","useSubscribeRecord","map","delay","last","operatorOpts","clampNonNegative","sourceOpts","sseFrame","topic","buffer","import_node_crypto","import_node_fs","import_node_path","sortJsonValue","node","version","operatorOpts","map","buffer","emptySnapshot","first","map","keepalive","node","emptySnapshot","keepaliveDerived","emptySnapshot","isTransport","node","policy","out","keepalive","isNodeLike","filter","interval","node","keepalive","forEach","gate","join","gate","forEach","join","w","last"]}
|