@graphrefly/graphrefly 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-R6OHUUYB.js → chunk-AHRKWMNI.js} +7 -7
- package/dist/chunk-AHRKWMNI.js.map +1 -0
- package/dist/{chunk-2PORF4RP.js → chunk-BER7UYLM.js} +27 -32
- package/dist/chunk-BER7UYLM.js.map +1 -0
- package/dist/{chunk-646OG3PO.js → chunk-IRZAGZUB.js} +51 -52
- package/dist/chunk-IRZAGZUB.js.map +1 -0
- package/dist/{chunk-IHJHBADD.js → chunk-JC2SN46B.js} +385 -197
- package/dist/chunk-JC2SN46B.js.map +1 -0
- package/dist/{chunk-XJ6EMQ22.js → chunk-OO5QOAXI.js} +4 -10
- package/dist/chunk-OO5QOAXI.js.map +1 -0
- package/dist/{chunk-YXROQFXZ.js → chunk-UW77D7SP.js} +3 -3
- package/dist/{chunk-F2ULI3Q3.js → chunk-XUOY3YKN.js} +7 -3
- package/dist/chunk-XUOY3YKN.js.map +1 -0
- package/dist/chunk-YLR5JUJZ.js +111 -0
- package/dist/chunk-YLR5JUJZ.js.map +1 -0
- package/dist/{chunk-BV3TPSBK.js → chunk-YXR3WW3Q.js} +740 -755
- package/dist/chunk-YXR3WW3Q.js.map +1 -0
- package/dist/compat/nestjs/index.cjs +1127 -983
- package/dist/compat/nestjs/index.cjs.map +1 -1
- package/dist/compat/nestjs/index.d.cts +4 -4
- package/dist/compat/nestjs/index.d.ts +4 -4
- package/dist/compat/nestjs/index.js +7 -13
- package/dist/core/index.cjs +653 -749
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +7 -7
- package/dist/extra/index.cjs +773 -795
- package/dist/extra/index.cjs.map +1 -1
- package/dist/extra/index.d.cts +4 -4
- package/dist/extra/index.d.ts +4 -4
- package/dist/extra/index.js +5 -11
- package/dist/graph/index.cjs +1036 -975
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +3 -3
- package/dist/graph/index.d.ts +3 -3
- package/dist/graph/index.js +8 -8
- package/dist/{graph-fCsaaVIa.d.cts → graph-KsTe57nI.d.cts} +127 -51
- package/dist/{graph-Dc-P9BVm.d.ts → graph-mILUUqW8.d.ts} +127 -51
- package/dist/{index-DhXznWyH.d.ts → index-8a605sg9.d.ts} +2 -2
- package/dist/{index-D7y9Q8W4.d.ts → index-B2SvPEbc.d.ts} +8 -69
- package/dist/{index-YlOH1Gw6.d.cts → index-BBUYZfJ1.d.cts} +122 -78
- package/dist/{index-ClaKZFPl.d.cts → index-Bjh5C1Tp.d.cts} +38 -35
- package/dist/{index-DWq0P9T6.d.ts → index-BjtlNirP.d.cts} +5 -7
- package/dist/{index-N704txAA.d.ts → index-BnkMgNNa.d.ts} +38 -35
- package/dist/{index-BBVBYPxr.d.cts → index-CgSiUouz.d.ts} +5 -7
- package/dist/{index-BmoUvOGN.d.ts → index-CvKzv0AW.d.ts} +122 -78
- package/dist/{index-4OIX-q0C.d.cts → index-UudxGnzc.d.cts} +8 -69
- package/dist/{index-DlGMf_Qe.d.cts → index-VHA43cGP.d.cts} +2 -2
- package/dist/index.cjs +6146 -5725
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +617 -383
- package/dist/index.d.ts +617 -383
- package/dist/index.js +4401 -4028
- package/dist/index.js.map +1 -1
- package/dist/{meta-BV4pj9ML.d.cts → meta-BnG7XAaE.d.cts} +395 -289
- package/dist/{meta-BV4pj9ML.d.ts → meta-BnG7XAaE.d.ts} +395 -289
- package/dist/observable-C8Kx_O6k.d.cts +36 -0
- package/dist/observable-DcBwQY7t.d.ts +36 -0
- package/dist/patterns/reactive-layout/index.cjs +1037 -857
- package/dist/patterns/reactive-layout/index.cjs.map +1 -1
- package/dist/patterns/reactive-layout/index.d.cts +3 -3
- package/dist/patterns/reactive-layout/index.d.ts +3 -3
- package/dist/patterns/reactive-layout/index.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-2PORF4RP.js.map +0 -1
- package/dist/chunk-646OG3PO.js.map +0 -1
- package/dist/chunk-BV3TPSBK.js.map +0 -1
- package/dist/chunk-EBNKJULL.js +0 -231
- package/dist/chunk-EBNKJULL.js.map +0 -1
- package/dist/chunk-F2ULI3Q3.js.map +0 -1
- package/dist/chunk-IHJHBADD.js.map +0 -1
- package/dist/chunk-R6OHUUYB.js.map +0 -1
- package/dist/chunk-XJ6EMQ22.js.map +0 -1
- package/dist/observable-Cz-AWhwR.d.cts +0 -42
- package/dist/observable-DCqlwGyl.d.ts +0 -42
- /package/dist/{chunk-YXROQFXZ.js.map → chunk-UW77D7SP.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/compat/nestjs/index.ts","../../../src/extra/observable.ts","../../../src/core/messages.ts","../../../src/compat/nestjs/decorators.ts","../../../src/compat/nestjs/tokens.ts","../../../src/extra/sources.ts","../../../src/core/clock.ts","../../../src/core/actor.ts","../../../src/core/batch.ts","../../../src/core/guard.ts","../../../src/core/versioning.ts","../../../src/core/node.ts","../../../src/core/sugar.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/dynamic-node.ts","../../../src/core/meta.ts","../../../src/graph/graph.ts","../../../src/extra/reactive-log.ts","../../../src/patterns/cqrs.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\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 * GraphReFly message protocol — §1 `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n * Emissions are always `[[Type, Data?], ...]` (no single-tuple shorthand).\n *\n * ## Canonical message ordering (within a composite batch)\n *\n * When multiple message types appear in a single `down()` call, the canonical\n * delivery order is determined by **signal tier**:\n *\n * | Tier | Signals | Role | Batch behavior |\n * |------|------------------------|-------------------|-------------------------------------|\n * | 0 | DIRTY, INVALIDATE | Notification | Immediate (never deferred) |\n * | 1 | PAUSE, RESUME | Flow control | Immediate (never deferred) |\n * | 2 | DATA, RESOLVED | Value settlement | Deferred inside `batch()` |\n * | 3 | COMPLETE, ERROR | Terminal lifecycle | Deferred to after phase-2 |\n * | 4 | TEARDOWN | Destruction | Immediate (usually sent alone) |\n *\n * **Rule:** Within `downWithBatch`, messages are partitioned by tier and delivered\n * in tier order. This ensures phase-2 values (DATA/RESOLVED) reach sinks before\n * terminal signals (COMPLETE/ERROR) mark the node as done, preventing the\n * \"COMPLETE-before-DATA\" class of bugs. Sources that emit in canonical order\n * naturally partition correctly with zero overhead.\n *\n * Unknown message types (forward-compat) are tier 0 (immediate).\n *\n * ## Meta node bypass rules (centralized — GRAPHREFLY-SPEC §2.3)\n *\n * - **INVALIDATE** via `graph.signal()` — no-op on meta nodes (cached values preserved).\n * - **COMPLETE / ERROR** — not propagated from parent to meta (meta outlives terminal\n * state for post-mortem writes like setting `meta.error` after ERROR).\n * - **TEARDOWN** — propagated from parent to meta, releasing meta resources.\n */\n\n/** Value delivery (`DATA`, value). Tier 2 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 0 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 2 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 0 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 1 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 1 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 4 — immediate (usually sent alone). */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 3 — delivered after phase-2 in the same batch. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 3 — delivered after phase-2 in the same batch. */\nexport const ERROR = Symbol.for(\"graphrefly/ERROR\");\n\n/** Known protocol type symbols (open set — other symbols are valid and forward). */\nexport const knownMessageTypes: readonly symbol[] = [\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tINVALIDATE,\n\tPAUSE,\n\tRESUME,\n\tTEARDOWN,\n\tCOMPLETE,\n\tERROR,\n];\n\n/** One protocol tuple: `[Type, optional payload]`. */\nexport type Message = readonly [symbol, unknown?];\n\n/**\n * A batch of tuples — the wire shape for `node.down()` / `node.up()`.\n */\nexport type Messages = readonly Message[];\n\n/**\n * Whether `t` is one of the built-in protocol symbols in this module.\n *\n * @param t — Message type symbol (unknown types are still valid; they must forward).\n * @returns `true` for `DATA`, `DIRTY`, `RESOLVED`, etc.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, isKnownMessageType } from \"@graphrefly/graphrefly-ts\";\n *\n * isKnownMessageType(DATA); // true\n * isKnownMessageType(Symbol(\"custom\")); // false\n * ```\n */\nexport function isKnownMessageType(t: symbol): boolean {\n\treturn knownMessageTypes.includes(t);\n}\n\n/**\n * Returns the signal tier for a message type (see module-level ordering table).\n *\n * - 0: notification (DIRTY, INVALIDATE) — immediate\n * - 1: flow control (PAUSE, RESUME) — immediate\n * - 2: value (DATA, RESOLVED) — deferred inside `batch()`\n * - 3: terminal (COMPLETE, ERROR) — delivered after phase-2\n * - 4: destruction (TEARDOWN) — immediate, usually alone\n * - 0 for unknown types (forward-compat: immediate)\n *\n * @param t — Message type symbol.\n * @returns Tier number (0–4).\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, TEARDOWN, messageTier } from \"@graphrefly/graphrefly-ts\";\n *\n * messageTier(DIRTY); // 0\n * messageTier(DATA); // 2\n * messageTier(COMPLETE); // 3\n * messageTier(TEARDOWN); // 4\n * ```\n */\nexport function messageTier(t: symbol): number {\n\tif (t === DIRTY || t === INVALIDATE) return 0;\n\tif (t === PAUSE || t === RESUME) return 1;\n\tif (t === DATA || t === RESOLVED) return 2;\n\tif (t === COMPLETE || t === ERROR) return 3;\n\tif (t === TEARDOWN) return 4;\n\treturn 0; // unknown → immediate\n}\n\n/**\n * Returns whether this tuple is deferred by `batch()` (phase 2: `DATA` or `RESOLVED`).\n *\n * @param msg — Single message tuple.\n * @returns `true` if `msg` is `DATA` or `RESOLVED`.\n *\n * @example\n * ```ts\n * import { DATA, RESOLVED, DIRTY, isPhase2Message } from \"@graphrefly/graphrefly-ts\";\n *\n * isPhase2Message([DATA, 42]); // true\n * isPhase2Message([RESOLVED]); // true\n * isPhase2Message([DIRTY]); // false\n * ```\n */\nexport function isPhase2Message(msg: Message): boolean {\n\tconst t = msg[0];\n\treturn t === DATA || t === RESOLVED;\n}\n\n/**\n * Returns whether this message type is terminal (COMPLETE or ERROR).\n * Terminal messages are delivered after phase-2 in the same batch to prevent\n * the node from becoming terminal before value messages reach sinks.\n *\n * @param t — Message type symbol.\n * @returns `true` for `COMPLETE` or `ERROR`.\n *\n * @example\n * ```ts\n * import { COMPLETE, ERROR, DATA, isTerminalMessage } from \"@graphrefly/graphrefly-ts\";\n *\n * isTerminalMessage(COMPLETE); // true\n * isTerminalMessage(ERROR); // true\n * isTerminalMessage(DATA); // false\n * ```\n */\nexport function isTerminalMessage(t: symbol): boolean {\n\treturn t === COMPLETE || t === ERROR;\n}\n\n/**\n * Whether `t` should be propagated from a parent node to its companion meta nodes.\n * Only TEARDOWN propagates; COMPLETE/ERROR/INVALIDATE do not (meta outlives parent\n * terminal state for post-mortem writes).\n *\n * @param t — Message type symbol.\n * @returns `true` if the signal should reach meta nodes.\n *\n * @example\n * ```ts\n * import { TEARDOWN, COMPLETE, ERROR, propagatesToMeta } from \"@graphrefly/graphrefly-ts\";\n *\n * propagatesToMeta(TEARDOWN); // true\n * propagatesToMeta(COMPLETE); // false\n * propagatesToMeta(ERROR); // false\n * ```\n */\nexport function propagatesToMeta(t: symbol): boolean {\n\treturn t === TEARDOWN;\n}\n","// ---------------------------------------------------------------------------\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 * Centralised timestamp utilities.\n *\n * Convention: all graphrefly-ts timestamps use nanoseconds (`_ns` suffix).\n *\n * - {@link monotonicNs} — monotonic clock (ordering, durations, timeline events).\n * - {@link wallClockNs} — wall-clock (mutation attribution, cron emission).\n *\n * **Precision limits (JS platform):**\n *\n * - `monotonicNs`: effective ~microsecond precision. `performance.now()` returns\n * milliseconds with ~5µs resolution; the last 3 digits of the nanosecond value\n * are always zero. Python's `time.monotonic_ns()` gives true nanoseconds.\n *\n * - `wallClockNs`: ~256ns precision loss at current epoch. `Date.now() * 1e6`\n * produces values around 1.8×10¹⁸ which exceed IEEE 754's 2⁵³ safe integer\n * limit. Python's `time.time_ns()` (arbitrary-precision `int`) has no loss.\n * In practice this is irrelevant — JS is single-threaded, so sub-microsecond\n * timestamp collisions cannot occur.\n */\n\n/** Monotonic nanosecond timestamp via `performance.now()`. */\nexport function monotonicNs(): number {\n\treturn Math.trunc(performance.now() * 1_000_000);\n}\n\n/** Wall-clock nanosecond timestamp via `Date.now()`. */\nexport function wallClockNs(): number {\n\treturn Date.now() * 1_000_000;\n}\n","/**\n * 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","import {\n\tDATA,\n\tisPhase2Message,\n\tisTerminalMessage,\n\ttype Message,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n} from \"./messages.js\";\n\n/**\n * §1.3.7 — Inside a batch, DIRTY propagates immediately; DATA and RESOLVED are\n * deferred until the outermost `batch()` callback returns. Terminal signals\n * (COMPLETE, ERROR) are delivered after phase-2 messages in the same batch\n * (see canonical ordering in `messages.ts`).\n */\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\nconst pendingPhase2: Array<() => void> = [];\nconst pendingPhase3: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * deferred phase-2 work is draining.\n *\n * Matching Python's `is_batching()` semantics: nested emissions during drain\n * are deferred until the current drain pass completes, preventing ordering\n * bugs when callbacks trigger further DATA/RESOLVED.\n *\n * @returns `true` while inside `batch()` or while the drain loop is running.\n *\n * @example\n * ```ts\n * import { batch, isBatching } from \"@graphrefly/graphrefly-ts\";\n *\n * batch(() => {\n * console.log(isBatching()); // true\n * });\n * ```\n *\n * @category core\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral queue.\n * If `fn` throws (including from a nested `batch`), deferred DATA/RESOLVED for\n * that **outer** `batch` frame are discarded — phase-2 is not flushed after an\n * error. While the drain loop is running (`flushInProgress`), a nested `batch`\n * that throws must **not** clear the global queue (cross-language decision A4).\n *\n * During the drain loop, `isBatching()` remains true so nested `downWithBatch`\n * calls still defer phase-2 messages. The drain loop runs until the queue is\n * quiescent (no pending work remains). Per-emission try/catch ensures one\n * throwing callback does not orphan remaining emissions; the first error is\n * re-thrown after all emissions drain. Callbacks that ran before the throw may\n * have applied phase-2 — partial graph state is intentional (decision C1).\n *\n * @param fn — Synchronous work that may call `downWithBatch` / `node.down()`.\n * @returns `void` — all side-effects happen through `downWithBatch` and the\n * phase-2 drain that runs after `fn` returns.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.batch(() => {\n * core.downWithBatch(sink, [[core.DATA, 1]]);\n * });\n * ```\n *\n * @category core\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\t// Do not wipe the outer drain's queue (decision A4).\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) {\n\t\tflushInProgress = true;\n\t}\n\tconst errors: unknown[] = [];\n\ttry {\n\t\tlet iterations = 0;\n\t\t// Drain phase-2 first, then phase-3. If phase-3 callbacks enqueue new\n\t\t// phase-2 work, the outer loop catches it and drains phase-2 again\n\t\t// before re-entering phase-3.\n\t\twhile (pendingPhase2.length > 0 || pendingPhase3.length > 0) {\n\t\t\t// Phase-2 (DATA/RESOLVED) — parent node values settle here.\n\t\t\twhile (pendingPhase2.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase2.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Phase-3 — meta companion emissions that must follow parent settlement.\n\t\t\tif (pendingPhase3.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase3.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) {\n\t\t\tflushInProgress = false;\n\t\t}\n\t}\n\tif (errors.length === 1) {\n\t\tthrow errors[0];\n\t}\n\tif (errors.length > 1) {\n\t\tthrow new AggregateError(errors, \"batch drain: multiple callbacks threw\");\n\t}\n}\n\n/**\n * Splits a message array into three groups by signal tier (see `messages.ts`):\n *\n * - **immediate** — tier 0–1: DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN, unknown\n * - **deferred** — tier 2: DATA, RESOLVED (phase-2, deferred inside `batch()`)\n * - **terminal** — tier 3: COMPLETE, ERROR (delivered after phase-2)\n *\n * Order within each group is preserved.\n *\n * @param messages — One `down()` payload.\n * @returns Three groups in canonical delivery order.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, partitionForBatch } from \"@graphrefly/graphrefly-ts\";\n *\n * partitionForBatch([[DIRTY], [DATA, 1], [COMPLETE]]);\n * // { immediate: [[DIRTY]], deferred: [[DATA, 1]], terminal: [[COMPLETE]] }\n * ```\n *\n * @category core\n */\nexport function partitionForBatch(messages: Messages): {\n\timmediate: Messages;\n\tdeferred: Messages;\n\tterminal: Messages;\n} {\n\tconst immediate: Message[] = [];\n\tconst deferred: Message[] = [];\n\tconst terminal: Message[] = [];\n\tfor (const m of messages) {\n\t\tif (isPhase2Message(m)) {\n\t\t\tdeferred.push(m);\n\t\t} else if (isTerminalMessage(m[0])) {\n\t\t\tterminal.push(m);\n\t\t} else {\n\t\t\timmediate.push(m);\n\t\t}\n\t}\n\treturn { immediate, deferred, terminal };\n}\n\n/**\n * Delivers messages downstream through `sink`, applying batch semantics and\n * canonical tier-based ordering (see `messages.ts`):\n *\n * 1. **Immediate** (tier 0–1, 4): DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN,\n * unknown — delivered synchronously.\n * 2. **Phase-2** (tier 2): DATA, RESOLVED — deferred while `isBatching()`.\n * 3. **Terminal** (tier 3): COMPLETE, ERROR — always delivered after phase-2.\n * When batching, terminal is queued after deferred phase-2 in the pending list.\n * When not batching, terminal is delivered after phase-2 synchronously.\n *\n * This ordering prevents the \"COMPLETE-before-DATA\" class of bugs: terminal\n * signals never make a node terminal before phase-2 values reach sinks,\n * regardless of how the source assembled the message array.\n *\n * @param sink — Sink callback. May be called up to three times per invocation\n * (immediate, deferred, terminal) when not batching.\n * @param messages — Full `[[Type, Data?], ...]` array for one downstream delivery.\n * @param phase — Starting delivery phase (`2` = data, `3` = terminal). Default `2`.\n * @param options - Optional configuration.\n * @option strategy | `\"partition\"` or `\"sequential\"` | `\"partition\"` | `\"partition\"` groups by tier; `\"sequential\"` preserves message order within each tier using `messageTier()` classification.\n * @returns `void` — delivery is performed through `sink` callbacks, synchronously\n * or deferred into the active batch queue.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.downWithBatch((msgs) => console.log(msgs), [[core.DIRTY], [core.DATA, 42]]);\n * ```\n *\n * @category core\n */\n/** Delivery strategy for {@link downWithBatch}. Mirrors Python `DownStrategy`. */\nexport type DownStrategy = \"partition\" | \"sequential\";\n\nexport function downWithBatch(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n\toptions?: { strategy?: DownStrategy },\n): void {\n\tif (messages.length === 0) {\n\t\treturn;\n\t}\n\n\tif (options?.strategy === \"sequential\") {\n\t\t_downSequential(sink, messages, phase);\n\t\treturn;\n\t}\n\n\tconst queue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\n\t// Fast path: single-message batches (most common in graph-internal propagation)\n\t// skip partitionForBatch allocation entirely.\n\tif (messages.length === 1) {\n\t\tconst t = messages[0][0];\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else if (isTerminalMessage(t)) {\n\t\t\t// Terminal single message: defer when batching so any preceding\n\t\t\t// phase-2 in the queue flushes first.\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate: deliver synchronously.\n\t\t\tsink(messages);\n\t\t}\n\t\treturn;\n\t}\n\t// Multi-message: three-way partition by tier.\n\tconst { immediate, deferred, terminal } = partitionForBatch(messages);\n\n\t// 1. Immediate signals (tier 0–1, 4) — deliver synchronously now.\n\tif (immediate.length > 0) {\n\t\tsink(immediate);\n\t}\n\n\t// 2. Deferred (tier 2) + Terminal (tier 3) — canonical order preserved.\n\tif (isBatching()) {\n\t\tif (deferred.length > 0) {\n\t\t\tqueue.push(() => sink(deferred));\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tqueue.push(() => sink(terminal));\n\t\t}\n\t} else {\n\t\tif (deferred.length > 0) {\n\t\t\tsink(deferred);\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tsink(terminal);\n\t\t}\n\t}\n}\n\n/**\n * Sequential strategy: walk messages one at a time. Phase-2 (DATA/RESOLVED) and\n * terminal (COMPLETE/ERROR) messages are deferred while batching; immediate\n * messages deliver synchronously. Matches graphrefly-py `_down_sequential`.\n */\nfunction _downSequential(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n): void {\n\tconst dataQueue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\tfor (const msg of messages) {\n\t\tconst tier = messageTier(msg[0]);\n\t\tif (tier === 2) {\n\t\t\t// Phase-2 (DATA/RESOLVED): defer while batching.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tdataQueue.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else if (tier >= 3) {\n\t\t\t// Terminal (COMPLETE/ERROR/TEARDOWN): always route to phase-3\n\t\t\t// regardless of the caller's `phase` param — terminals must\n\t\t\t// drain after all phase-2 work to prevent premature termination.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tpendingPhase3.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate (DIRTY, INVALIDATE, PAUSE, RESUME): deliver synchronously.\n\t\t\tsink([msg]);\n\t\t}\n\t}\n}\n","import type { Actor } from \"./actor.js\";\n\n/**\n * Actions checked by {@link NodeGuard}. `write` covers both {@link Node.down} and\n * {@link Node.up} today; finer-grained strings may be added later (e.g. `\"write.data\"`).\n */\nexport type GuardAction = \"write\" | \"signal\" | \"observe\" | (string & {});\n\nexport type NodeGuard = (actor: Actor, action: GuardAction) => boolean;\n\nexport type GuardDeniedDetails = {\n\tactor: Actor;\n\taction: GuardAction;\n\t/** Registry or options name when known */\n\tnodeName?: string;\n};\n\n/**\n * Thrown when a {@link NodeGuard} denies an action for a given actor.\n *\n * Carries the rejected `actor`, `action`, and optional `nodeName` for diagnostic\n * messages and middleware error handling.\n *\n * @example\n * ```ts\n * import { GuardDenied, policy } from \"@graphrefly/graphrefly-ts\";\n *\n * const guard = policy((allow) => { allow(\"observe\"); });\n * try {\n * if (!guard({ type: \"llm\", id: \"agent-1\" }, \"write\")) {\n * throw new GuardDenied(\n * { actor: { type: \"llm\", id: \"agent-1\" }, action: \"write\", nodeName: \"userInput\" },\n * );\n * }\n * } catch (e) {\n * if (e instanceof GuardDenied) console.error(e.action, e.actor.type); // \"write\" \"llm\"\n * }\n * ```\n */\nexport class GuardDenied extends Error {\n\treadonly actor: Actor;\n\treadonly action: GuardAction;\n\treadonly nodeName?: string;\n\n\t/**\n\t * @param details - Actor, action, and optional node name for the denial.\n\t * @param message - Optional override for the default error message.\n\t */\n\tconstructor(details: GuardDeniedDetails, message?: string) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\t`GuardDenied: action \"${String(details.action)}\" denied for actor type \"${String(details.actor.type)}\"`,\n\t\t);\n\t\tthis.name = \"GuardDenied\";\n\t\tthis.actor = details.actor;\n\t\tthis.action = details.action;\n\t\tthis.nodeName = details.nodeName;\n\t}\n\n\t/** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */\n\tget node(): string | undefined {\n\t\treturn this.nodeName;\n\t}\n}\n\ntype Where = (actor: Actor) => boolean;\n\ntype Rule = {\n\tkind: \"allow\" | \"deny\";\n\tactions: Set<GuardAction>;\n\twhere: Where;\n};\n\nfunction normalizeActions(action: GuardAction | readonly GuardAction[]): GuardAction[] {\n\tif (Array.isArray(action)) {\n\t\treturn [...action];\n\t}\n\treturn [action as GuardAction];\n}\n\nfunction matchesActions(set: Set<GuardAction>, action: GuardAction): boolean {\n\treturn set.has(action) || set.has(\"*\" as GuardAction);\n}\n\nexport type PolicyAllow = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyDeny = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyRuleData = {\n\teffect: \"allow\" | \"deny\";\n\taction: GuardAction | readonly GuardAction[];\n\tactorType?: string | readonly string[];\n\tactorId?: string | readonly string[];\n\tclaims?: Record<string, unknown>;\n};\n\n/**\n * Declarative guard builder. Precedence: any matching **deny** blocks even if an allow also matches.\n * If no rule matches, the guard returns `false` (deny-by-default). Aligned with graphrefly-py `policy()`.\n *\n * @param build - Callback that registers `allow(...)` / `deny(...)` rules in order.\n * @returns A `NodeGuard` for use as `node({ guard })`.\n *\n * @example\n * ```ts\n * const guard = policy((allow, deny) => {\n * allow(\"observe\");\n * deny(\"write\", { where: (a) => a.type === \"llm\" });\n * });\n * ```\n */\nexport function policy(build: (allow: PolicyAllow, deny: PolicyDeny) => void): NodeGuard {\n\tconst rules: Rule[] = [];\n\tconst allow: PolicyAllow = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"allow\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tconst deny: PolicyDeny = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"deny\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tbuild(allow, deny);\n\treturn (actor, action) => {\n\t\tlet denied = false;\n\t\tlet allowed = false;\n\t\tfor (const r of rules) {\n\t\t\tif (!matchesActions(r.actions, action)) continue;\n\t\t\tif (!r.where(actor)) continue;\n\t\t\tif (r.kind === \"deny\") {\n\t\t\t\tdenied = true;\n\t\t\t} else {\n\t\t\t\tallowed = true;\n\t\t\t}\n\t\t}\n\t\tif (denied) return false;\n\t\treturn allowed;\n\t};\n}\n\n/**\n * Rebuild a declarative guard from persisted policy data (snapshot-safe).\n *\n * Rules are deny-overrides, same semantics as {@link policy}.\n */\nexport function policyFromRules(rules: readonly PolicyRuleData[]): NodeGuard {\n\treturn policy((allow, deny) => {\n\t\tfor (const rule of rules) {\n\t\t\tconst actorTypes =\n\t\t\t\trule.actorType == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);\n\t\t\tconst actorIds =\n\t\t\t\trule.actorId == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);\n\t\t\tconst claimEntries = Object.entries(rule.claims ?? {});\n\t\t\tconst where: Where = (actor) => {\n\t\t\t\tif (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;\n\t\t\t\tif (actorIds !== null && !actorIds.has(String(actor.id ?? \"\"))) return false;\n\t\t\t\tfor (const [key, value] of claimEntries) {\n\t\t\t\t\tif ((actor as Record<string, unknown>)[key] !== value) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tif (rule.effect === \"deny\") {\n\t\t\t\tdeny(rule.action, { where });\n\t\t\t} else {\n\t\t\t\tallow(rule.action, { where });\n\t\t\t}\n\t\t}\n\t});\n}\n\nconst STANDARD_WRITE_TYPES = [\"human\", \"llm\", \"wallet\", \"system\"] as const;\n\n/**\n * Derives a best-effort `meta.access` hint string by probing `guard` with the\n * standard actor types `human`, `llm`, `wallet`, `system` for the `\"write\"` action\n * (roadmap 1.5). Aligned with graphrefly-py `access_hint_for_guard`.\n *\n * @param guard - Guard function to probe (typically from {@link policy}).\n * @returns `\"restricted\"` when no standard type is allowed; `\"both\"` when both\n * `human` and `llm` are allowed (plus optionally `system`); the single allowed\n * type name when only one passes; or a `\"+\"` joined list otherwise.\n *\n * @example\n * ```ts\n * import { policy, accessHintForGuard } from \"@graphrefly/graphrefly-ts\";\n *\n * const guardBoth = policy((allow) => { allow(\"write\"); });\n * accessHintForGuard(guardBoth); // \"both\"\n *\n * const guardHuman = policy((allow) => {\n * allow(\"write\", { where: (a) => a.type === \"human\" });\n * });\n * accessHintForGuard(guardHuman); // \"human\"\n * ```\n */\nexport function accessHintForGuard(guard: NodeGuard): string {\n\tconst allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: \"\" }, \"write\"));\n\tif (allowed.length === 0) return \"restricted\";\n\tif (\n\t\tallowed.includes(\"human\") &&\n\t\tallowed.includes(\"llm\") &&\n\t\tallowed.every((t) => t === \"human\" || t === \"llm\" || t === \"system\")\n\t) {\n\t\treturn \"both\";\n\t}\n\tif (allowed.length === 1) return allowed[0];\n\treturn allowed.join(\"+\");\n}\n","/**\n * Node versioning — GRAPHREFLY-SPEC §7.\n *\n * Progressive, optional versioning for node identity and change tracking.\n *\n * - **V0**: `id` + `version` — identity & change detection (~16 bytes overhead)\n * - **V1**: + `cid` + `prev` — content addressing & linked history (~60 bytes overhead)\n *\n * **Lifecycle notes:**\n * - Version advances only on DATA (not RESOLVED, INVALIDATE, or TEARDOWN).\n * - `resetOnTeardown` clears the cached value but does NOT reset versioning state.\n * After teardown, `v.cid` still reflects the last DATA value, not the cleared cache.\n * The invariant `hash(node.get()) === v.cid` only holds in `settled`/`resolved` status.\n * - Resubscribable nodes preserve versioning across subscription lifetimes (monotonic counter).\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** V0: identity + monotonic version counter. */\nexport type V0 = {\n\treadonly id: string;\n\tversion: number;\n};\n\n/** V1: V0 + content-addressed identifier + previous cid link. */\nexport type V1 = V0 & {\n\tcid: string;\n\tprev: string | null;\n};\n\n/** Union of all versioning info shapes. */\nexport type NodeVersionInfo = V0 | V1;\n\n/** Supported versioning levels (extensible to 2, 3 later). */\nexport type VersioningLevel = 0 | 1;\n\n/** Function that hashes a value to a hex string (for V1 cid). */\nexport type HashFn = (value: unknown) => string;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface VersioningOptions {\n\t/** Override auto-generated id. */\n\tid?: string;\n\t/** Custom hash function for V1 cid (default: SHA-256 truncated to 16 hex chars). */\n\thash?: HashFn;\n}\n\n// ---------------------------------------------------------------------------\n// Default hash\n// ---------------------------------------------------------------------------\n\n/**\n * Canonicalize a value for deterministic cross-language hashing.\n *\n * - Integer-valued floats normalize to integer strings (`1.0` → `1`).\n * - `NaN`, `Infinity`, `-Infinity` are rejected (no JSON equivalent).\n * - `undefined` normalizes to `null`.\n * - Object keys are sorted lexicographically.\n *\n * This ensures TS `JSON.stringify` and Python `json.dumps(sort_keys=True)`\n * produce identical output for the same logical value.\n */\nexport function canonicalizeForHash(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow new TypeError(`Cannot hash non-finite number: ${value}`);\n\t\t}\n\t\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. ` +\n\t\t\t\t\t\"Cross-language cid parity is not guaranteed for unsafe integers.\",\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\" || typeof value === \"boolean\" || value === null) {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalizeForHash);\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst sorted: Record<string, unknown> = {};\n\t\tfor (const k of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tsorted[k] = canonicalizeForHash((value as Record<string, unknown>)[k]);\n\t\t}\n\t\treturn sorted;\n\t}\n\t// Fallback: coerce to null (bigint, symbol, function)\n\treturn null;\n}\n\n/**\n * Default content hash: SHA-256 of deterministic JSON, truncated to 16 hex chars (~64-bit).\n * Uses {@link canonicalizeForHash} for cross-language parity with Python `default_hash`.\n */\nexport function defaultHash(value: unknown): string {\n\tconst canonical = canonicalizeForHash(value ?? null);\n\tconst json = JSON.stringify(canonical);\n\treturn createHash(\"sha256\").update(json).digest(\"hex\").slice(0, 16);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create initial versioning state for a node.\n *\n * @param level - 0 for V0, 1 for V1.\n * @param initialValue - The node's initial cached value (used for V1 cid).\n * @param opts - Optional overrides (id, hash).\n */\nexport function createVersioning(\n\tlevel: VersioningLevel,\n\tinitialValue: unknown,\n\topts?: VersioningOptions,\n): NodeVersionInfo {\n\tconst id = opts?.id ?? randomUUID();\n\tif (level === 0) {\n\t\treturn { id, version: 0 } satisfies V0;\n\t}\n\tconst hash = opts?.hash ?? defaultHash;\n\tconst cid = hash(initialValue);\n\treturn { id, version: 0, cid, prev: null } satisfies V1;\n}\n\n// ---------------------------------------------------------------------------\n// Advance\n// ---------------------------------------------------------------------------\n\n/**\n * Advance versioning state after a DATA emission (value changed).\n *\n * Mutates `info` in place for performance (called on every DATA).\n * Only call when the cached value has actually changed (not on RESOLVED).\n *\n * @param info - The node's current versioning state.\n * @param newValue - The new cached value.\n * @param hashFn - Hash function (only used for V1).\n */\nexport function advanceVersion(info: NodeVersionInfo, newValue: unknown, hashFn: HashFn): void {\n\tinfo.version += 1;\n\tif (\"cid\" in info) {\n\t\t(info as V1).prev = (info as V1).cid;\n\t\t(info as V1).cid = hashFn(newValue);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this V1 versioning info? */\nexport function isV1(info: NodeVersionInfo): info is V1 {\n\treturn \"cid\" in info;\n}\n","import type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, NodeVersionInfo, VersioningLevel } from \"./versioning.js\";\nimport { advanceVersion, createVersioning, defaultHash } from \"./versioning.js\";\n\n/**\n * Internal sentinel value: \"no cached value has been set or emitted.\"\n * Used instead of `undefined` so that `undefined` can be a valid emitted value.\n */\nexport const NO_VALUE: unique symbol = Symbol.for(\"graphrefly/NO_VALUE\");\n\n/**\n * Branded symbol that marks a {@link CleanupResult} wrapper.\n * Used internally by {@link cleanupResult} — prevents duck-type collisions\n * with domain objects that happen to have a `cleanup` property.\n */\nexport const CLEANUP_RESULT: unique symbol = Symbol.for(\"graphrefly/CLEANUP_RESULT\");\n\n/** Lifecycle status of a node. */\nexport type NodeStatus =\n\t| \"disconnected\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\n/** Callback that receives downstream message batches. */\nexport type NodeSink = (messages: Messages) => void;\n\n/**\n * Compute function passed to `node()`.\n *\n * @returns A value to emit, `undefined` to skip emission, or a cleanup\n * function invoked before the next run or on teardown.\n */\nexport type NodeFn<T = unknown> = (\n\tdeps: readonly unknown[],\n\tactions: NodeActions,\n) => T | undefined | (() => void);\n\n/** Imperative actions available inside a {@link NodeFn}. */\nexport interface NodeActions {\n\t/** Emit raw messages downstream. */\n\tdown(messages: Messages): void;\n\t/** Emit a single value (auto-wraps in DIRTY/DATA or DIRTY/RESOLVED). */\n\temit(value: unknown): void;\n\t/** Send messages upstream toward sources. */\n\tup(messages: Messages): void;\n}\n\n/**\n * Callback for intercepting messages before the default dispatch.\n *\n * Called for every message from every dep. Return `true` to consume the\n * message (skip default handling), or `false` to let default dispatch run.\n *\n * @param msg — The message tuple `[Type, Data?]`.\n * @param depIndex — Which dep sent it (index into the deps array).\n * @param actions — `{ down(), emit(), up() }` — same as `NodeFn` receives.\n */\nexport type OnMessageHandler = (msg: Message, depIndex: number, actions: NodeActions) => boolean;\n\n/**\n * Internal inspector hook (opt-in): emits dependency message and run events\n * for graph-level observability features (`observe(..., { causal|derived })`).\n */\nexport type NodeInspectorHookEvent =\n\t| { kind: \"dep_message\"; depIndex: number; message: Message }\n\t| { kind: \"run\"; depValues: readonly unknown[] };\n\nexport type NodeInspectorHook = (event: NodeInspectorHookEvent) => void;\n\n/** Explicit describe `type` for {@link Graph.describe} / {@link describeNode} (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\n/** Options for {@link node}. */\nexport interface NodeOptions {\n\tname?: string;\n\t/**\n\t * Overrides inferred `type` in describe output. Sugar constructors set this;\n\t * omit to infer from deps / fn / manual emit usage.\n\t */\n\tdescribeKind?: NodeDescribeKind;\n\t/** Equality check for RESOLVED detection. Defaults to `Object.is`. */\n\tequals?: (a: unknown, b: unknown) => boolean;\n\tinitial?: unknown;\n\t/**\n\t * Each key becomes an independently subscribable companion node.\n\t * Meta nodes outlive the parent's subscription lifecycle: when all sinks\n\t * unsubscribe the parent disconnects upstream but meta nodes stay alive.\n\t * Send `[[TEARDOWN]]` to the parent to release meta node resources.\n\t */\n\tmeta?: Record<string, unknown>;\n\t/** Allow fresh subscriptions after COMPLETE/ERROR. */\n\tresubscribable?: boolean;\n\t/**\n\t * Invoked when a new {@link Node.subscribe} clears a terminal state on a\n\t * resubscribable node — reset operator-local counters/accumulators here.\n\t */\n\tonResubscribe?: () => void;\n\t/** Clear cached value on TEARDOWN. */\n\tresetOnTeardown?: boolean;\n\t/**\n\t * When `true` (default), auto-emit `[[COMPLETE]]` when all deps complete\n\t * (spec §1.3.5). Set `false` for derived/operator nodes that should not\n\t * auto-complete.\n\t */\n\tcompleteWhenDepsComplete?: boolean;\n\t/**\n\t * Intercept messages before the default dispatch (spec §2.6).\n\t *\n\t * Return `true` to consume the message (skip default handling),\n\t * or `false` to let the default dispatch run.\n\t */\n\tonMessage?: OnMessageHandler;\n\t/**\n\t * ABAC: `(actor, action) => boolean`. `write` applies to both {@link Node.down} and {@link Node.up}.\n\t * Companion {@link NodeOptions.meta | meta} nodes inherit this guard from the primary.\n\t */\n\tguard?: NodeGuard;\n\t/**\n\t * Opt-in versioning level (GRAPHREFLY-SPEC §7).\n\t * - `0` (V0): `id` + `version` — identity & change detection.\n\t * - `1` (V1): + `cid` + `prev` — content addressing & linked history.\n\t */\n\tversioning?: VersioningLevel;\n\t/** Override auto-generated versioning id. */\n\tversioningId?: string;\n\t/** Custom hash function for V1 cid computation. */\n\tversioningHash?: HashFn;\n}\n\n/**\n * Options for {@link Node.down} / {@link Node.up} (actor context, graph delivery mode, internal bypass).\n */\nexport type NodeTransportOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips guard checks (reactive internals, graph lifecycle TEARDOWN, etc.).\n\t * Not for untrusted call sites.\n\t */\n\tinternal?: boolean;\n\t/**\n\t * `signal` for {@link Graph.signal} deliveries; default `write` for {@link Graph.set} and direct `down`.\n\t */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/**\n * Optional hints passed to {@link Node.subscribe} to enable per-sink\n * optimizations.\n */\nexport interface SubscribeHints {\n\t/**\n\t * Subscriber has exactly one dep with `fn` — the source may skip DIRTY\n\t * dispatch when this is the sole subscriber. The subscriber synthesizes\n\t * dirty state locally via `onDepSettled`.\n\t */\n\tsingleDep?: boolean;\n\t/**\n\t * Actor to check against the node's `observe` guard.\n\t * When set, `subscribe()` throws {@link GuardDenied} if the actor is not\n\t * permitted to observe this node. Aligned with graphrefly-py `subscribe(actor=)`.\n\t */\n\tactor?: Actor;\n}\n\n/** A reactive node in the GraphReFly protocol. */\nexport interface Node<T = unknown> {\n\treadonly name?: string;\n\treadonly status: NodeStatus;\n\treadonly meta: Record<string, Node>;\n\t/** Returns the current cached value. */\n\tget(): T | undefined;\n\t/** Push messages downstream. */\n\tdown(messages: Messages, options?: NodeTransportOptions): void;\n\t/**\n\t * Registers a sink to receive downstream messages.\n\t *\n\t * @param sink - Callback receiving message batches.\n\t * @param hints - Optional optimization hints (e.g. `{ singleDep: true }`).\n\t * @returns An unsubscribe function (idempotent).\n\t */\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void;\n\t/** Send messages upstream (present on nodes with deps). */\n\tup?: (messages: Messages, options?: NodeTransportOptions) => void;\n\t/** Disconnect from upstream deps (present on nodes with deps). */\n\tunsubscribe?: () => void;\n\t/** Last successful guarded `down` / `up` (not set for `internal` deliveries). */\n\treadonly lastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/** Whether {@link NodeTransportOptions.actor | actor} may {@link Graph.observe | observe} this node. */\n\tallowsObserve(actor: Actor): boolean;\n\t/** Whether a {@link NodeOptions.guard | guard} is installed. */\n\thasGuard(): boolean;\n\t/** Versioning info (GRAPHREFLY-SPEC §7). `undefined` when versioning is not enabled. */\n\treadonly v: Readonly<NodeVersionInfo> | undefined;\n}\n\n// --- Bitmask helpers: integer for <=31 deps, Uint32Array for >31 ---\n\ninterface BitSet {\n\tset(index: number): void;\n\tclear(index: number): void;\n\thas(index: number): boolean;\n\t/**\n\t * True when all bits in `other` are also set in `this`.\n\t * IMPORTANT: `other` must be the same concrete type (both IntBitSet or both\n\t * ArrayBitSet). Cross-type calls will crash. Within `node()`, all masks for\n\t * a given node share the same `createBitSet(deps.length)` factory, so this\n\t * is always satisfied.\n\t */\n\tcovers(other: BitSet): boolean;\n\t/** True when at least one bit is set. */\n\tany(): boolean;\n\treset(): void;\n}\n\nfunction createIntBitSet(): BitSet {\n\tlet bits = 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\tbits |= 1 << i;\n\t\t},\n\t\tclear(i: number) {\n\t\t\tbits &= ~(1 << i);\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (bits & (1 << i)) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\treturn (\n\t\t\t\t(bits & (other as unknown as { _bits(): number })._bits()) ===\n\t\t\t\t(other as unknown as { _bits(): number })._bits()\n\t\t\t);\n\t\t},\n\t\tany() {\n\t\t\treturn bits !== 0;\n\t\t},\n\t\treset() {\n\t\t\tbits = 0;\n\t\t},\n\t\t_bits() {\n\t\t\treturn bits;\n\t\t},\n\t} as BitSet & { _bits(): number };\n}\n\nfunction createArrayBitSet(size: number): BitSet {\n\tconst words = new Uint32Array(Math.ceil(size / 32));\n\treturn {\n\t\tset(i: number) {\n\t\t\twords[i >>> 5] |= 1 << (i & 31);\n\t\t},\n\t\tclear(i: number) {\n\t\t\twords[i >>> 5] &= ~(1 << (i & 31));\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (words[i >>> 5] & (1 << (i & 31))) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst ow = (other as unknown as { _words: Uint32Array })._words;\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif ((words[w] & ow[w]) >>> 0 !== ow[w]) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\t\tany() {\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif (words[w] !== 0) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\treset() {\n\t\t\twords.fill(0);\n\t\t},\n\t\t_words: words,\n\t} as unknown as BitSet;\n}\n\nfunction createBitSet(size: number): BitSet {\n\treturn size <= 31 ? createIntBitSet() : createArrayBitSet(size);\n}\n\nconst isNodeArray = (value: unknown): value is readonly Node[] => Array.isArray(value);\n\nconst isNodeOptions = (value: unknown): value is NodeOptions =>\n\ttypeof value === \"object\" && value != null && !Array.isArray(value);\n\n/**\n * Explicit cleanup wrapper. When a node fn returns `{ cleanup, value? }`,\n * `cleanup` is registered as the teardown/recompute cleanup and `value`\n * (if present) is emitted as data. This avoids the ambiguity where returning\n * a plain function is silently consumed as cleanup instead of emitted as data.\n *\n * Use the {@link cleanupResult} factory to create instances — it stamps the\n * branded {@link CLEANUP_RESULT} symbol so that domain objects with a `cleanup`\n * property are never misinterpreted.\n *\n * Plain function returns are still treated as cleanup for backward compatibility.\n */\nexport type CleanupResult<T = unknown> = {\n\treadonly [CLEANUP_RESULT]: true;\n\tcleanup: () => void;\n\tvalue?: T;\n};\n\n/**\n * Create a branded {@link CleanupResult}.\n *\n * ```ts\n * node([dep], () => cleanupResult(() => release(), computedValue))\n * ```\n */\nexport function cleanupResult<T>(cleanup: () => void): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, value: T): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, ...args: [] | [T]): CleanupResult<T> {\n\tconst r: CleanupResult<T> = { [CLEANUP_RESULT]: true, cleanup };\n\tif (args.length > 0) r.value = args[0];\n\treturn r;\n}\n\nconst isCleanupResult = (value: unknown): value is CleanupResult =>\n\ttypeof value === \"object\" && value !== null && CLEANUP_RESULT in value;\n\nconst isCleanupFn = (value: unknown): value is () => void => typeof value === \"function\";\n\nconst statusAfterMessage = (status: NodeStatus, msg: Message): NodeStatus => {\n\tconst t = msg[0];\n\tif (t === DIRTY) return \"dirty\";\n\tif (t === DATA) return \"settled\";\n\tif (t === RESOLVED) return \"resolved\";\n\tif (t === COMPLETE) return \"completed\";\n\tif (t === ERROR) return \"errored\";\n\tif (t === INVALIDATE) return \"dirty\";\n\tif (t === TEARDOWN) return \"disconnected\";\n\treturn status;\n};\n\n// --- NodeImpl: class-based for V8 hidden class optimization and prototype method sharing ---\n\n/**\n * Class-based implementation of the {@link Node} interface.\n *\n * All internal state lives on instance fields (`_` prefix, private by convention)\n * so that introspection (e.g. {@link describeNode}) can read them directly via\n * `instanceof NodeImpl` — no side-channel registry needed.\n *\n * Follows callbag-recharge's `ProducerImpl` pattern: V8 hidden class stability,\n * prototype method sharing, selective binding for commonly detached methods.\n */\nexport class NodeImpl<T = unknown> implements Node<T> {\n\t// --- Configuration (set once, never reassigned) ---\n\tprivate readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\t/** @internal — read by {@link describeNode} before inference. */\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\t_deps: readonly Node[];\n\t_fn: NodeFn<T> | undefined;\n\t_opts: NodeOptions;\n\t_equals: (a: unknown, b: unknown) => boolean;\n\t_onMessage: OnMessageHandler | undefined;\n\t/** @internal — read by {@link describeNode} for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\tprivate _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\t_hasDeps: boolean;\n\t_autoComplete: boolean;\n\t_isSingleDep: boolean;\n\n\t// --- Mutable state ---\n\t_cached: T | typeof NO_VALUE;\n\t_status: NodeStatus;\n\t_terminal = false;\n\t_connected = false;\n\t_producerStarted = false;\n\t_connecting = false;\n\t_manualEmitUsed = false;\n\t_sinkCount = 0;\n\t_singleDepSinkCount = 0;\n\n\t// --- Object/collection state ---\n\t_depDirtyMask: BitSet;\n\t_depSettledMask: BitSet;\n\t_depCompleteMask: BitSet;\n\t_allDepsCompleteMask: BitSet;\n\t_lastDepValues: readonly unknown[] | undefined;\n\t_cleanup: (() => void) | undefined;\n\t_sinks: NodeSink | Set<NodeSink> | null = null;\n\t_singleDepSinks = new WeakSet<NodeSink>();\n\t_upstreamUnsubs: Array<() => void> = [];\n\t_actions: NodeActions;\n\t_boundDownToSinks: (messages: Messages) => void;\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\tprivate _versioning: NodeVersionInfo | undefined;\n\tprivate _hashFn: HashFn;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn<T> | undefined, opts: NodeOptions) {\n\t\tthis._deps = deps;\n\t\tthis._fn = fn;\n\t\tthis._opts = opts;\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._guard = opts.guard;\n\t\tthis._hasDeps = deps.length > 0;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._isSingleDep = deps.length === 1 && fn != null;\n\n\t\tthis._cached = \"initial\" in opts ? (opts.initial as T) : NO_VALUE;\n\t\tthis._status = this._hasDeps ? \"disconnected\" : \"settled\";\n\n\t\t// Versioning (GRAPHREFLY-SPEC §7)\n\t\tthis._hashFn = opts.versioningHash ?? defaultHash;\n\t\tthis._versioning =\n\t\t\topts.versioning != null\n\t\t\t\t? createVersioning(opts.versioning, this._cached === NO_VALUE ? undefined : this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\tthis._depDirtyMask = createBitSet(deps.length);\n\t\tthis._depSettledMask = createBitSet(deps.length);\n\t\tthis._depCompleteMask = createBitSet(deps.length);\n\t\tthis._allDepsCompleteMask = createBitSet(deps.length);\n\t\tfor (let i = 0; i < deps.length; i++) this._allDepsCompleteMask.set(i);\n\n\t\t// Build companion meta nodes\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = node({\n\t\t\t\tinitial: v,\n\t\t\t\tname: `${opts.name ?? \"node\"}:meta:${k}`,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t\t});\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions object: created once, references `this` methods.\n\t\t// Captures `this` via arrow-in-object so manualEmitUsed is set on the instance.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._manualEmitUsed = true;\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._manualEmitUsed = true;\n\t\t\t\tself._downAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tself._upInternal(messages);\n\t\t\t},\n\t\t};\n\n\t\t// Bind commonly detached protocol methods\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t\tthis._boundDownToSinks = this._downToSinks.bind(this);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/**\n\t * When a node is registered with {@link Graph.add} without an options `name`,\n\t * the graph assigns the registry local name for introspection (parity with graphrefly-py).\n\t */\n\t_assignRegistryName(localName: string): void {\n\t\tif (this._optsName !== undefined || this._registryName !== undefined) return;\n\t\tthis._registryName = localName;\n\t}\n\n\t/**\n\t * @internal Attach/remove inspector hook for graph-level observability.\n\t * Returns a disposer that restores the previous hook.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tconst prev = this._inspectorHook;\n\t\tthis._inspectorHook = hook;\n\t\treturn () => {\n\t\t\tif (this._inspectorHook === hook) {\n\t\t\t\tthis._inspectorHook = prev;\n\t\t\t}\n\t\t};\n\t}\n\n\t// --- Public interface (Node<T>) ---\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\tget v(): Readonly<NodeVersionInfo> | undefined {\n\t\treturn this._versioning;\n\t}\n\n\t/**\n\t * Retroactively apply versioning to a node that was created without it.\n\t * No-op if versioning is already enabled.\n\t *\n\t * Version starts at 0 regardless of prior DATA emissions — it tracks\n\t * changes from the moment versioning is enabled, not historical ones.\n\t *\n\t * @internal — used by {@link Graph.setVersioning}.\n\t */\n\t_applyVersioning(level: VersioningLevel, opts?: { id?: string; hash?: HashFn }): void {\n\t\tif (this._versioning != null) return;\n\t\tthis._hashFn = opts?.hash ?? this._hashFn;\n\t\tthis._versioning = createVersioning(\n\t\t\tlevel,\n\t\t\tthis._cached === NO_VALUE ? undefined : this._cached,\n\t\t\t{\n\t\t\t\tid: opts?.id,\n\t\t\t\thash: this._hashFn,\n\t\t\t},\n\t\t);\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\tget(): T | undefined {\n\t\treturn this._cached === NO_VALUE ? undefined : this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\tprivate _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet lifecycleMessages = messages;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._opts.resubscribable) {\n\t\t\tconst terminalPassthrough = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (terminalPassthrough.length === 0) return;\n\t\t\tlifecycleMessages = terminalPassthrough;\n\t\t\tsinkMessages = terminalPassthrough;\n\t\t}\n\t\tthis._handleLocalLifecycle(lifecycleMessages);\n\t\t// Single-dep optimization: skip DIRTY to sinks when sole subscriber is single-dep\n\t\t// AND the batch contains a phase-2 message (DATA/RESOLVED). Standalone DIRTY\n\t\t// (without follow-up) must pass through so downstream is notified.\n\t\tif (this._canSkipDirty()) {\n\t\t\t// Inline check: does the batch contain DATA or RESOLVED?\n\t\t\tlet hasPhase2 = false;\n\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\tconst t = sinkMessages[i][0];\n\t\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\t\thasPhase2 = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPhase2) {\n\t\t\t\t// Inline filter: remove DIRTY messages\n\t\t\t\tconst filtered: Message[] = [];\n\t\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\t\tif (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);\n\t\t\t\t}\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tdownWithBatch(this._boundDownToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tdownWithBatch(this._boundDownToSinks, sinkMessages);\n\t}\n\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void {\n\t\tif (hints?.actor != null && this._guard != null) {\n\t\t\tconst actor = normalizeActor(hints.actor);\n\t\t\tif (!this._guard(actor, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\tif (this._terminal && this._opts.resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._status = this._hasDeps ? \"disconnected\" : \"settled\";\n\t\t\tthis._opts.onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\tif (this._hasDeps) {\n\t\t\tthis._connectUpstream();\n\t\t} else if (this._fn) {\n\t\t\tthis._startProducer();\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tif (this._singleDepSinks.has(sink)) {\n\t\t\t\tthis._singleDepSinkCount -= 1;\n\t\t\t\tthis._singleDepSinks.delete(sink);\n\t\t\t}\n\t\t\tif (this._sinks == null) return;\n\t\t\tif (typeof this._sinks === \"function\") {\n\t\t\t\tif (this._sinks === sink) this._sinks = null;\n\t\t\t} else {\n\t\t\t\tthis._sinks.delete(sink);\n\t\t\t\tif (this._sinks.size === 1) {\n\t\t\t\t\tconst [only] = this._sinks;\n\t\t\t\t\tthis._sinks = only;\n\t\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\t\tthis._sinks = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._sinks == null) {\n\t\t\t\tthis._disconnectUpstream();\n\t\t\t\tthis._stopProducer();\n\t\t\t}\n\t\t};\n\t}\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tif (options === undefined) {\n\t\t\t\tdep.up?.(messages);\n\t\t\t} else {\n\t\t\t\tdep.up?.(messages, options);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _upInternal(messages: Messages): void {\n\t\tif (!this._hasDeps) return;\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tif (!this._hasDeps) return;\n\t\tthis._disconnectUpstream();\n\t}\n\n\t// --- Private methods (prototype, _ prefix) ---\n\n\t_downToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others mid-iteration.\n\t\t// Iterating the live Set would skip not-yet-visited sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\t_handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (m.length < 2) {\n\t\t\t\t\t// GRAPHREFLY-SPEC §1.2: bare [DATA] without payload is a protocol violation.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\t// GRAPHREFLY-SPEC §1.2: clear cached state; do not auto-emit from here.\n\t\t\t\tconst cleanupFn = this._cleanup;\n\t\t\t\tthis._cleanup = undefined;\n\t\t\t\tcleanupFn?.();\n\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t\tthis._lastDepValues = undefined;\n\t\t\t}\n\t\t\tthis._status = statusAfterMessage(this._status, m);\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._opts.resetOnTeardown) {\n\t\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t\t}\n\t\t\t\t// Invoke cleanup for compute nodes (deps+fn) — spec §2.4\n\t\t\t\t// requires cleanup on teardown, not just before next invocation.\n\t\t\t\t// _stopProducer handles cleanup for producer nodes separately.\n\t\t\t\tconst teardownCleanup = this._cleanup;\n\t\t\t\tthis._cleanup = undefined;\n\t\t\t\tteardownCleanup?.();\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._disconnectUpstream();\n\t\t\t\t\tthis._stopProducer();\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Propagate other meta-eligible signals (centralized in messages.ts).\n\t\t\tif (t !== TEARDOWN && propagatesToMeta(t)) {\n\t\t\t\tthis._propagateToMeta(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Propagate a signal to all companion meta nodes (best-effort). */\n\t_propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\t(metaNode as NodeImpl)._downInternal([[t]]);\n\t\t\t} catch {\n\t\t\t\t/* best-effort: other meta nodes still receive the signal */\n\t\t\t}\n\t\t}\n\t}\n\n\t_canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\t_downAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\t// §2.5: equals() only compares two real values. NO_VALUE sentinel means\n\t\t// \"never emitted / cache cleared\" — first emission always treated as changed.\n\t\tlet unchanged: boolean;\n\t\ttry {\n\t\t\tunchanged = this._cached !== NO_VALUE && this._equals(this._cached, value);\n\t\t} catch (eqErr) {\n\t\t\tconst eqMsg = eqErr instanceof Error ? eqErr.message : String(eqErr);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": equals threw: ${eqMsg}`, { cause: eqErr });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\treturn;\n\t\t}\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\t// _handleLocalLifecycle (called by _downInternal) sets _cached from the DATA payload.\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n\n\t_runFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._terminal && !this._opts.resubscribable) return;\n\t\tif (this._connecting) return;\n\n\t\ttry {\n\t\t\tconst n = this._deps.length;\n\t\t\tconst depValues = new Array(n);\n\t\t\tfor (let i = 0; i < n; i++) depValues[i] = this._deps[i].get();\n\t\t\t// Identity check BEFORE cleanup: if all dep values are unchanged,\n\t\t\t// skip cleanup+fn entirely so effect nodes don't teardown/restart on no-op.\n\t\t\tconst prev = this._lastDepValues;\n\t\t\tif (n > 0 && prev != null && prev.length === n) {\n\t\t\t\tlet allSame = true;\n\t\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\t\tif (!Object.is(depValues[i], prev[i])) {\n\t\t\t\t\t\tallSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (allSame) {\n\t\t\t\t\tif (this._status === \"dirty\") {\n\t\t\t\t\t\tthis._downInternal([[RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevCleanup = this._cleanup;\n\t\t\tthis._cleanup = undefined;\n\t\t\tprevCleanup?.();\n\t\t\tthis._manualEmitUsed = false;\n\t\t\tthis._lastDepValues = depValues;\n\t\t\tthis._inspectorHook?.({ kind: \"run\", depValues });\n\t\t\tconst out = this._fn(depValues, this._actions);\n\t\t\t// Explicit cleanup wrapper: { cleanup, value? }\n\t\t\tif (isCleanupResult(out)) {\n\t\t\t\tthis._cleanup = out.cleanup;\n\t\t\t\tif (this._manualEmitUsed) return;\n\t\t\t\tif (\"value\" in out) {\n\t\t\t\t\tthis._downAutoValue(out.value);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Legacy: plain function return → cleanup (backward compat)\n\t\t\tif (isCleanupFn(out)) {\n\t\t\t\tthis._cleanup = out;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this._manualEmitUsed) return;\n\t\t\tif (out === undefined) return;\n\t\t\tthis._downAutoValue(out);\n\t\t} catch (err) {\n\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, { cause: err });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t}\n\t}\n\n\t_onDepDirty(index: number): void {\n\t\tconst wasDirty = this._depDirtyMask.has(index);\n\t\tthis._depDirtyMask.set(index);\n\t\tthis._depSettledMask.clear(index);\n\t\tif (!wasDirty) {\n\t\t\tthis._downInternal([[DIRTY]]);\n\t\t}\n\t}\n\n\t_onDepSettled(index: number): void {\n\t\tif (!this._depDirtyMask.has(index)) {\n\t\t\tthis._onDepDirty(index);\n\t\t}\n\t\tthis._depSettledMask.set(index);\n\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\tthis._depDirtyMask.reset();\n\t\t\tthis._depSettledMask.reset();\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\t_maybeCompleteFromDeps(): void {\n\t\tif (\n\t\t\tthis._autoComplete &&\n\t\t\tthis._deps.length > 0 &&\n\t\t\tthis._depCompleteMask.covers(this._allDepsCompleteMask)\n\t\t) {\n\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t}\n\t}\n\n\t_handleDepMessages(index: number, messages: Messages): void {\n\t\tfor (const msg of messages) {\n\t\t\tthis._inspectorHook?.({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\t\t\t// User-defined message handler gets first look (spec §2.6).\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!this._fn) {\n\t\t\t\t// Passthrough: forward all messages except COMPLETE when multi-dep.\n\t\t\t\t// Multi-dep passthrough must wait for ALL deps to complete (§1.3.5).\n\t\t\t\tif (t === COMPLETE && this._deps.length > 1) {\n\t\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._onDepDirty(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._onDepSettled(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\t// Complete implies no longer pending — clear dirty/settled bits\n\t\t\t\t// so a preceding DIRTY from this dep doesn't block settlement.\n\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\tthis._depSettledMask.clear(index);\n\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t} else if (!this._depDirtyMask.any() && this._status === \"dirty\") {\n\t\t\t\t\t// D2: dep went DIRTY→COMPLETE without DATA — node was marked\n\t\t\t\t\t// dirty but no settlement came. Recompute so downstream\n\t\t\t\t\t// gets RESOLVED (value unchanged) or DATA (value changed).\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Forward unknown message types\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\t_connectUpstream(): void {\n\t\tif (!this._hasDeps || this._connected) return;\n\t\tthis._connected = true;\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\tthis._status = \"settled\";\n\t\tconst subHints: SubscribeHints | undefined = this._isSingleDep\n\t\t\t? { singleDep: true }\n\t\t\t: undefined;\n\t\tthis._connecting = true;\n\t\ttry {\n\t\t\tfor (let i = 0; i < this._deps.length; i += 1) {\n\t\t\t\tconst dep = this._deps[i];\n\t\t\t\tthis._upstreamUnsubs.push(\n\t\t\t\t\tdep.subscribe((msgs) => this._handleDepMessages(i, msgs), subHints),\n\t\t\t\t);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._connecting = false;\n\t\t}\n\t\tif (this._fn) {\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\t_stopProducer(): void {\n\t\tif (!this._producerStarted) return;\n\t\tthis._producerStarted = false;\n\t\tconst producerCleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tproducerCleanup?.();\n\t}\n\n\t_startProducer(): void {\n\t\tif (this._deps.length !== 0 || !this._fn || this._producerStarted) return;\n\t\tthis._producerStarted = true;\n\t\tthis._runFn();\n\t}\n\n\t_disconnectUpstream(): void {\n\t\tif (!this._connected) return;\n\t\tfor (const unsub of this._upstreamUnsubs.splice(0)) {\n\t\t\tunsub();\n\t\t}\n\t\tthis._connected = false;\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\tthis._status = \"disconnected\";\n\t}\n}\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (GRAPHREFLY-SPEC §2).\n *\n * Typical shapes: `node([])` / `node([], opts)` for a manual source; `node(producerFn, opts)` for a\n * producer; `node(deps, computeFn, opts)` for derived nodes and operators.\n *\n * @param depsOrFn - Dependency nodes, a {@link NodeFn} (producer), or {@link NodeOptions} alone.\n * @param fnOrOpts - With deps: compute function or options. Omitted for producer-only form.\n * @param optsArg - Options when both `deps` and `fn` are provided.\n * @returns `Node<T>` - Configured node instance (lazy until subscribed).\n *\n * @remarks\n * **Protocol:** DIRTY / DATA / RESOLVED ordering, completion, and batch deferral follow `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n *\n * **`equals` and mutable values:** The default `Object.is` identity check is\n * correct for the common immutable-value case. If your node produces mutable\n * objects (e.g. arrays or maps mutated in place), provide a custom `equals`\n * function — otherwise `Object.is` will always return `true` for the same\n * reference and the node will emit `RESOLVED` instead of `DATA`.\n *\n * @example\n * ```ts\n * import { node, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = node([a], ([x]) => (x as number) + 1);\n * ```\n *\n * @seeAlso [Specification](/spec)\n *\n * @category core\n */\nexport function node<T = unknown>(\n\tdepsOrFn?: readonly Node[] | NodeFn<T> | NodeOptions,\n\tfnOrOpts?: NodeFn<T> | NodeOptions,\n\toptsArg?: NodeOptions,\n): Node<T> {\n\tconst deps: readonly Node[] = isNodeArray(depsOrFn) ? depsOrFn : [];\n\tconst fn: NodeFn<T> | undefined =\n\t\ttypeof depsOrFn === \"function\"\n\t\t\t? depsOrFn\n\t\t\t: typeof fnOrOpts === \"function\"\n\t\t\t\t? fnOrOpts\n\t\t\t\t: undefined;\n\tlet opts: NodeOptions = {};\n\tif (isNodeArray(depsOrFn)) {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t} else if (isNodeOptions(depsOrFn)) {\n\t\topts = depsOrFn;\n\t} else {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t}\n\n\treturn new NodeImpl<T>(deps, fn, opts);\n}\n","import { type Node, type NodeFn, type NodeOptions, node } from \"./node.js\";\n\n/**\n * Creates a manual source with no upstream deps. Emit values with {@link Node.down}.\n *\n * Spec: `state(initial, opts?)` is `node([], { initial, ...opts })` (GRAPHREFLY-SPEC §2.7).\n *\n * @param initial - Initial cached value. Because `initial` is provided, `equals` is\n * called on the first {@link Node.down | down()} emission — if the value matches\n * `initial`, the node emits `RESOLVED` instead of `DATA` (spec §2.5).\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n * @returns `Node<T>` - Stateful node you drive imperatively.\n *\n * @example\n * ```ts\n * import { DATA, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(0);\n * n.down([[DATA, 1]]);\n * ```\n *\n * @category core\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n/**\n * Creates a producer node with no deps; `fn` runs when the first subscriber connects.\n *\n * @param fn - Receives deps (empty) and {@link NodeActions}; use `emit` / `down` to push.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Producer node.\n *\n * @example\n * ```ts\n * import { producer } from \"@graphrefly/graphrefly-ts\";\n *\n * const tick = producer((_d, a) => {\n * a.emit(1);\n * });\n * ```\n *\n * @category core\n */\nexport function producer<T = unknown>(fn: NodeFn<T>, opts?: NodeOptions): Node<T> {\n\treturn node<T>(fn, { describeKind: \"producer\", ...opts });\n}\n\n/**\n * Creates a derived node from dependencies and a compute function (same primitive as operators).\n *\n * @param deps - Upstream nodes.\n * @param fn - Compute function; return value is emitted, or use `actions` explicitly.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Derived node.\n *\n * @example\n * ```ts\n * import { derived, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n *\n * @category core\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: NodeFn<T>,\n\topts?: NodeOptions,\n): Node<T> {\n\treturn node<T>(deps, fn, { describeKind: \"derived\", ...opts });\n}\n\n/**\n * Runs a side-effect when deps settle; return value is not auto-emitted.\n *\n * @param deps - Nodes to watch.\n * @param fn - Side-effect body.\n * @returns `Node<unknown>` - Effect node.\n *\n * @example\n * ```ts\n * import { effect, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(1);\n * effect([n], ([v]) => {\n * console.log(v);\n * });\n * ```\n *\n * @category core\n */\nexport function effect(deps: readonly Node[], fn: NodeFn<unknown>): Node<unknown> {\n\treturn node(deps, fn, { describeKind: \"effect\" });\n}\n\n/** Unary transform used by {@link pipe} (typically returns a new node wrapping `n`). */\nexport type PipeOperator = (n: Node) => Node;\n\n/**\n * Composes unary operators left-to-right; returns the final node. Does not register a {@link Graph}.\n *\n * @param source - Starting node.\n * @param ops - Each operator maps `Node` to `Node` (curried operators from `extra` use a factory pattern — wrap or use direct calls).\n * @returns `Node` - Result of the last operator.\n *\n * @example\n * ```ts\n * import { filter, map, pipe, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state(1);\n * const out = pipe(\n * src,\n * (n) => map(n, (x) => x + 1),\n * (n) => filter(n, (x) => x > 0),\n * );\n * ```\n *\n * @category core\n */\nexport function pipe(source: Node, ...ops: PipeOperator[]): Node {\n\tlet current = source;\n\tfor (const op of ops) {\n\t\tcurrent = op(current);\n\t}\n\treturn current;\n}\n","/**\n * 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 existingEntries = eventNode.get() as readonly { seq: number }[] | undefined;\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 entries = m[1] as readonly { seq: number }[];\n\t\t\t\t\tfor (const entry of 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","/**\n * `dynamicNode` — runtime dep tracking with diamond resolution (Phase 0.3b).\n *\n * Unlike `node()` where deps are fixed at construction, `dynamicNode` discovers\n * deps at runtime via a tracking `get()` proxy. After each recompute, deps are\n * diffed: new deps are connected, removed deps are disconnected, and bitmasks\n * are rebuilt. Kept deps retain their subscriptions (no teardown/reconnect churn).\n *\n * This ports callbag-recharge's `dynamicDerived` pattern to GraphReFly's protocol.\n */\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport {\n\tnode as createNode,\n\tNO_VALUE,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeInspectorHook,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node.js\";\n\n/**\n * The tracking `get` function passed to `dynamicNode`'s compute function.\n * Each call to `get(dep)` reads the dep's current value and records it as a dependency.\n */\nexport type DynGet = <V>(dep: Node<V>) => V | undefined;\n\n/**\n * Compute function for `dynamicNode`. Receives a tracking `get` proxy.\n * Deps are discovered by which nodes are passed to `get()` during execution.\n */\nexport type DynamicNodeFn<T> = (get: DynGet) => T;\n\n/** Options for `dynamicNode`. */\nexport type DynamicNodeOptions = Pick<\n\tNodeOptions,\n\t| \"name\"\n\t| \"equals\"\n\t| \"meta\"\n\t| \"resubscribable\"\n\t| \"resetOnTeardown\"\n\t| \"guard\"\n\t| \"onMessage\"\n\t| \"onResubscribe\"\n\t| \"completeWhenDepsComplete\"\n\t| \"describeKind\"\n>;\n\n/**\n * Creates a node with runtime dep tracking. Deps are discovered each time the\n * compute function runs by tracking which nodes are passed to the `get()` proxy.\n *\n * After each recompute:\n * - New deps (not in previous set) are subscribed\n * - Removed deps (not in current set) are unsubscribed\n * - Kept deps retain their existing subscriptions\n * - Bitmasks are rebuilt to match the new dep set\n *\n * The node participates fully in diamond resolution via the standard two-phase\n * DIRTY/RESOLVED protocol across all dynamically-tracked deps.\n *\n * @param fn - Compute function receiving a tracking `get` proxy.\n * @param opts - Optional configuration.\n * @returns `Node<T>` with dynamic dep tracking.\n *\n * @example\n * ```ts\n * import { dynamicNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const cond = state(true);\n * const a = state(1);\n * const b = state(2);\n *\n * // Deps change based on cond's value\n * const d = dynamicNode((get) => {\n * const useA = get(cond);\n * return useA ? get(a) : get(b);\n * });\n * ```\n *\n * @category core\n */\nexport function dynamicNode<T = unknown>(fn: DynamicNodeFn<T>, opts?: DynamicNodeOptions): Node<T> {\n\treturn new DynamicNodeImpl<T>(fn, opts ?? {});\n}\n\n/** @internal — exported for {@link describeNode} `instanceof` check. */\nexport class DynamicNodeImpl<T = unknown> implements Node<T> {\n\tprivate readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\tprivate readonly _fn: DynamicNodeFn<T>;\n\tprivate readonly _equals: (a: unknown, b: unknown) => boolean;\n\tprivate readonly _resubscribable: boolean;\n\tprivate readonly _resetOnTeardown: boolean;\n\tprivate readonly _autoComplete: boolean;\n\tprivate readonly _onMessage: OnMessageHandler | undefined;\n\tprivate readonly _onResubscribe: (() => void) | undefined;\n\t/** @internal — read by {@link describeNode} for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\tprivate _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\n\t// Sink tracking\n\tprivate _sinkCount = 0;\n\tprivate _singleDepSinkCount = 0;\n\tprivate _singleDepSinks = new WeakSet<NodeSink>();\n\n\t// Actions object (for onMessage handler)\n\tprivate readonly _actions: NodeActions;\n\tprivate readonly _boundDownToSinks: (messages: Messages) => void;\n\n\t// Mutable state\n\tprivate _cached: T | typeof NO_VALUE = NO_VALUE;\n\tprivate _status: NodeStatus = \"disconnected\";\n\tprivate _terminal = false;\n\tprivate _connected = false;\n\tprivate _rewiring = false; // re-entrancy guard\n\n\t// Dynamic deps tracking\n\tprivate _deps: Node[] = [];\n\tprivate _depUnsubs: Array<() => void> = [];\n\tprivate _depIndexMap = new Map<Node, number>(); // node → index in _deps\n\tprivate _dirtyBits = new Set<number>();\n\tprivate _settledBits = new Set<number>();\n\tprivate _completeBits = new Set<number>();\n\n\t// Sinks\n\tprivate _sinks: NodeSink | Set<NodeSink> | null = null;\n\n\tconstructor(fn: DynamicNodeFn<T>, opts: DynamicNodeOptions) {\n\t\tthis._fn = fn;\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._resubscribable = opts.resubscribable ?? false;\n\t\tthis._resetOnTeardown = opts.resetOnTeardown ?? false;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._onResubscribe = opts.onResubscribe;\n\t\tthis._guard = opts.guard;\n\t\tthis._inspectorHook = undefined;\n\n\t\t// Build companion meta nodes (same pattern as NodeImpl)\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = createNode({\n\t\t\t\tinitial: v,\n\t\t\t\tname: `${opts.name ?? \"dynamicNode\"}:meta:${k}`,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t\t});\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions object: created once, references `this` methods.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._downAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tfor (const dep of self._deps) {\n\t\t\t\t\tdep.up?.(messages, { internal: true });\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\n\t\t// Bind commonly detached protocol methods\n\t\tthis._boundDownToSinks = this._downToSinks.bind(this);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/** @internal */\n\t_assignRegistryName(localName: string): void {\n\t\tif (this._optsName !== undefined || this._registryName !== undefined) return;\n\t\tthis._registryName = localName;\n\t}\n\n\t/**\n\t * @internal Attach/remove inspector hook for graph-level observability.\n\t * Returns a disposer that restores the previous hook.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tconst prev = this._inspectorHook;\n\t\tthis._inspectorHook = hook;\n\t\treturn () => {\n\t\t\tif (this._inspectorHook === hook) {\n\t\t\t\tthis._inspectorHook = prev;\n\t\t\t}\n\t\t};\n\t}\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\t/** Versioning not yet supported on DynamicNodeImpl. */\n\tget v(): undefined {\n\t\treturn undefined;\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\tget(): T | undefined {\n\t\treturn this._cached === NO_VALUE ? undefined : this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\tprivate _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._resubscribable) {\n\t\t\tconst pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (pass.length === 0) return;\n\t\t\tsinkMessages = pass as Messages;\n\t\t}\n\t\tthis._handleLocalLifecycle(sinkMessages);\n\t\t// Single-dep optimization: skip DIRTY to sinks when sole subscriber is single-dep\n\t\t// AND the batch contains a phase-2 message (DATA/RESOLVED). Standalone DIRTY\n\t\t// (without follow-up) must pass through so downstream is notified.\n\t\tif (this._canSkipDirty()) {\n\t\t\t// Inline check: does the batch contain DATA or RESOLVED?\n\t\t\tlet hasPhase2 = false;\n\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\tconst t = sinkMessages[i][0];\n\t\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\t\thasPhase2 = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPhase2) {\n\t\t\t\t// Inline filter: remove DIRTY messages\n\t\t\t\tconst filtered: Message[] = [];\n\t\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\t\tif (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);\n\t\t\t\t}\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tdownWithBatch(this._boundDownToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tdownWithBatch(this._boundDownToSinks, sinkMessages);\n\t}\n\n\tprivate _canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void {\n\t\tif (hints?.actor != null && this._guard != null) {\n\t\t\tconst actor = normalizeActor(hints.actor);\n\t\t\tif (!this._guard(actor, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\tif (this._terminal && this._resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._status = \"disconnected\";\n\t\t\tthis._onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\tif (!this._connected) {\n\t\t\tthis._connect();\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tif (this._singleDepSinks.has(sink)) {\n\t\t\t\tthis._singleDepSinkCount -= 1;\n\t\t\t\tthis._singleDepSinks.delete(sink);\n\t\t\t}\n\t\t\tif (this._sinks == null) return;\n\t\t\tif (typeof this._sinks === \"function\") {\n\t\t\t\tif (this._sinks === sink) this._sinks = null;\n\t\t\t} else {\n\t\t\t\tthis._sinks.delete(sink);\n\t\t\t\tif (this._sinks.size === 1) {\n\t\t\t\t\tconst [only] = this._sinks;\n\t\t\t\t\tthis._sinks = only;\n\t\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\t\tthis._sinks = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._sinks == null) {\n\t\t\t\tthis._disconnect();\n\t\t\t}\n\t\t};\n\t}\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, options);\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tthis._disconnect();\n\t}\n\n\t// --- Private methods ---\n\n\tprivate _downToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\tprivate _handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) this._cached = m[1] as T;\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t\tthis._status = \"dirty\";\n\t\t\t}\n\t\t\tif (t === DATA) {\n\t\t\t\tthis._status = \"settled\";\n\t\t\t} else if (t === RESOLVED) {\n\t\t\t\tthis._status = \"resolved\";\n\t\t\t} else if (t === DIRTY) {\n\t\t\t\tthis._status = \"dirty\";\n\t\t\t} else if (t === COMPLETE) {\n\t\t\t\tthis._status = \"completed\";\n\t\t\t\tthis._terminal = true;\n\t\t\t} else if (t === ERROR) {\n\t\t\t\tthis._status = \"errored\";\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._resetOnTeardown) this._cached = NO_VALUE;\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._disconnect();\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Propagate other meta-eligible signals (centralized in messages.ts).\n\t\t\tif (t !== TEARDOWN && propagatesToMeta(t)) {\n\t\t\t\tthis._propagateToMeta(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Propagate a signal to all companion meta nodes (best-effort). */\n\tprivate _propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\tmetaNode.down([[t]], { internal: true });\n\t\t\t} catch {\n\t\t\t\t/* best-effort: other meta nodes still receive the signal */\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _downAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tlet unchanged: boolean;\n\t\ttry {\n\t\t\tunchanged = this._cached !== NO_VALUE && this._equals(this._cached, value);\n\t\t} catch (eqErr) {\n\t\t\tconst eqMsg = eqErr instanceof Error ? eqErr.message : String(eqErr);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": equals threw: ${eqMsg}`, { cause: eqErr });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\treturn;\n\t\t}\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._cached = value as T;\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n\n\tprivate _connect(): void {\n\t\tif (this._connected) return;\n\t\tthis._connected = true;\n\t\tthis._status = \"settled\";\n\t\tthis._dirtyBits.clear();\n\t\tthis._settledBits.clear();\n\t\tthis._completeBits.clear();\n\t\tthis._runFn();\n\t}\n\n\tprivate _disconnect(): void {\n\t\tif (!this._connected) return;\n\t\tfor (const unsub of this._depUnsubs) unsub();\n\t\tthis._depUnsubs = [];\n\t\tthis._deps = [];\n\t\tthis._depIndexMap.clear();\n\t\tthis._dirtyBits.clear();\n\t\tthis._settledBits.clear();\n\t\tthis._completeBits.clear();\n\t\tthis._connected = false;\n\t\tthis._status = \"disconnected\";\n\t}\n\n\tprivate _runFn(): void {\n\t\tif (this._terminal && !this._resubscribable) return;\n\t\tif (this._rewiring) return;\n\n\t\t// Track deps during fn execution\n\t\tconst trackedDeps: Node[] = [];\n\t\tconst trackedSet = new Set<Node>();\n\n\t\tconst get: DynGet = <V>(dep: Node<V>): V | undefined => {\n\t\t\tif (!trackedSet.has(dep)) {\n\t\t\t\ttrackedSet.add(dep);\n\t\t\t\ttrackedDeps.push(dep);\n\t\t\t}\n\t\t\treturn dep.get();\n\t\t};\n\n\t\ttry {\n\t\t\t// Collect dep values for inspector hook\n\t\t\tconst depValues: unknown[] = [];\n\t\t\tfor (const dep of this._deps) {\n\t\t\t\tdepValues.push(dep.get());\n\t\t\t}\n\t\t\tthis._inspectorHook?.({ kind: \"run\", depValues });\n\n\t\t\tconst result = this._fn(get);\n\t\t\tthis._rewire(trackedDeps);\n\t\t\tif (result === undefined) return;\n\t\t\tthis._downAutoValue(result);\n\t\t} catch (err) {\n\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t}\n\t}\n\n\tprivate _rewire(newDeps: Node[]): void {\n\t\tthis._rewiring = true;\n\t\ttry {\n\t\t\tconst oldMap = this._depIndexMap;\n\t\t\tconst newMap = new Map<Node, number>();\n\t\t\tconst newUnsubs: Array<() => void> = [];\n\n\t\t\t// Reuse or create subscriptions\n\t\t\tfor (let i = 0; i < newDeps.length; i++) {\n\t\t\t\tconst dep = newDeps[i];\n\t\t\t\tnewMap.set(dep, i);\n\t\t\t\tconst oldIdx = oldMap.get(dep);\n\t\t\t\tif (oldIdx !== undefined) {\n\t\t\t\t\t// Kept dep — reuse subscription but update index\n\t\t\t\t\tnewUnsubs.push(this._depUnsubs[oldIdx]);\n\t\t\t\t\t// Mark old unsub as consumed\n\t\t\t\t\tthis._depUnsubs[oldIdx] = () => {};\n\t\t\t\t} else {\n\t\t\t\t\t// New dep — subscribe\n\t\t\t\t\tconst idx = i;\n\t\t\t\t\tconst unsub = dep.subscribe((msgs) => this._handleDepMessages(idx, msgs));\n\t\t\t\t\tnewUnsubs.push(unsub);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Disconnect removed deps\n\t\t\tfor (const [dep, oldIdx] of oldMap) {\n\t\t\t\tif (!newMap.has(dep)) {\n\t\t\t\t\tthis._depUnsubs[oldIdx]();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._deps = newDeps;\n\t\t\tthis._depUnsubs = newUnsubs;\n\t\t\tthis._depIndexMap = newMap;\n\t\t\tthis._dirtyBits.clear();\n\t\t\tthis._settledBits.clear();\n\t\t\t// Preserve complete bits for deps that are still present\n\t\t\tconst newCompleteBits = new Set<number>();\n\t\t\tfor (const oldIdx of this._completeBits) {\n\t\t\t\tconst dep = [...oldMap.entries()].find(([, idx]) => idx === oldIdx)?.[0];\n\t\t\t\tif (dep && newMap.has(dep)) {\n\t\t\t\t\tnewCompleteBits.add(newMap.get(dep)!);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._completeBits = newCompleteBits;\n\t\t} finally {\n\t\t\tthis._rewiring = false;\n\t\t}\n\t}\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\tif (this._rewiring) return; // suppress signals during rewire\n\n\t\tfor (const msg of messages) {\n\t\t\tthis._inspectorHook?.({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\t\t\t// User-defined message handler gets first look (spec §2.6).\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis._downInternal([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._dirtyBits.add(index);\n\t\t\t\tthis._settledBits.delete(index);\n\t\t\t\tif (this._dirtyBits.size === 1) {\n\t\t\t\t\t// First dirty — propagate\n\t\t\t\t\tdownWithBatch(this._boundDownToSinks, [[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tif (!this._dirtyBits.has(index)) {\n\t\t\t\t\tthis._dirtyBits.add(index);\n\t\t\t\t\tdownWithBatch(this._boundDownToSinks, [[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tthis._settledBits.add(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._dirtyBits.clear();\n\t\t\t\t\tthis._settledBits.clear();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._completeBits.add(index);\n\t\t\t\tthis._dirtyBits.delete(index);\n\t\t\t\tthis._settledBits.delete(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._dirtyBits.clear();\n\t\t\t\t\tthis._settledBits.clear();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tthis._autoComplete &&\n\t\t\t\t\tthis._completeBits.size >= this._deps.length &&\n\t\t\t\t\tthis._deps.length > 0\n\t\t\t\t) {\n\t\t\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\tprivate _allDirtySettled(): boolean {\n\t\tif (this._dirtyBits.size === 0) return false;\n\t\tfor (const idx of this._dirtyBits) {\n\t\t\tif (!this._settledBits.has(idx)) return false;\n\t\t}\n\t\treturn true;\n\t}\n}\n","import type { Actor } from \"./actor.js\";\nimport { DynamicNodeImpl } from \"./dynamic-node.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { type Node, NodeImpl } from \"./node.js\";\n\n/** JSON-shaped slice of a node for Phase 1 `Graph.describe()` (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type DescribeNodeOutput = {\n\ttype: \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\tstatus?: Node[\"status\"];\n\tdeps: string[];\n\tmeta?: Record<string, unknown>;\n\tname?: string;\n\tvalue?: unknown;\n\t/** Node versioning info (GRAPHREFLY-SPEC §7). Present only when versioning is enabled. */\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\n\t/** Guard info (full detail). */\n\tguard?: string;\n\t/** Last mutation attribution (full detail). */\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n};\n\n/**\n * Detail level for `describe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — type + deps only (default). LLM-friendly.\n * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`).\n * - `\"full\"` — standard + guard, lastMutation.\n */\nexport type DescribeDetail = \"minimal\" | \"standard\" | \"full\";\n\n/**\n * Valid field names for `describe({ fields: [...] })` (Phase 3.3b).\n * Dotted paths like `\"meta.label\"` select specific meta keys.\n */\nexport type DescribeField =\n\t| \"type\"\n\t| \"status\"\n\t| \"value\"\n\t| \"deps\"\n\t| \"meta\"\n\t| \"v\"\n\t| \"guard\"\n\t| \"lastMutation\"\n\t| `meta.${string}`;\n\n/** Resolve which fields to include based on detail level or explicit field list. */\nexport function resolveDescribeFields(\n\tdetail?: DescribeDetail,\n\tfields?: readonly DescribeField[],\n): Set<string> | null {\n\t// Explicit fields override detail level\n\tif (fields != null && fields.length > 0) return new Set(fields);\n\tswitch (detail) {\n\t\tcase \"standard\":\n\t\t\treturn new Set([\"type\", \"status\", \"value\", \"deps\", \"meta\", \"v\"]);\n\t\tcase \"full\":\n\t\t\treturn null; // null = include everything\n\t\tdefault:\n\t\t\treturn new Set([\"type\", \"deps\"]);\n\t}\n}\n\nfunction inferDescribeType(n: NodeImpl): DescribeNodeOutput[\"type\"] {\n\tif (n._describeKind != null) return n._describeKind;\n\tif (!n._hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\tif (n._fn == null) return \"derived\";\n\tif (n._manualEmitUsed) return \"operator\";\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON (GRAPHREFLY-SPEC §2.3, §3.6).\n *\n * @remarks\n * Values come from {@link Node.get}, which returns the **last settled** cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status` when\n * freshness matters. Avoid calling mid-batch for the same reason.\n *\n * Meta nodes are **not** terminated when their parent receives COMPLETE or\n * ERROR — they remain writable so callers can record post-mortem metadata\n * (e.g. `meta.error`). They *are* torn down when the parent receives TEARDOWN.\n *\n * @param node - The node whose meta fields to snapshot.\n * @returns Plain object of `{ key: value }` pairs (empty if no meta defined).\n * Keys whose companion node's {@link Node.get} throws are omitted.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = core.node({ initial: 0, meta: { tag: \"a\" } });\n * core.metaSnapshot(n); // { tag: \"a\" }\n * ```\n */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.get();\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta` snapshot).\n * Parity with graphrefly-py `describe_node`.\n *\n * `type` is inferred from factory configuration, optional `describeKind` in node options,\n * and the last `manualEmitUsed` hint (operator vs derived). {@link effect} sets\n * `describeKind: \"effect\"`. Nodes not created by {@link node} fall back to `type: \"state\"` and empty `deps`.\n *\n * @param node - Any `Node` to introspect.\n * @returns `DescribeNodeOutput` suitable for merging into graph describe maps.\n *\n * @example\n * ```ts\n * import { describeNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * describeNode(state(0));\n * ```\n */\n/**\n * Builds a single-node slice for `Graph.describe()`.\n *\n * @param node - Node to introspect.\n * @param includeFields - Set of fields to include, or `null` for all. When omitted, all fields are included (legacy behavior).\n */\nexport function describeNode(node: Node, includeFields?: Set<string> | null): DescribeNodeOutput {\n\tconst all = includeFields == null; // null or undefined → include everything\n\n\t// Specific meta keys requested via dotted paths (e.g. \"meta.label\")\n\tconst metaKeys: string[] | null =\n\t\t!all && includeFields != null\n\t\t\t? [...includeFields].filter((f) => f.startsWith(\"meta.\")).map((f) => f.slice(5))\n\t\t\t: null;\n\tconst wantsMeta = all || includeFields!.has(\"meta\") || (metaKeys != null && metaKeys.length > 0);\n\n\tlet type: DescribeNodeOutput[\"type\"] = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.name ?? \"\");\n\t} else if (node instanceof DynamicNodeImpl) {\n\t\ttype = node._describeKind ?? \"derived\";\n\t\tdeps = [];\n\t}\n\n\tconst out: DescribeNodeOutput = { type, deps };\n\n\t// status\n\tif (all || includeFields!.has(\"status\")) {\n\t\tout.status = node.status;\n\t}\n\n\t// Resolve guard once — used by both meta.access hint and standalone guard field\n\tconst guard =\n\t\t(node instanceof NodeImpl && node._guard) ||\n\t\t(node instanceof DynamicNodeImpl && node._guard) ||\n\t\tundefined;\n\n\t// meta\n\tif (wantsMeta) {\n\t\tconst rawMeta: Record<string, unknown> = { ...metaSnapshot(node) };\n\t\tif (guard != null && rawMeta.access === undefined) {\n\t\t\trawMeta.access = accessHintForGuard(guard);\n\t\t}\n\n\t\tif (metaKeys != null && metaKeys.length > 0 && !includeFields!.has(\"meta\")) {\n\t\t\t// Only specific meta keys\n\t\t\tconst filtered: Record<string, unknown> = {};\n\t\t\tfor (const k of metaKeys) {\n\t\t\t\tif (k in rawMeta) filtered[k] = rawMeta[k];\n\t\t\t}\n\t\t\tout.meta = filtered;\n\t\t} else {\n\t\t\tout.meta = rawMeta;\n\t\t}\n\t}\n\n\t// name (always include when present — it's identity, not detail)\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\t// value\n\tif (all || includeFields!.has(\"value\")) {\n\t\ttry {\n\t\t\tout.value = node.get();\n\t\t} catch {\n\t\t\t/* omit value */\n\t\t}\n\t}\n\n\t// Versioning (GRAPHREFLY-SPEC §7)\n\tif ((all || includeFields!.has(\"v\")) && node.v != null) {\n\t\tconst vInfo: DescribeNodeOutput[\"v\"] = { id: node.v.id, version: node.v.version };\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo!.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo!.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\t// Guard info (full detail)\n\tif (all || includeFields!.has(\"guard\")) {\n\t\tif (guard != null) {\n\t\t\tout.guard = accessHintForGuard(guard);\n\t\t}\n\t}\n\n\t// Last mutation attribution (full detail)\n\tif (all || includeFields!.has(\"lastMutation\")) {\n\t\tif (node.lastMutation != null) {\n\t\t\tout.lastMutation = node.lastMutation;\n\t\t}\n\t}\n\n\treturn out;\n}\n","import type { Actor } from \"../core/actor.js\";\nimport { isBatching } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { GuardDenied } from \"../core/guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport {\n\ttype DescribeDetail,\n\ttype DescribeField,\n\ttype DescribeNodeOutput,\n\tdescribeNode,\n\tresolveDescribeFields,\n} from \"../core/meta.js\";\nimport {\n\ttype Node,\n\tNodeImpl,\n\ttype NodeInspectorHookEvent,\n\ttype NodeSink,\n\ttype NodeTransportOptions,\n} from \"../core/node.js\";\nimport { state as stateNode } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\n\n/** The separator used for qualified paths in {@link Graph.resolve} et al. */\nconst PATH_SEP = \"::\";\n\n/**\n * Reserved segment for meta companion paths: `nodeName::__meta__::metaKey` (GRAPHREFLY-SPEC §3.6).\n * Forbidden as a local node or mount name.\n */\nexport const GRAPH_META_SEGMENT = \"__meta__\";\n\n/** Options for {@link Graph} (reserved for future hooks). */\nexport type GraphOptions = Record<string, unknown>;\n\n/** Filter for {@link Graph.describe} — object-style partial match or predicate. */\nexport type DescribeFilter =\n\t| Partial<Pick<DescribeNodeOutput, \"type\" | \"status\">>\n\t| {\n\t\t\ttype?: DescribeNodeOutput[\"type\"];\n\t\t\tstatus?: DescribeNodeOutput[\"status\"];\n\t\t\t/** Keep nodes whose `deps` includes this qualified path. */\n\t\t\tdepsIncludes?: string;\n\t\t\t/** Snake-case alias for `depsIncludes` (Python parity). */\n\t\t\tdeps_includes?: string;\n\t\t\t/** Keep nodes whose `meta` contains this key. */\n\t\t\tmetaHas?: string;\n\t\t\t/** Snake-case alias for `metaHas` (Python parity). */\n\t\t\tmeta_has?: string;\n\t }\n\t| ((node: DescribeNodeOutput) => boolean)\n\t| ((nodePath: string, node: DescribeNodeOutput) => boolean);\n\n/** Options for {@link Graph.signal} and {@link Graph.set} (actor context, internal lifecycle). */\nexport type GraphActorOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips node guards (graph lifecycle TEARDOWN, unmount teardown, etc.).\n\t */\n\tinternal?: boolean;\n};\n\n/** Options for {@link Graph.describe} (Phase 3.3b progressive disclosure). */\nexport type GraphDescribeOptions = {\n\tactor?: Actor;\n\t/**\n\t * Node filter. Filters operate on whatever fields the chosen `detail` level\n\t * provides. For `metaHas` and `status` filters, use `detail: \"standard\"` or\n\t * higher — at `\"minimal\"` those fields are absent and the filter silently\n\t * excludes all nodes.\n\t */\n\tfilter?: DescribeFilter;\n\t/**\n\t * Detail level (Phase 3.3b). Default: `\"minimal\"`.\n\t * - `\"minimal\"` — type + deps only\n\t * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`)\n\t * - `\"full\"` — standard + guard, lastMutation\n\t */\n\tdetail?: DescribeDetail;\n\t/**\n\t * Explicit field selection (GraphQL-style). Overrides `detail` when provided.\n\t * Dotted paths like `\"meta.label\"` select specific meta keys.\n\t */\n\tfields?: DescribeField[];\n\t/**\n\t * Output format (Phase 3.3b).\n\t * - `undefined` — normal describe output\n\t * - `\"spec\"` — GraphSpec input format (no status, no value, deps as edges, type labels)\n\t */\n\tformat?: \"spec\";\n};\n\n/** JSON snapshot from {@link Graph.describe} (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type GraphDescribeOutput = {\n\tname: string;\n\tnodes: Record<string, DescribeNodeOutput>;\n\tedges: ReadonlyArray<{ from: string; to: string }>;\n\tsubgraphs: string[];\n\t/**\n\t * Re-read the live graph with higher detail (Phase 3.3b).\n\t * Returns a new `GraphDescribeOutput`; the original remains a snapshot.\n\t * Present on live describe results; absent on deserialized snapshots.\n\t */\n\texpand?: (detailOrFields: DescribeDetail | DescribeField[]) => GraphDescribeOutput;\n};\n\n/**\n * Persisted graph snapshot: {@link GraphDescribeOutput} plus optional format version\n * ({@link Graph.snapshot}, {@link Graph.restore}, {@link Graph.fromSnapshot}, {@link Graph.toObject},\n * {@link Graph.toJSONString} — §3.8).\n */\nexport type GraphPersistSnapshot = GraphDescribeOutput & {\n\tversion?: number;\n};\n\nexport type GraphFactoryContext = {\n\tpath: string;\n\ttype: DescribeNodeOutput[\"type\"];\n\tvalue: unknown;\n\tmeta: Record<string, unknown>;\n\tdeps: readonly string[];\n\tresolvedDeps: readonly Node[];\n};\n\nexport type GraphNodeFactory = (name: string, context: GraphFactoryContext) => Node;\n\n/** @deprecated Use `CheckpointAdapter` from `extra/checkpoint` instead. */\nexport type AutoCheckpointAdapter = {\n\tsave(key: string, data: unknown): void;\n};\n\nexport type GraphCheckpointRecord =\n\t| { mode: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { mode: \"diff\"; diff: GraphDiffResult; snapshot: GraphPersistSnapshot; seq: number };\n\nexport type GraphAutoCheckpointOptions = {\n\tdebounceMs?: number;\n\tcompactEvery?: number;\n\tfilter?: (name: string, described: DescribeNodeOutput) => boolean;\n\tonError?: (error: unknown) => void;\n};\n\nexport type GraphAutoCheckpointHandle = {\n\tdispose(): void;\n};\n\n/** Direction options for diagram export helpers. */\nexport type GraphDiagramDirection = \"TD\" | \"LR\" | \"BT\" | \"RL\";\n\n/** Options for {@link Graph.toMermaid} / {@link Graph.toD2}. */\nexport type GraphDiagramOptions = {\n\t/**\n\t * Diagram flow direction.\n\t * - `TD`: top-down\n\t * - `LR`: left-right (default)\n\t * - `BT`: bottom-top\n\t * - `RL`: right-left\n\t */\n\tdirection?: GraphDiagramDirection;\n};\n\n/** Snapshot format version (§3.8). */\nconst SNAPSHOT_VERSION = 1;\n\n/**\n * Validate the snapshot envelope: version, required keys, types. Aligned with\n * Python `_parse_snapshot_envelope`. Throws on invalid data.\n */\nfunction parseSnapshotEnvelope(data: GraphPersistSnapshot): void {\n\tif (data.version !== SNAPSHOT_VERSION) {\n\t\tthrow new Error(\n\t\t\t`unsupported snapshot version ${String(data.version)} (expected ${SNAPSHOT_VERSION})`,\n\t\t);\n\t}\n\tfor (const key of [\"name\", \"nodes\", \"edges\", \"subgraphs\"] as const) {\n\t\tif (!(key in data)) {\n\t\t\tthrow new Error(`snapshot missing required key \"${key}\"`);\n\t\t}\n\t}\n\tif (typeof data.name !== \"string\") {\n\t\tthrow new TypeError(`snapshot 'name' must be a string`);\n\t}\n\tif (typeof data.nodes !== \"object\" || data.nodes === null || Array.isArray(data.nodes)) {\n\t\tthrow new TypeError(`snapshot 'nodes' must be an object`);\n\t}\n\tif (!Array.isArray(data.edges)) {\n\t\tthrow new TypeError(`snapshot 'edges' must be an array`);\n\t}\n\tif (!Array.isArray(data.subgraphs)) {\n\t\tthrow new TypeError(`snapshot 'subgraphs' must be an array`);\n\t}\n}\n\n/** Recursively sort object keys for deterministic JSON (git-diffable). */\nfunction sortJsonValue(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sortJsonValue);\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\tconst out: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tout[k] = sortJsonValue(obj[k]);\n\t}\n\treturn out;\n}\n\nfunction stableJsonStringify(value: unknown): string {\n\treturn `${JSON.stringify(sortJsonValue(value))}\\n`;\n}\n\nfunction escapeMermaidLabel(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction escapeD2Label(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction d2DirectionFromGraphDirection(direction: GraphDiagramDirection): string {\n\tif (direction === \"TD\") return \"down\";\n\tif (direction === \"BT\") return \"up\";\n\tif (direction === \"RL\") return \"left\";\n\treturn \"right\";\n}\n\n/** Collect deduplicated (from, to) arrows from deps + edges. */\nfunction collectDiagramArrows(described: GraphDescribeOutput): [string, string][] {\n\tconst seen = new Set<string>();\n\tconst arrows: [string, string][] = [];\n\tfunction add(from: string, to: string): void {\n\t\tconst key = `${from}\\0${to}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tarrows.push([from, to]);\n\t}\n\tfor (const [path, info] of Object.entries(described.nodes)) {\n\t\tconst deps: string[] | undefined = (info as Record<string, unknown>).deps as\n\t\t\t| string[]\n\t\t\t| undefined;\n\t\tif (deps) {\n\t\t\tfor (const dep of deps) add(dep, path);\n\t\t}\n\t}\n\tfor (const edge of described.edges) add(edge.from, edge.to);\n\treturn arrows;\n}\n\nfunction normalizeDiagramDirection(direction: unknown): GraphDiagramDirection {\n\tif (direction === undefined) return \"LR\";\n\tif (direction === \"TD\" || direction === \"LR\" || direction === \"BT\" || direction === \"RL\") {\n\t\treturn direction;\n\t}\n\tthrow new Error(\n\t\t`invalid diagram direction ${String(direction)}; expected one of: TD, LR, BT, RL`,\n\t);\n}\n\nfunction escapeRegexLiteral(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet re = \"^\";\n\tfor (let i = 0; i < pattern.length; i += 1) {\n\t\tconst ch = pattern[i]!;\n\t\tif (ch === \"*\") {\n\t\t\tre += \".*\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"?\") {\n\t\t\tre += \".\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tconst end = pattern.indexOf(\"]\", i + 1);\n\t\t\tif (end <= i + 1) {\n\t\t\t\tre += \"\\\\[\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet cls = pattern.slice(i + 1, end);\n\t\t\tif (cls.startsWith(\"!\")) cls = `^${cls.slice(1)}`;\n\t\t\tcls = cls.replace(/\\\\/g, \"\\\\\\\\\");\n\t\t\tre += `[${cls}]`;\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tre += escapeRegexLiteral(ch);\n\t}\n\tre += \"$\";\n\treturn new RegExp(re);\n}\n\n/** Fixed-capacity ring buffer — O(1) push and eviction. */\nclass RingBuffer<T> {\n\tprivate buf: (T | undefined)[];\n\tprivate head = 0;\n\tprivate _size = 0;\n\tconstructor(private capacity: number) {\n\t\tthis.buf = new Array(capacity);\n\t}\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\tpush(item: T): void {\n\t\tconst idx = (this.head + this._size) % this.capacity;\n\t\tthis.buf[idx] = item;\n\t\tif (this._size < this.capacity) this._size++;\n\t\telse this.head = (this.head + 1) % this.capacity;\n\t}\n\ttoArray(): T[] {\n\t\tconst result: T[] = [];\n\t\tfor (let i = 0; i < this._size; i++) result.push(this.buf[(this.head + i) % this.capacity]!);\n\t\treturn result;\n\t}\n}\n\nconst 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/** Resolve observe `detail` level into effective boolean flags. */\nfunction resolveObserveDetail(opts?: ObserveOptions): ObserveOptions {\n\tif (opts == null) return {};\n\tconst detail = opts.detail;\n\tif (detail === \"full\") {\n\t\treturn {\n\t\t\t...opts,\n\t\t\tstructured: opts.structured ?? true,\n\t\t\ttimeline: opts.timeline ?? true,\n\t\t\tcausal: opts.causal ?? true,\n\t\t\tderived: opts.derived ?? true,\n\t\t};\n\t}\n\tif (detail === \"minimal\") {\n\t\treturn { ...opts, structured: opts.structured ?? true };\n\t}\n\treturn opts;\n}\n\n/** {@link Graph.observe} on a single node or meta path — sink receives plain message batches. */\nexport type GraphObserveOne = {\n\tsubscribe(sink: NodeSink): () => void;\n\t/** Send messages upstream toward the observed node's sources (e.g. PAUSE/RESUME). */\n\tup(messages: Messages): void;\n};\n\n/**\n * {@link Graph.observe} on the whole graph — sink receives each batch with the qualified source path.\n * Subscription order follows code-point sort on paths (mounts-first walk, then sorted locals/meta).\n */\nexport type GraphObserveAll = {\n\tsubscribe(sink: (nodePath: string, messages: Messages) => void): () => void;\n\t/** Send messages upstream toward a specific observed node's sources (e.g. PAUSE/RESUME). */\n\tup(path: string, messages: Messages): void;\n};\n\n/**\n * Detail level for `observe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — DATA events only, no timestamps, no causal info.\n * - `\"standard\"` — all message types (DATA, DIRTY, RESOLVED, COMPLETE, ERROR).\n * - `\"full\"` — standard + timeline + causal + derived.\n */\nexport type ObserveDetail = \"minimal\" | \"standard\" | \"full\";\n\n/** Options for structured observation modes on {@link Graph.observe}. */\nexport type ObserveOptions = {\n\tactor?: Actor;\n\t/** Return an {@link ObserveResult} accumulator instead of a raw stream. */\n\tstructured?: boolean;\n\t/** Include causal trace info (which dep triggered each recomputation). */\n\tcausal?: boolean;\n\t/** Include timestamps and batch context on each event. */\n\ttimeline?: boolean;\n\t/** Include per-evaluation dep snapshots for compute/derived nodes. */\n\tderived?: boolean;\n\t/**\n\t * Detail level (Phase 3.3b). Individual flags (`causal`, `timeline`, `derived`)\n\t * override. `\"full\"` implies all three plus structured.\n\t * `\"minimal\"` filters to DATA-only events.\n\t */\n\tdetail?: ObserveDetail;\n};\n\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\t/**\n\t * Resubscribe with higher detail (Phase 3.3b).\n\t * Disposes current observation, returns new `ObserveResult` with merged options.\n\t */\n\texpand(\n\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t): ObserveResult<T>;\n};\n\n/** A single event in the structured observation log. */\nexport type ObserveEvent = {\n\ttype: \"data\" | \"dirty\" | \"resolved\" | \"complete\" | \"error\" | \"derived\";\n\tpath?: string;\n\tdata?: unknown;\n\ttimestamp_ns?: number;\n\tin_batch?: boolean;\n\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 readonly _disposers = new Set<() => void>();\n\tprivate _defaultVersioningLevel: VersioningLevel | undefined;\n\n\tstatic registerFactory(pattern: string, factory: GraphNodeFactory): void {\n\t\tif (!pattern) {\n\t\t\tthrow new Error(\"Graph.registerFactory requires a non-empty pattern\");\n\t\t}\n\t\tGraph.unregisterFactory(pattern);\n\t\tGraph._factories.push({ pattern, re: globToRegex(pattern), factory });\n\t}\n\n\tstatic unregisterFactory(pattern: string): void {\n\t\tconst i = Graph._factories.findIndex((entry) => entry.pattern === pattern);\n\t\tif (i >= 0) Graph._factories.splice(i, 1);\n\t}\n\n\t/**\n\t * @param name - Non-empty graph id (must not contain `::`).\n\t * @param opts - Reserved for future hooks; currently unused.\n\t */\n\tconstructor(name: string, opts?: GraphOptions) {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(\"Graph name must be non-empty\");\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\tthrow new Error(`Graph name must not contain '${PATH_SEP}' (got \"${name}\")`);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.opts = opts ?? {};\n\t}\n\n\tprivate static _factoryForPath(path: string): GraphNodeFactory | undefined {\n\t\tfor (let i = Graph._factories.length - 1; i >= 0; i -= 1) {\n\t\t\tconst entry = Graph._factories[i]!;\n\t\t\tif (entry.re.test(path)) return entry.factory;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate static _ownerForPath(root: Graph, path: string): [Graph, string] {\n\t\tconst segments = path.split(PATH_SEP);\n\t\tconst local = segments.pop();\n\t\tif (local == null || local.length === 0) {\n\t\t\tthrow new Error(`invalid snapshot path \"${path}\"`);\n\t\t}\n\t\tlet owner = root;\n\t\tfor (const seg of segments) {\n\t\t\tconst next = owner._mounts.get(seg);\n\t\t\tif (!next) throw new Error(`unknown mount \"${seg}\" in path \"${path}\"`);\n\t\t\towner = next;\n\t\t}\n\t\treturn [owner, local];\n\t}\n\n\t/**\n\t * Graphs reachable from this instance via nested {@link Graph.mount} (includes `this`).\n\t */\n\tprivate _graphsReachableViaMounts(seen = new Set<Graph>()): Set<Graph> {\n\t\tif (seen.has(this)) return seen;\n\t\tseen.add(this);\n\t\tfor (const child of this._mounts.values()) {\n\t\t\tchild._graphsReachableViaMounts(seen);\n\t\t}\n\t\treturn seen;\n\t}\n\n\t/**\n\t * Resolve an endpoint: returns `[owningGraph, localName, node]`.\n\t * Accepts both local names and `::` qualified paths.\n\t */\n\tprivate _resolveEndpoint(path: string): [Graph, string, Node] {\n\t\tif (!path.includes(PATH_SEP)) {\n\t\t\tconst n = this._nodes.get(path);\n\t\t\tif (!n) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${path}\"`);\n\t\t\t}\n\t\t\treturn [this, path, n];\n\t\t}\n\t\tconst segments = splitPath(path, this.name);\n\t\treturn this._resolveEndpointFromSegments(segments, path);\n\t}\n\n\tprivate _resolveEndpointFromSegments(\n\t\tsegments: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return [this, head, n];\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${head}\" (from path \"${fullPath}\")`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaEndpointKeys(localN, head, rest, fullPath);\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\t\treturn child._resolveEndpointFromSegments(rest, fullPath);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Node registry\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Registers a node under a local name. Fails if the name is already used,\n\t * reserved by a mount, or the same node instance is already registered.\n\t *\n\t * @param name - Local key (no `::`).\n\t * @param node - Node instance to own.\n\t */\n\tadd(name: string, node: Node): void {\n\t\tassertLocalName(name, this.name, \"add\");\n\t\tassertNoPathSep(name, this.name, \"add\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"node\");\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": name \"${name}\" is already a mount point`);\n\t\t}\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node \"${name}\" already exists`);\n\t\t}\n\t\tfor (const [existingName, existing] of this._nodes) {\n\t\t\tif (existing === node) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": node instance already registered as \"${existingName}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._nodes.set(name, node);\n\t\tif (node instanceof NodeImpl) {\n\t\t\tnode._assignRegistryName(name);\n\t\t\tif (this._defaultVersioningLevel != null) {\n\t\t\t\tnode._applyVersioning(this._defaultVersioningLevel);\n\t\t\t}\n\t\t\t// Auto-register edges from constructor deps (eliminates dual-bookkeeping).\n\t\t\t// Forward: this node's deps → already-registered nodes.\n\t\t\tif (node._deps.length > 0) {\n\t\t\t\tfor (const dep of node._deps) {\n\t\t\t\t\tfor (const [depName, depNode] of this._nodes) {\n\t\t\t\t\t\tif (depNode === dep) {\n\t\t\t\t\t\t\tthis._edges.add(edgeKey(depName, name));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Reverse: already-registered nodes that depend on this newly added node.\n\t\t\tfor (const [otherName, otherNode] of this._nodes) {\n\t\t\t\tif (otherName === name) continue;\n\t\t\t\tif (otherNode instanceof NodeImpl && otherNode._deps.includes(node)) {\n\t\t\t\t\tthis._edges.add(edgeKey(name, otherName));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Set a default versioning level for all nodes added to this graph (roadmap §6.0).\n\t *\n\t * Nodes already registered are retroactively upgraded. Nodes added later via\n\t * {@link add} will inherit this level unless they already have versioning.\n\t *\n\t * **Scope:** Does not propagate to mounted subgraphs. Call `setVersioning`\n\t * on each child graph separately if needed.\n\t *\n\t * @param level - `0` for V0, `1` for V1, or `undefined` to clear.\n\t */\n\tsetVersioning(level: VersioningLevel | undefined): void {\n\t\tthis._defaultVersioningLevel = level;\n\t\tif (level == null) return;\n\t\tfor (const n of this._nodes.values()) {\n\t\t\tif (n instanceof NodeImpl) {\n\t\t\t\tn._applyVersioning(level);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters a node or unmounts a subgraph, drops incident edges, and sends\n\t * `[[TEARDOWN]]` to the removed node or recursively through the mounted subtree (§3.2).\n\t *\n\t * @param name - Local mount or node name.\n\t */\n\tremove(name: string): void {\n\t\tassertLocalName(name, this.name, \"remove\");\n\t\tassertNoPathSep(name, this.name, \"remove\");\n\n\t\t// Case 1: unmount a subgraph\n\t\tconst child = this._mounts.get(name);\n\t\tif (child) {\n\t\t\tthis._mounts.delete(name);\n\t\t\t// Drop edges touching this mount name or qualified paths under it.\n\t\t\tconst prefix = `${name}${PATH_SEP}`;\n\t\t\tfor (const key of [...this._edges]) {\n\t\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\t\tif (from === name || to === name || from.startsWith(prefix) || to.startsWith(prefix)) {\n\t\t\t\t\tthis._edges.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tteardownMountedGraph(child);\n\t\t\treturn;\n\t\t}\n\n\t\t// Case 2: remove a local node\n\t\tconst node = this._nodes.get(name);\n\t\tif (!node) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node or mount \"${name}\"`);\n\t\t}\n\t\tthis._nodes.delete(name);\n\t\tfor (const key of [...this._edges]) {\n\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\tif (from === name || to === name) this._edges.delete(key);\n\t\t}\n\t\tnode.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n\n\t/**\n\t * Returns a node by local name or `::` qualified path.\n\t * Local names are looked up directly; paths with `::` delegate to {@link resolve}.\n\t *\n\t * @param name - Local name or qualified path.\n\t */\n\tnode(name: string): Node {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node name must be non-empty`);\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\treturn this.resolve(name);\n\t\t}\n\t\tconst n = this._nodes.get(name);\n\t\tif (!n) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${name}\"`);\n\t\t}\n\t\treturn n;\n\t}\n\n\t/**\n\t * Reads `graph.node(name).get()` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @returns Cached value or `undefined`.\n\t */\n\tget(name: string): unknown {\n\t\treturn this.node(name).get();\n\t}\n\n\t/**\n\t * Shorthand for `graph.node(name).down([[DATA, value]], { actor })` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @param value - Next `DATA` payload.\n\t * @param options - Optional `actor` and `internal` guard bypass.\n\t */\n\tset(name: string, value: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[DATA, value]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Edges\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Record a wire from `fromPath` → `toPath` (§3.3). Accepts local names or\n\t * `::` qualified paths. The target must be a {@link NodeImpl} whose `_deps`\n\t * includes the source node (same reference). Idempotent.\n\t *\n\t * Same-owner edges are stored on the owning child graph; cross-subgraph edges\n\t * are stored on this (parent) graph's registry.\n\t *\n\t * @param fromPath - Source endpoint (local or qualified).\n\t * @param toPath - Target endpoint whose deps already include the source node.\n\t */\n\tconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": connect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal, fromNode] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal, toNode] = this._resolveEndpoint(toPath);\n\n\t\tif (fromNode === toNode) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot connect a node to itself`);\n\t\t}\n\n\t\tif (!(toNode instanceof NodeImpl)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) requires the target to be a graphrefly NodeImpl so deps can be validated`,\n\t\t\t);\n\t\t}\n\t\tif (!toNode._deps.includes(fromNode)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) — target must include source in its constructor deps (same node reference)`,\n\t\t\t);\n\t\t}\n\n\t\tif (fromGraph === toGraph) {\n\t\t\t// Same-owner: store on the child graph\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tfromGraph._edges.add(key);\n\t\t} else {\n\t\t\t// Cross-subgraph: store on this (parent) graph\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tthis._edges.add(key);\n\t\t}\n\t}\n\n\t/**\n\t * Remove a registered edge (§3.3). Accepts local names or `::` qualified paths.\n\t *\n\t * **Registry-only (§C resolved):** This drops the edge from the graph's edge\n\t * registry only. It does **not** mutate the target node's constructor-time\n\t * dependency list, bitmasks, or upstream subscriptions. Message flow follows\n\t * constructor-time deps, not the edge registry. For runtime dep rewiring, use\n\t * {@link dynamicNode}.\n\t *\n\t * @param fromPath - Registered edge tail.\n\t * @param toPath - Registered edge head.\n\t */\n\tdisconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": disconnect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal] = this._resolveEndpoint(toPath);\n\n\t\tif (fromGraph === toGraph) {\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tif (!fromGraph._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tif (!this._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns registered `[from, to]` edge pairs (read-only snapshot).\n\t *\n\t * @returns Edge pairs recorded on this graph instance’s local `_edges` set.\n\t */\n\tedges(): ReadonlyArray<[string, string]> {\n\t\tconst result: [string, string][] = [];\n\t\tfor (const key of this._edges) {\n\t\t\tresult.push(parseEdgeKey(key));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Composition\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Embed a child graph at a local mount name (§3.4). Child nodes are reachable via\n\t * {@link Graph.resolve} using `::` delimited paths (§3.5). Lifecycle\n\t * {@link Graph.signal} visits mounted subgraphs recursively.\n\t *\n\t * Rejects: same name as existing node or mount, self-mount, mount cycles,\n\t * and the same child graph instance mounted twice on one parent.\n\t *\n\t * @param name - Local mount point.\n\t * @param child - Nested `Graph` instance.\n\t */\n\tmount(name: string, child: Graph): void {\n\t\tassertLocalName(name, this.name, \"mount\");\n\t\tassertNoPathSep(name, this.name, \"mount\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"mount\");\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": cannot mount at \"${name}\" — node with that name exists`,\n\t\t\t);\n\t\t}\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount \"${name}\" already exists`);\n\t\t}\n\t\tif (child === this) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot mount a graph into itself`);\n\t\t}\n\t\t// Reject same child instance mounted twice on this parent.\n\t\tfor (const existing of this._mounts.values()) {\n\t\t\tif (existing === child) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": this child graph is already mounted on this graph`);\n\t\t\t}\n\t\t}\n\t\tif (child._graphsReachableViaMounts().has(this)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount(\"${name}\", …) would create a mount cycle`);\n\t\t}\n\t\tthis._mounts.set(name, child);\n\t}\n\n\t/**\n\t * Look up a node by qualified path (§3.5). Segments are separated by `::`.\n\t *\n\t * If the first segment equals this graph's {@link Graph.name}, it is stripped\n\t * (so `root.resolve(\"app::a\")` works when `root.name === \"app\"`).\n\t *\n\t * @param path - Qualified `::` path or local name.\n\t * @returns The resolved `Node`.\n\t */\n\tresolve(path: string): Node {\n\t\tlet segments = splitPath(path, this.name);\n\t\tif (segments[0] === this.name) {\n\t\t\tsegments = segments.slice(1);\n\t\t\tif (segments.length === 0) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": resolve path ends at graph name only`);\n\t\t\t}\n\t\t}\n\t\treturn this._resolveFromSegments(segments);\n\t}\n\n\tprivate _resolveFromSegments(segments: readonly string[]): Node {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return n;\n\t\t\tif (this._mounts.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": path ends at subgraph \"${head}\" — not a node (GRAPHREFLY-SPEC §3.5)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown name \"${head}\"`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaChainFromNode(localN, rest, segments.join(PATH_SEP));\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\n\t\treturn child.resolve(rest.join(PATH_SEP));\n\t}\n\n\t/**\n\t * Resolve `::__meta__::key` segments from a registered primary node (possibly chained).\n\t */\n\tprivate _resolveMetaChainFromNode(n: Node, parts: readonly string[], fullPath: string): Node {\n\t\tlet current = n;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = p[i + 1] as string;\n\t\t\tconst next = current.meta[key];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown meta \"${key}\" in path \"${fullPath}\"`);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate _resolveMetaEndpointKeys(\n\t\tbaseNode: Node,\n\t\tbaseLocalKey: string,\n\t\tparts: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tlet current = baseNode;\n\t\tlet localKey = baseLocalKey;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst metaKey = p[i + 1] as string;\n\t\t\tconst next = current.meta[metaKey];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": unknown meta \"${metaKey}\" on node (in \"${fullPath}\")`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlocalKey = `${localKey}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${metaKey}`;\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn [this, localKey, current];\n\t}\n\n\t/**\n\t * Deliver a message batch to every registered node in this graph and, recursively,\n\t * in mounted child graphs (§3.7). Recurses into mounts first, then delivers to\n\t * local nodes (sorted by name). Each {@link Node} receives at most one delivery\n\t * per call (deduped by reference).\n\t *\n\t * Companion `meta` nodes receive the same batch for control-plane types (e.g.\n\t * PAUSE) that the primary does not forward. **TEARDOWN-only** batches skip the\n\t * extra meta pass — the primary’s `down()` already cascades TEARDOWN to meta.\n\t *\n\t * @param messages - Batch to deliver to every registered node (and mounts, recursively).\n\t * @param options - Optional `actor` / `internal` for transport.\n\t */\n\tsignal(messages: Messages, options?: GraphActorOptions): void {\n\t\tthis._signalDeliver(messages, options ?? {}, new Set());\n\t}\n\n\tprivate _signalDeliver(messages: Messages, opts: GraphActorOptions, vis: Set<Node>): void {\n\t\tfor (const sub of this._mounts.values()) {\n\t\t\tsub._signalDeliver(messages, opts, vis);\n\t\t}\n\t\tconst internal = opts.internal === true;\n\t\tconst downOpts: NodeTransportOptions = internal\n\t\t\t? { internal: true }\n\t\t\t: { actor: opts.actor, delivery: \"signal\" };\n\t\tconst metaMessages = filterMetaMessages(messages);\n\t\tfor (const localName of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(localName)!;\n\t\t\tif (vis.has(n)) continue;\n\t\t\tvis.add(n);\n\t\t\tn.down(messages, downOpts);\n\t\t\tif (metaMessages.length === 0) continue;\n\t\t\tthis._signalMetaSubtree(n, metaMessages, vis, downOpts);\n\t\t}\n\t}\n\n\tprivate _signalMetaSubtree(\n\t\troot: Node,\n\t\tmessages: Messages,\n\t\tvis: Set<Node>,\n\t\tdownOpts: NodeTransportOptions,\n\t): void {\n\t\tfor (const mk of Object.keys(root.meta).sort()) {\n\t\t\tconst mnode = root.meta[mk];\n\t\t\tif (vis.has(mnode)) continue;\n\t\t\tvis.add(mnode);\n\t\t\tmnode.down(messages, downOpts);\n\t\t\tthis._signalMetaSubtree(mnode, messages, vis, downOpts);\n\t\t}\n\t}\n\n\t/**\n\t * Static structure snapshot: qualified node keys, edges, mount names (GRAPHREFLY-SPEC §3.6, Appendix B).\n\t *\n\t * @param options - Optional `actor` for guard-scoped visibility and/or `filter` for selective output.\n\t * @returns JSON-shaped describe payload for this graph tree.\n\t *\n\t * @example\n\t * ```ts\n\t * graph.describe() // full snapshot\n\t * graph.describe({ actor: llm }) // guard-scoped\n\t * graph.describe({ filter: { status: \"errored\" } }) // only errored nodes\n\t * graph.describe({ filter: (n) => n.type === \"state\" }) // predicate filter\n\t * ```\n\t */\n\tdescribe(options?: GraphDescribeOptions): GraphDescribeOutput {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst includeFields = resolveDescribeFields(options?.detail, options?.fields);\n\t\tconst isSpec = options?.format === \"spec\";\n\t\t// For spec format, force minimal fields (type + deps only, no status/value)\n\t\tconst effectiveFields = isSpec ? resolveDescribeFields(\"minimal\") : includeFields;\n\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\tconst nodeToPath = new Map<Node, string>();\n\t\tfor (const [p, n] of targets) {\n\t\t\tnodeToPath.set(n, p);\n\t\t}\n\t\tconst nodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const [p, n] of targets) {\n\t\t\tif (actor != null && !n.allowsObserve(actor)) continue;\n\t\t\tconst raw = describeNode(n, effectiveFields);\n\t\t\tconst deps =\n\t\t\t\tn instanceof NodeImpl ? n._deps.map((d) => nodeToPath.get(d) ?? d.name ?? \"\") : [];\n\t\t\tconst { name: _name, ...rest } = raw;\n\t\t\tconst entry: DescribeNodeOutput = { ...rest, deps };\n\t\t\tif (filter != null) {\n\t\t\t\tif (typeof filter === \"function\") {\n\t\t\t\t\tconst fn = filter as\n\t\t\t\t\t\t| ((nodePath: string, node: DescribeNodeOutput) => boolean)\n\t\t\t\t\t\t| ((node: DescribeNodeOutput) => boolean);\n\t\t\t\t\tconst pass =\n\t\t\t\t\t\tfn.length >= 2\n\t\t\t\t\t\t\t? (fn as (nodePath: string, node: DescribeNodeOutput) => boolean)(p, entry)\n\t\t\t\t\t\t\t: (fn as (node: DescribeNodeOutput) => boolean)(entry);\n\t\t\t\t\tif (!pass) continue;\n\t\t\t\t} else {\n\t\t\t\t\tlet match = true;\n\t\t\t\t\tfor (const [fk, fv] of Object.entries(filter)) {\n\t\t\t\t\t\tconst normalizedKey =\n\t\t\t\t\t\t\tfk === \"deps_includes\" ? \"depsIncludes\" : fk === \"meta_has\" ? \"metaHas\" : fk;\n\t\t\t\t\t\tif (normalizedKey === \"depsIncludes\") {\n\t\t\t\t\t\t\tif (!entry.deps.includes(String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (normalizedKey === \"metaHas\") {\n\t\t\t\t\t\t\tif (!Object.hasOwn(entry.meta ?? {}, String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((entry as Record<string, unknown>)[normalizedKey] !== fv) {\n\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) continue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodes[p] = entry;\n\t\t}\n\t\tconst nodeKeys = new Set(Object.keys(nodes));\n\t\tlet edges = this._collectAllEdges(\"\");\n\t\tif (actor != null || filter != null) {\n\t\t\tedges = edges.filter((e) => nodeKeys.has(e.from) && nodeKeys.has(e.to));\n\t\t}\n\t\tedges.sort((a, b) => {\n\t\t\tif (a.from < b.from) return -1;\n\t\t\tif (a.from > b.from) return 1;\n\t\t\tif (a.to < b.to) return -1;\n\t\t\tif (a.to > b.to) return 1;\n\t\t\treturn 0;\n\t\t});\n\t\tconst allSubgraphs = this._collectSubgraphs(\"\");\n\t\tconst subgraphs =\n\t\t\tactor != null || filter != null\n\t\t\t\t? allSubgraphs.filter((sg) => {\n\t\t\t\t\t\tconst prefix = `${sg}${PATH_SEP}`;\n\t\t\t\t\t\treturn [...nodeKeys].some((k) => k === sg || k.startsWith(prefix));\n\t\t\t\t\t})\n\t\t\t\t: allSubgraphs;\n\n\t\t// Capture graph ref and base options for expand()\n\t\tconst graph = this;\n\t\tconst baseOpts = options;\n\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t\texpand(detailOrFields: DescribeDetail | DescribeField[]): GraphDescribeOutput {\n\t\t\t\tconst merged: GraphDescribeOptions = { ...baseOpts, format: undefined };\n\t\t\t\tif (Array.isArray(detailOrFields)) {\n\t\t\t\t\tmerged.fields = detailOrFields;\n\t\t\t\t\tmerged.detail = undefined;\n\t\t\t\t} else {\n\t\t\t\t\tmerged.detail = detailOrFields;\n\t\t\t\t\tmerged.fields = undefined;\n\t\t\t\t}\n\t\t\t\treturn graph.describe(merged);\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _collectSubgraphs(prefix: string): string[] {\n\t\tconst out: string[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst q = prefix === \"\" ? m : `${prefix}${m}`;\n\t\t\tout.push(q);\n\t\t\tout.push(...this._mounts.get(m)!._collectSubgraphs(`${q}${PATH_SEP}`));\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _collectAllEdges(prefix: string): { from: string; to: string }[] {\n\t\tconst out: { from: string; to: string }[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tout.push(...this._mounts.get(m)!._collectAllEdges(p2));\n\t\t}\n\t\tfor (const [f, t] of this.edges()) {\n\t\t\tout.push({\n\t\t\t\tfrom: this._qualifyEdgeEndpoint(f, prefix),\n\t\t\t\tto: this._qualifyEdgeEndpoint(t, prefix),\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\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 resolved = resolveObserveDetail(options);\n\t\t\tconst actor = resolved.actor;\n\t\t\tconst target = this.resolve(path);\n\t\t\tif (actor != null && !target.allowsObserve(actor)) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: path });\n\t\t\t}\n\t\t\tconst wantsStructured =\n\t\t\t\tresolved.structured === true ||\n\t\t\t\tresolved.timeline === true ||\n\t\t\t\tresolved.causal === true ||\n\t\t\t\tresolved.derived === true ||\n\t\t\t\tresolved.detail === \"minimal\" ||\n\t\t\t\tresolved.detail === \"full\";\n\t\t\tif (wantsStructured && Graph.inspectorEnabled) {\n\t\t\t\treturn this._createObserveResult(path, target, resolved);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsubscribe(sink: NodeSink) {\n\t\t\t\t\treturn target.subscribe(sink);\n\t\t\t\t},\n\t\t\t\tup(messages: Messages) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttarget.up?.(messages);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst opts = resolveObserveDetail(pathOrOpts as ObserveOptions | undefined);\n\t\tconst actor = opts.actor;\n\t\tconst wantsStructured =\n\t\t\topts.structured === true ||\n\t\t\topts.timeline === true ||\n\t\t\topts.causal === true ||\n\t\t\topts.derived === true ||\n\t\t\topts.detail === \"minimal\" ||\n\t\t\topts.detail === \"full\";\n\t\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 minimal = options.detail === \"minimal\";\n\t\tconst result: {\n\t\t\tvalues: Record<string, T>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\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 (minimal) {\n\t\t\t\t\t// minimal: track state but don't push non-DATA events\n\t\t\t\t\tif (t === DIRTY) result.dirtyCount++;\n\t\t\t\t\telse if (t === RESOLVED) result.resolvedCount++;\n\t\t\t\t\telse if (t === COMPLETE && !result.errored) result.completedCleanly = true;\n\t\t\t\t\telse if (t === ERROR) result.errored = true;\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base, ...withCausal });\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!result.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\tconst graph = this;\n\t\tconst basePath = path;\n\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget 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\texpand(\n\t\t\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t\t\t): ObserveResult<T> {\n\t\t\t\tunsub();\n\t\t\t\tdetachInspectorHook?.();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\tconst resolvedTarget = graph.resolve(basePath);\n\t\t\t\treturn graph._createObserveResult<T>(\n\t\t\t\t\tbasePath,\n\t\t\t\t\tresolvedTarget as Node<T>,\n\t\t\t\t\tresolveObserveDetail(merged),\n\t\t\t\t);\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResultForAll(options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline === true;\n\t\tconst minimal = options.detail === \"minimal\";\n\t\tconst result: {\n\t\t\tvalues: Record<string, unknown>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\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 (minimal) {\n\t\t\t\t\t\tif (t === DIRTY) result.dirtyCount++;\n\t\t\t\t\t\telse if (t === RESOLVED) result.resolvedCount++;\n\t\t\t\t\t\telse if (t === COMPLETE && !result.errored) result.completedCleanly = true;\n\t\t\t\t\t\telse if (t === ERROR) result.errored = true;\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\n\t\tconst graph = this;\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget 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\texpand(\n\t\t\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t\t\t): ObserveResult {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\treturn graph._createObserveResultForAll(resolveObserveDetail(merged));\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\texpand() {\n\t\t\t\t\tthrow new Error(\"expand() requires inspector mode (Graph.inspectorEnabled = true)\");\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 { expand: _, ...described } = this.describe({\n\t\t\tactor: options.actor,\n\t\t\tfilter: options.filter,\n\t\t\tdetail: \"standard\",\n\t\t});\n\t\tconst includeEdges = options.includeEdges ?? true;\n\t\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\t\tif (options.format === \"json\") {\n\t\t\tconst payload: GraphDescribeOutput = {\n\t\t\t\t...described,\n\t\t\t\tedges: includeEdges ? described.edges : [],\n\t\t\t\tsubgraphs: includeSubgraphs ? described.subgraphs : [],\n\t\t\t};\n\t\t\tconst text = JSON.stringify(sortJsonValue(payload), null, options.indent ?? 2);\n\t\t\toptions.logger?.(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tconst lines: string[] = [];\n\t\tlines.push(`Graph ${described.name}`);\n\t\tlines.push(\"Nodes:\");\n\t\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\t\tconst n = described.nodes[path]!;\n\t\t\tlines.push(`- ${path} (${n.type}/${n.status}): ${describeData(n.value)}`);\n\t\t}\n\t\tif (includeEdges) {\n\t\t\tlines.push(\"Edges:\");\n\t\t\tfor (const edge of described.edges) {\n\t\t\t\tlines.push(`- ${edge.from} -> ${edge.to}`);\n\t\t\t}\n\t\t}\n\t\tif (includeSubgraphs) {\n\t\t\tlines.push(\"Subgraphs:\");\n\t\t\tfor (const sg of described.subgraphs) {\n\t\t\t\tlines.push(`- ${sg}`);\n\t\t\t}\n\t\t}\n\t\tconst text = lines.join(\"\\n\");\n\t\toptions.logger?.(text);\n\t\treturn text;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Lifecycle & persistence (§3.7–§3.8)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Register a cleanup function to be called on {@link Graph.destroy}.\n\t *\n\t * Factories use this to attach teardown logic for internal nodes, keepalive\n\t * subscriptions, or other resources that are not registered on the graph and\n\t * would otherwise leak on repeated create/destroy cycles.\n\t *\n\t * Returns a removal function — call it to unregister the disposer early.\n\t */\n\taddDisposer(fn: () => void): () => void {\n\t\tthis._disposers.add(fn);\n\t\treturn () => {\n\t\t\tthis._disposers.delete(fn);\n\t\t};\n\t}\n\n\t/**\n\t * Drains disposers (registered via {@link addDisposer}), then sends `[[TEARDOWN]]` to all\n\t * nodes and clears registries on this graph and every mounted subgraph (§3.7).\n\t * The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\t// Drain disposers (keepalive unsubs etc.) BEFORE TEARDOWN so that\n\t\t// internal effect nodes are disconnected before the cascade fires.\n\t\tfor (const dispose of [...this._disposers]) {\n\t\t\ttry {\n\t\t\t\tdispose();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t\tthis._disposers.clear();\n\t\tthis.signal([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tfor (const dispose of [...this._autoCheckpointDisposers]) {\n\t\t\ttry {\n\t\t\t\tdispose();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t\tthis._autoCheckpointDisposers.clear();\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/** Clear structure after parent already signaled TEARDOWN through this subtree. */\n\tprivate _destroyClearOnly(): void {\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/**\n\t * Serializes structure and current values to JSON-shaped data (§3.8). Same information\n\t * as {@link Graph.describe} plus a `version` field for format evolution.\n\t *\n\t * @returns Persistable snapshot with sorted keys.\n\t */\n\tsnapshot(): GraphPersistSnapshot {\n\t\tconst { expand: _, ...d } = this.describe({ detail: \"full\" });\n\t\t// Explicit key sorting for deterministic output — don't rely on\n\t\t// describe() iteration order (audit batch-3, §3.8).\n\t\t// Strip non-restorable fields (runtime attribution) so snapshot → restore → snapshot\n\t\t// is idempotent. Use describe({ detail: \"full\" }) for audit snapshots instead.\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = d.nodes[key]!;\n\t\t\tsortedNodes[key] = node;\n\t\t}\n\t\tconst sortedSubgraphs = [...d.subgraphs].sort();\n\t\treturn { ...d, version: 1, nodes: sortedNodes, subgraphs: sortedSubgraphs };\n\t}\n\n\t/**\n\t * Apply persisted values onto an existing graph whose topology matches the snapshot\n\t * (§3.8). Only {@link DescribeNodeOutput.type} `state` and `producer` entries with a\n\t * `value` field are written; `derived` / `operator` / `effect` are skipped so deps\n\t * drive recomputation. Unknown paths are ignored.\n\t *\n\t * @param data - Snapshot envelope with matching `name` and node slices.\n\t * @throws If `data.name` does not equal {@link Graph.name}.\n\t */\n\trestore(data: GraphPersistSnapshot, options?: { only?: string | readonly string[] }): void {\n\t\tparseSnapshotEnvelope(data);\n\t\tif (data.name !== this.name) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": restore snapshot name \"${data.name}\" does not match this graph`,\n\t\t\t);\n\t\t}\n\t\tconst onlyPatterns =\n\t\t\toptions?.only == null\n\t\t\t\t? null\n\t\t\t\t: (Array.isArray(options.only) ? options.only : [options.only]).map((p) => globToRegex(p));\n\t\tfor (const path of Object.keys(data.nodes).sort()) {\n\t\t\tif (onlyPatterns !== null && !onlyPatterns.some((re) => re.test(path))) continue;\n\t\t\tconst slice = data.nodes[path];\n\t\t\tif (slice === undefined || slice.value === undefined) continue;\n\t\t\tif (slice.type === \"derived\" || slice.type === \"operator\" || slice.type === \"effect\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.set(path, slice.value);\n\t\t\t} catch {\n\t\t\t\t/* missing path or set not applicable */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a graph named from the snapshot, optionally runs `build` to register nodes\n\t * and mounts, then {@link Graph.restore} values (§3.8).\n\t *\n\t * @param data - Snapshot envelope (`version` checked).\n\t * @param build - Optional callback to construct topology before values are applied.\n\t * @returns Hydrated `Graph` instance.\n\t */\n\tstatic fromSnapshot(data: GraphPersistSnapshot, build?: (g: Graph) => void): Graph {\n\t\tparseSnapshotEnvelope(data);\n\t\tconst g = new Graph(data.name);\n\t\tif (build) {\n\t\t\tbuild(g);\n\t\t\tg.restore(data);\n\t\t\treturn g;\n\t\t}\n\t\t// Auto-create mount hierarchy from subgraphs.\n\t\tfor (const mount of [...data.subgraphs].sort((a, b) => {\n\t\t\tconst da = a.split(PATH_SEP).length;\n\t\t\tconst db = b.split(PATH_SEP).length;\n\t\t\tif (da !== db) return da - db;\n\t\t\tif (a < b) return -1;\n\t\t\tif (a > b) return 1;\n\t\t\treturn 0;\n\t\t})) {\n\t\t\tconst parts = mount.split(PATH_SEP);\n\t\t\tlet target: Graph = g;\n\t\t\tfor (const seg of parts) {\n\t\t\t\tif (!target._mounts.has(seg)) {\n\t\t\t\t\ttarget.mount(seg, new Graph(seg));\n\t\t\t\t}\n\t\t\t\ttarget = target._mounts.get(seg)!;\n\t\t\t}\n\t\t}\n\n\t\tconst primaryEntries = Object.entries(data.nodes)\n\t\t\t.filter(([path]) => !path.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`))\n\t\t\t.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst pending = new Map(primaryEntries);\n\t\tconst created = new Map<string, Node>();\n\n\t\tlet progressed = true;\n\t\twhile (pending.size > 0 && progressed) {\n\t\t\tprogressed = false;\n\t\t\tfor (const [path, slice] of [...pending.entries()]) {\n\t\t\t\tconst deps = slice?.deps ?? [];\n\t\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\t\t\t\tconst [owner, localName] = Graph._ownerForPath(g, path);\n\t\t\t\tconst meta: Record<string, unknown> = { ...(slice?.meta ?? {}) };\n\t\t\t\tconst factory = Graph._factoryForPath(path);\n\t\t\t\tlet node: Node;\n\t\t\t\tif (slice?.type === \"state\") {\n\t\t\t\t\tnode = stateNode(slice.value, { meta });\n\t\t\t\t} else {\n\t\t\t\t\tif (factory == null) continue;\n\t\t\t\t\tnode = factory(localName, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\ttype: slice.type,\n\t\t\t\t\t\tvalue: slice.value,\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tresolvedDeps: deps.map((dep) => created.get(dep)!),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\towner.add(localName, node);\n\t\t\t\tcreated.set(path, node);\n\t\t\t\tpending.delete(path);\n\t\t\t\tprogressed = true;\n\t\t\t}\n\t\t}\n\t\tif (pending.size > 0) {\n\t\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`Graph.fromSnapshot could not reconstruct nodes without build callback: ${unresolved}. ` +\n\t\t\t\t\t`Register matching factories with Graph.registerFactory(pattern, factory).`,\n\t\t\t);\n\t\t}\n\t\tfor (const edge of data.edges) {\n\t\t\ttry {\n\t\t\t\tg.connect(edge.from, edge.to);\n\t\t\t} catch {\n\t\t\t\t/* ignore malformed or non-reconstructable edge */\n\t\t\t}\n\t\t}\n\t\tg.restore(data);\n\t\treturn g;\n\t}\n\n\t/**\n\t * Plain snapshot object with **recursively sorted object keys** for deterministic serialization (§3.8).\n\t *\n\t * @remarks\n\t * For a single UTF-8 string with a trailing newline (convenient for git), use {@link Graph.toJSONString}.\n\t *\n\t * @returns Same object as {@link Graph.snapshot}.\n\t */\n\ttoObject(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * ECMAScript `JSON.stringify` hook — delegates to {@link Graph.toObject}.\n\t *\n\t * @remarks\n\t * Must return a plain object (not a string) so `JSON.stringify(graph)` works correctly\n\t * without double-encoding.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.toObject();\n\t}\n\n\t/**\n\t * Deterministic JSON **text**: `JSON.stringify` of {@link Graph.toObject} plus a trailing newline (§3.8).\n\t *\n\t * @returns Stable string suitable for diffs.\n\t */\n\ttoJSONString(): string {\n\t\treturn stableJsonStringify(this.snapshot());\n\t}\n\n\t/**\n\t * Debounced persistence wired to graph-wide observe stream (spec §3.8 auto-checkpoint).\n\t *\n\t * Checkpoint trigger uses {@link messageTier}: only batches containing tier >= 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 { expand: _expand, ...raw } = this.describe({ detail: \"full\" });\n\t\t\t\t// Strip non-restorable fields for persistence idempotency\n\t\t\t\tconst cleanNodes: Record<string, DescribeNodeOutput> = {};\n\t\t\t\tfor (const [p, n] of Object.entries(raw.nodes)) {\n\t\t\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = n!;\n\t\t\t\t\tcleanNodes[p] = node;\n\t\t\t\t}\n\t\t\t\tconst described = { ...raw, nodes: cleanNodes };\n\t\t\t\tconst snapshot = { ...described, version: SNAPSHOT_VERSION };\n\t\t\t\tseq += 1;\n\t\t\t\tconst shouldCompact = lastDescribe == null || seq % compactEvery === 0;\n\t\t\t\tif (shouldCompact) {\n\t\t\t\t\tadapter.save(this.name, { mode: \"full\", snapshot, seq } satisfies GraphCheckpointRecord);\n\t\t\t\t} else {\n\t\t\t\t\tconst previous = lastDescribe;\n\t\t\t\t\tif (previous == null) return;\n\t\t\t\t\tadapter.save(this.name, {\n\t\t\t\t\t\tmode: \"diff\",\n\t\t\t\t\t\tdiff: Graph.diff(previous, described),\n\t\t\t\t\t\tsnapshot,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t} satisfies GraphCheckpointRecord);\n\t\t\t\t}\n\t\t\t\tlastDescribe = described;\n\t\t\t} catch (error) {\n\t\t\t\toptions.onError?.(error);\n\t\t\t}\n\t\t};\n\n\t\tconst schedule = () => {\n\t\t\tpending = true;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = setTimeout(flush, debounceMs);\n\t\t};\n\n\t\tconst off = this.observe().subscribe((path, messages) => {\n\t\t\tconst triggeredByTier = messages.some((m) => messageTier(m[0]) >= 2);\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst nd = this.resolve(path);\n\t\t\t\tif (nd == null) return;\n\t\t\t\tconst described = describeNode(nd, resolveDescribeFields(\"standard\"));\n\t\t\t\tif (!options.filter(path, described)) return;\n\t\t\t}\n\t\t\tschedule();\n\t\t});\n\n\t\tconst dispose = () => {\n\t\t\toff();\n\t\t\tif (timer !== undefined) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = undefined;\n\t\t\t}\n\t\t\tthis._autoCheckpointDisposers.delete(dispose);\n\t\t};\n\t\tthis._autoCheckpointDisposers.add(dispose);\n\t\treturn { dispose };\n\t}\n\n\t/**\n\t * Export the current graph topology as Mermaid flowchart text.\n\t *\n\t * Renders qualified node paths and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns Mermaid flowchart source.\n\t */\n\ttoMermaid(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`flowchart ${direction}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(` ${id}[\"${escapeMermaidLabel(path)}\"]`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(` ${fromId} --> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t/**\n\t * Export the current graph topology as D2 diagram text.\n\t *\n\t * Renders qualified node paths, constructor deps, and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns D2 source text.\n\t */\n\ttoD2(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`direction: ${d2DirectionFromGraphDirection(direction)}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(`${id}: \"${escapeD2Label(path)}\"`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(`${fromId} -> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Inspector (roadmap 3.3) — reasoning trace, overhead gating\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * When `false`, structured observation options (`causal`, `timeline`),\n\t * `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 * Reactive append-only log (roadmap §3.2) — emits `readonly T[]` snapshots directly.\n *\n * Internal version counter drives efficient equality without leaking `Versioned`\n * into the public API (spec §5.12).\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\";\n\nexport type ReactiveLogOptions = {\n\tname?: string;\n\tmaxSize?: number;\n};\n\nexport type ReactiveLogBundle<T> = {\n\t/** Emits `readonly T[]` on each append/clear (two-phase). */\n\treadonly entries: Node<readonly 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\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 immutable array 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\n\tconst entries = state<readonly T[]>(buf.length > 0 ? [...buf] : [], {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: (a, b) => a === b,\n\t});\n\n\tfunction pushSnapshot(): void {\n\t\tconst snapshot: readonly T[] = [...buf];\n\t\tbatch(() => {\n\t\t\tentries.down([[DIRTY]]);\n\t\t\tentries.down([[DATA, snapshot]]);\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 e = entries.get() as readonly T[];\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 readonly T[];\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 e = log.entries.get() as readonly T[];\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 readonly T[];\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 * 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 { 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<readonly 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<readonly 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<readonly CqrsEvent[]>(\n\t\t\t[entries],\n\t\t\t([snapshot]) => snapshot as readonly 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 readonly 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 entries = snapshot as readonly CqrsEvent[];\n\t\t\t\t\tallEvents.push(...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 entries = snapshots[i] as readonly CqrsEvent<T>[];\n\t\t\t\t\tconst eName = eventNames[i];\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"],"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;;;ACcA,kBAA2B;;;ACoBpB,IAAM,OAAO,uBAAO,IAAI,iBAAiB;AAEzC,IAAM,QAAQ,uBAAO,IAAI,kBAAkB;AAE3C,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAEjD,IAAM,aAAa,uBAAO,IAAI,uBAAuB;AAErD,IAAM,QAAQ,uBAAO,IAAI,kBAAkB;AAE3C,IAAM,SAAS,uBAAO,IAAI,mBAAmB;AAE7C,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAEjD,IAAM,WAAW,uBAAO,IAAI,qBAAqB;AAEjD,IAAM,QAAQ,uBAAO,IAAI,kBAAkB;AAgE3C,SAAS,YAAY,GAAmB;AAC9C,MAAI,MAAM,SAAS,MAAM,WAAY,QAAO;AAC5C,MAAI,MAAM,SAAS,MAAM,OAAQ,QAAO;AACxC,MAAI,MAAM,QAAQ,MAAM,SAAU,QAAO;AACzC,MAAI,MAAM,YAAY,MAAM,MAAO,QAAO;AAC1C,MAAI,MAAM,SAAU,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AAK,KAAK,MAAM,KAAK,IAAI;AAGnC,cAAI,KAAK,WAAY,GAAE,cAAc,KAAK,UAAU;AACpD,cAAI,KAAK,MAAO,MAAK,MAAM,CAAC;AAC5B,oBAAU,MAAM,KAAK,MAAM,CAAC;AAC5B,iBAAO;AAAA,QACR;AAAA,QACA,QAAQ,CAAC,qBAAqB;AAAA,MAC/B;AAAA,IACD;AAEA,QAAI,KAAK,OAAO;AACf,iBAAW,QAAQ,KAAK,OAAO;AAC9B,kBAAU,KAAK;AAAA,UACd,SAAS,aAAa,GAAG,KAAK,IAAI,KAAK,IAAI,EAAE;AAAA,UAC7C,YAAY,CAAC,UAAiB,MAAM,QAAQ,IAAI;AAAA,UAChD,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC;AAAA,QAClC,CAAC;AAAA,MACF;AAAA,IACD;AAEA,WAAO;AAAA,MACN,QAAQ;AAAA,MACR;AAAA,MACA,SAAS;AAAA,QACR,cAAc,KAAK,IAAI;AAAA,QACvB,IAAI,KAAK,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,aAAa,GAAG,KAAK,IAAI,KAAK,CAAC,EAAE,CAAC;AAAA,MACpE;AAAA,IACD;AAAA,EACD;AACD;AA7LO;AAAM,oBAAN,gDAFP,8BAEa;AAAN,4BAAM;AAAN,IAAM,mBAAN;","names":["node","import_common","import_core","node","node","actor","wantsStructured","derived","stop","result","stream","text","edgeKey"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/compat/nestjs/index.ts","../../../src/extra/observable.ts","../../../src/core/messages.ts","../../../src/compat/nestjs/decorators.ts","../../../src/compat/nestjs/tokens.ts","../../../src/extra/sources.ts","../../../src/core/clock.ts","../../../src/core/actor.ts","../../../src/core/guard.ts","../../../src/core/batch.ts","../../../src/core/versioning.ts","../../../src/core/node-base.ts","../../../src/core/node.ts","../../../src/core/sugar.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/dynamic-node.ts","../../../src/core/meta.ts","../../../src/graph/sizeof.ts","../../../src/graph/profile.ts","../../../src/graph/graph.ts","../../../src/extra/reactive-log.ts","../../../src/patterns/cqrs.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\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 { type ToObservableOptions, 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// Usage:\n// import { toObservable } from '@graphrefly/graphrefly-ts/extra';\n// const values$ = toObservable(myNode); // Observable<T>\n// const msgs$ = toObservable(myNode, { raw: true }); // Observable<Messages>\n// ---------------------------------------------------------------------------\n\nimport { Observable } from \"rxjs\";\nimport { COMPLETE, DATA, ERROR, type Messages } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\n\n/** Options for {@link toObservable}. */\nexport type ToObservableOptions = {\n\t/**\n\t * When `true`, emit raw `Messages` batches instead of extracted `DATA` values.\n\t * Terminal batches are still emitted as the final `next()` before the\n\t * Observable signal (error/complete).\n\t */\n\traw?: boolean;\n};\n\n/**\n * Bridge a `Node<T>` to an RxJS `Observable`.\n *\n * Default mode 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 * With `{ raw: true }`, emits full `[[Type, Data?], ...]` message batches.\n * The Observable terminates on ERROR or COMPLETE (the terminal batch is still\n * emitted as the final `next()` before the Observable signal).\n *\n * For graph-level observation, use `toObservable(graph.resolve(path))` or\n * subscribe to `graph.observe()` directly.\n *\n * Unsubscribing the Observable unsubscribes the node.\n */\nexport function toObservable<T>(\n\tnode: Node<T>,\n\toptions?: ToObservableOptions & { raw?: false },\n): Observable<T>;\nexport function toObservable<T>(\n\tnode: Node<T>,\n\toptions: ToObservableOptions & { raw: true },\n): Observable<Messages>;\nexport function toObservable<T>(\n\tnode: Node<T>,\n\toptions?: ToObservableOptions,\n): Observable<T | Messages> {\n\tif (options?.raw) {\n\t\treturn new Observable<Messages>((subscriber) => {\n\t\t\tconst unsub = node.subscribe((msgs) => {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tsubscriber.next(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\tsubscriber.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) {\n\t\t\t\t\t\tsubscriber.complete();\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\treturn unsub;\n\t\t});\n\t}\n\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 * GraphReFly message protocol — §1 `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n * Emissions are always `[[Type, Data?], ...]` (no single-tuple shorthand).\n *\n * ## Canonical message ordering (within a composite batch)\n *\n * When multiple message types appear in a single `down()` call, the canonical\n * delivery order is determined by **signal tier**:\n *\n * | Tier | Signals | Role | Batch behavior |\n * |------|------------------------|-------------------|-------------------------------------|\n * | 0 | START | Subscribe handshake | Immediate (never deferred) |\n * | 1 | DIRTY, INVALIDATE | Notification | Immediate (never deferred) |\n * | 2 | PAUSE, RESUME | Flow control | Immediate (never deferred) |\n * | 3 | DATA, RESOLVED | Value settlement | Deferred inside `batch()` |\n * | 4 | COMPLETE, ERROR | Terminal lifecycle | Deferred to after phase-2 |\n * | 5 | TEARDOWN | Destruction | Immediate (usually sent alone) |\n *\n * **Rule:** Within `downWithBatch`, messages are partitioned by tier and delivered\n * in tier order. This ensures phase-2 values (DATA/RESOLVED) reach sinks before\n * terminal signals (COMPLETE/ERROR) mark the node as done, preventing the\n * \"COMPLETE-before-DATA\" class of bugs. Sources that emit in canonical order\n * naturally partition correctly with zero overhead.\n *\n * Unknown message types (forward-compat) are tier 1 (immediate).\n *\n * ## Meta node bypass rules (centralized — GRAPHREFLY-SPEC §2.3)\n *\n * - **INVALIDATE** via `graph.signal()` — no-op on meta nodes (cached values preserved).\n * - **COMPLETE / ERROR** — not propagated from parent to meta (meta outlives terminal\n * state for post-mortem writes like setting `meta.error` after ERROR).\n * - **TEARDOWN** — propagated from parent to meta, releasing meta resources.\n */\n\n/**\n * Subscribe-time handshake (`START`). Delivered to each new sink at the top of\n * `subscribe()` — `[[START]]` for a SENTINEL (no cached value) node or\n * `[[START], [DATA, cached]]` for a node with a cached value.\n *\n * Semantics: \"upstream connected and ready to flow.\" A new sink receiving\n * `[[START]]` alone knows the upstream is alive but has no current value; a\n * sink receiving `[[START], [DATA, v]]` knows the upstream is ready\n * with value `v`. Absence of `START` before any other message means the\n * subscription was either never established or the node is terminal.\n *\n * Tier 0 — immediate, delivered before any DIRTY/DATA in the same batch.\n * Not forwarded through nodes — each node emits its own `START` to its own\n * new sinks.\n */\nexport const START = Symbol.for(\"graphrefly/START\");\n/** Value delivery (`DATA`, value). Tier 3 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 1 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 3 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 1 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 2 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 2 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 5 — immediate (usually sent alone). */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 4 — delivered after phase-2 in the same batch. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 4 — delivered after phase-2 in the same batch. */\nexport const ERROR = Symbol.for(\"graphrefly/ERROR\");\n\n/** Known protocol type symbols (open set — other symbols are valid and forward). */\nexport const knownMessageTypes: readonly symbol[] = [\n\tSTART,\n\tDATA,\n\tDIRTY,\n\tRESOLVED,\n\tINVALIDATE,\n\tPAUSE,\n\tRESUME,\n\tTEARDOWN,\n\tCOMPLETE,\n\tERROR,\n];\n\n/** O(1) lookup for {@link isKnownMessageType} and {@link isLocalOnly}. */\nconst knownMessageSet: ReadonlySet<symbol> = new Set(knownMessageTypes);\n\n/** One protocol tuple: `[Type, optional payload]`. */\nexport type Message = readonly [symbol, unknown?];\n\n/**\n * A batch of tuples — the wire shape for `node.down()` / `node.up()`.\n */\nexport type Messages = readonly Message[];\n\n/**\n * Whether `t` is one of the built-in protocol symbols in this module.\n *\n * @param t — Message type symbol (unknown types are still valid; they must forward).\n * @returns `true` for `DATA`, `DIRTY`, `RESOLVED`, etc.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, isKnownMessageType } from \"@graphrefly/graphrefly-ts\";\n *\n * isKnownMessageType(DATA); // true\n * isKnownMessageType(Symbol(\"custom\")); // false\n * ```\n */\nexport function isKnownMessageType(t: symbol): boolean {\n\treturn knownMessageSet.has(t);\n}\n\n/**\n * Returns the signal tier for a message type (see module-level ordering table).\n *\n * - 0: subscribe handshake (START) — immediate, first in canonical order\n * - 1: notification (DIRTY, INVALIDATE) — immediate\n * - 2: flow control (PAUSE, RESUME) — immediate\n * - 3: value (DATA, RESOLVED) — deferred inside `batch()`\n * - 4: terminal (COMPLETE, ERROR) — delivered after phase-3\n * - 5: destruction (TEARDOWN) — immediate, usually alone\n * - 1 for unknown types (forward-compat: immediate)\n *\n * @param t — Message type symbol.\n * @returns Tier number (0–5).\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, TEARDOWN, messageTier, START } from \"@graphrefly/graphrefly-ts\";\n *\n * messageTier(START); // 0\n * messageTier(DIRTY); // 1\n * messageTier(DATA); // 3\n * messageTier(COMPLETE); // 4\n * messageTier(TEARDOWN); // 5\n * ```\n */\nexport function messageTier(t: symbol): number {\n\tif (t === START) return 0;\n\tif (t === DIRTY || t === INVALIDATE) return 1;\n\tif (t === PAUSE || t === RESUME) return 2;\n\tif (t === DATA || t === RESOLVED) return 3;\n\tif (t === COMPLETE || t === ERROR) return 4;\n\tif (t === TEARDOWN) return 5;\n\treturn 1; // unknown → immediate (after START)\n}\n\n/**\n * Returns whether this tuple is deferred by `batch()` (phase 2: `DATA` or `RESOLVED`).\n *\n * @param msg — Single message tuple.\n * @returns `true` if `msg` is `DATA` or `RESOLVED`.\n *\n * @example\n * ```ts\n * import { DATA, RESOLVED, DIRTY, isPhase2Message } from \"@graphrefly/graphrefly-ts\";\n *\n * isPhase2Message([DATA, 42]); // true\n * isPhase2Message([RESOLVED]); // true\n * isPhase2Message([DIRTY]); // false\n * ```\n */\nexport function isPhase2Message(msg: Message): boolean {\n\tconst t = msg[0];\n\treturn t === DATA || t === RESOLVED;\n}\n\n/**\n * Returns whether this message type is terminal (COMPLETE or ERROR).\n * Terminal messages are delivered after phase-2 in the same batch to prevent\n * the node from becoming terminal before value messages reach sinks.\n *\n * @param t — Message type symbol.\n * @returns `true` for `COMPLETE` or `ERROR`.\n *\n * @example\n * ```ts\n * import { COMPLETE, ERROR, DATA, isTerminalMessage } from \"@graphrefly/graphrefly-ts\";\n *\n * isTerminalMessage(COMPLETE); // true\n * isTerminalMessage(ERROR); // true\n * isTerminalMessage(DATA); // false\n * ```\n */\nexport function isTerminalMessage(t: symbol): boolean {\n\treturn t === COMPLETE || t === ERROR;\n}\n\n/**\n * Whether `t` is a graph-local signal that should NOT cross a wire/transport\n * boundary (SSE, WebSocket, worker bridge, persistence sinks).\n *\n * Local-only signals (tier 0–2): START, DIRTY, INVALIDATE, PAUSE, RESUME.\n * These are internal to the reactive graph — subscribe handshakes,\n * notification phases, and flow control have no semantics for remote consumers.\n *\n * Wire-crossing signals (tier 3+): DATA, RESOLVED, COMPLETE, ERROR, TEARDOWN.\n * Unknown message types (spec §1.3.6 forward-compat) also cross the wire.\n *\n * Individual adapters may further opt-in to local signals for observability\n * (e.g. SSE `includeDirty`, `includeResolved` options). Storage/persistence\n * adapters that need INVALIDATE for remote cache-clear should explicitly\n * forward it despite `isLocalOnly(INVALIDATE) === true`. The default is to\n * skip all local-only signals at the boundary.\n *\n * @param t — Message type symbol.\n * @returns `true` if the message should be kept local (not sent over wire).\n *\n * @example\n * ```ts\n * import { START, DIRTY, DATA, COMPLETE, isLocalOnly } from \"@graphrefly/graphrefly-ts\";\n *\n * isLocalOnly(START); // true — subscribe handshake\n * isLocalOnly(DIRTY); // true — notification phase\n * isLocalOnly(RESOLVED); // false — value settlement crosses wire\n * isLocalOnly(DATA); // false — value crosses wire\n * isLocalOnly(COMPLETE); // false — terminal crosses wire\n * ```\n *\n * @category core\n */\nexport function isLocalOnly(t: symbol): boolean {\n\t// Unknown types always cross the wire (spec §1.3.6 forward-compat).\n\t// messageTier returns 1 for unknowns, but unknowns are NOT local-only.\n\tif (!knownMessageSet.has(t)) return false;\n\treturn messageTier(t) < 3;\n}\n\n/**\n * Whether `t` should be propagated from a parent node to its companion meta nodes.\n * Only TEARDOWN propagates; COMPLETE/ERROR/INVALIDATE do not (meta outlives parent\n * terminal state for post-mortem writes).\n *\n * @param t — Message type symbol.\n * @returns `true` if the signal should reach meta nodes.\n *\n * @example\n * ```ts\n * import { TEARDOWN, COMPLETE, ERROR, propagatesToMeta } from \"@graphrefly/graphrefly-ts\";\n *\n * propagatesToMeta(TEARDOWN); // true\n * propagatesToMeta(COMPLETE); // false\n * propagatesToMeta(ERROR); // false\n * ```\n */\nexport function propagatesToMeta(t: symbol): boolean {\n\treturn t === TEARDOWN;\n}\n","// ---------------------------------------------------------------------------\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 * **Important:** This subscribes and waits for a **future** emission. Data that\n * has already flowed is gone and will not be seen. Call this *before* the upstream\n * emits, or use `source.get()` / `source.status` for already-cached state.\n * See COMPOSITION-GUIDE §2 (subscription ordering).\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 * Wait for the first DATA value from `source` that satisfies `predicate`.\n *\n * Subscribes directly and resolves on the first DATA value where\n * `predicate` returns true. Reactive, no polling. Use in tests and\n * bridging code where you need a single matching value as a Promise.\n *\n * **Important:** This only captures **future** emissions — data that has\n * already flowed through the node is gone. Call this *before* the upstream\n * emits. For already-cached values, use `source.get()` / `source.status`.\n * See COMPOSITION-GUIDE §2 (subscription ordering).\n *\n * ```ts\n * const val = await firstWhere(strategy.node, snap => snap.size > 0);\n * ```\n *\n * @category extra\n */\nexport function firstWhere<T>(source: Node<T>, predicate: (value: T) => boolean): 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\tconst v = m[1] as T;\n\t\t\t\t\tif (predicate(v)) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tresolve(v);\n\t\t\t\t\t\tqueueMicrotask(() => unsub());\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\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 matching value\"));\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 * Centralised timestamp utilities.\n *\n * Convention: all graphrefly-ts timestamps use nanoseconds (`_ns` suffix).\n *\n * - {@link monotonicNs} — monotonic clock (ordering, durations, timeline events).\n * - {@link wallClockNs} — wall-clock (mutation attribution, cron emission).\n *\n * **Precision limits (JS platform):**\n *\n * - `monotonicNs`: effective ~microsecond precision. `performance.now()` returns\n * milliseconds with ~5µs resolution; the last 3 digits of the nanosecond value\n * are always zero. Python's `time.monotonic_ns()` gives true nanoseconds.\n *\n * - `wallClockNs`: ~256ns precision loss at current epoch. `Date.now() * 1e6`\n * produces values around 1.8×10¹⁸ which exceed IEEE 754's 2⁵³ safe integer\n * limit. Python's `time.time_ns()` (arbitrary-precision `int`) has no loss.\n * In practice this is irrelevant — JS is single-threaded, so sub-microsecond\n * timestamp collisions cannot occur.\n */\n\n/** Monotonic nanosecond timestamp via `performance.now()`. */\nexport function monotonicNs(): number {\n\treturn Math.trunc(performance.now() * 1_000_000);\n}\n\n/** Wall-clock nanosecond timestamp via `Date.now()`. */\nexport function wallClockNs(): number {\n\treturn Date.now() * 1_000_000;\n}\n","/**\n * 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","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","import {\n\tDATA,\n\tisPhase2Message,\n\tisTerminalMessage,\n\ttype Message,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n} from \"./messages.js\";\n\n/**\n * §1.3.7 — Inside a batch, DIRTY propagates immediately; DATA and RESOLVED are\n * deferred until the outermost `batch()` callback returns. Terminal signals\n * (COMPLETE, ERROR) are delivered after phase-2 messages in the same batch\n * (see canonical ordering in `messages.ts`).\n */\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\nconst pendingPhase2: Array<() => void> = [];\nconst pendingPhase3: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * deferred phase-2 work is draining.\n *\n * Matching Python's `is_batching()` semantics: nested emissions during drain\n * are deferred until the current drain pass completes, preventing ordering\n * bugs when callbacks trigger further DATA/RESOLVED.\n *\n * @returns `true` while inside `batch()` or while the drain loop is running.\n *\n * @example\n * ```ts\n * import { batch, isBatching } from \"@graphrefly/graphrefly-ts\";\n *\n * batch(() => {\n * console.log(isBatching()); // true\n * });\n * ```\n *\n * @category core\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral queue.\n * If `fn` throws (including from a nested `batch`), deferred DATA/RESOLVED for\n * that **outer** `batch` frame are discarded — phase-2 is not flushed after an\n * error. While the drain loop is running (`flushInProgress`), a nested `batch`\n * that throws must **not** clear the global queue (cross-language decision A4).\n *\n * During the drain loop, `isBatching()` remains true so nested `downWithBatch`\n * calls still defer phase-2 messages. The drain loop runs until the queue is\n * quiescent (no pending work remains). Per-emission try/catch ensures one\n * throwing callback does not orphan remaining emissions; the first error is\n * re-thrown after all emissions drain. Callbacks that ran before the throw may\n * have applied phase-2 — partial graph state is intentional (decision C1).\n *\n * @param fn — Synchronous work that may call `downWithBatch` / `node.down()`.\n * @returns `void` — all side-effects happen through `downWithBatch` and the\n * phase-2 drain that runs after `fn` returns.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.batch(() => {\n * core.downWithBatch(sink, [[core.DATA, 1]]);\n * });\n * ```\n *\n * @category core\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\t// Do not wipe the outer drain's queue (decision A4).\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) {\n\t\tflushInProgress = true;\n\t}\n\tconst errors: unknown[] = [];\n\ttry {\n\t\tlet iterations = 0;\n\t\t// Drain phase-2 first, then phase-3. If phase-3 callbacks enqueue new\n\t\t// phase-2 work, the outer loop catches it and drains phase-2 again\n\t\t// before re-entering phase-3.\n\t\twhile (pendingPhase2.length > 0 || pendingPhase3.length > 0) {\n\t\t\t// Phase-2 (DATA/RESOLVED) — parent node values settle here.\n\t\t\twhile (pendingPhase2.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase2.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Phase-3 — meta companion emissions that must follow parent settlement.\n\t\t\tif (pendingPhase3.length > 0) {\n\t\t\t\titerations += 1;\n\t\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\t\tpendingPhase2.length = 0;\n\t\t\t\t\tpendingPhase3.length = 0;\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst ops = pendingPhase3.splice(0);\n\t\t\t\tfor (const run of ops) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trun();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) {\n\t\t\tflushInProgress = false;\n\t\t}\n\t}\n\tif (errors.length === 1) {\n\t\tthrow errors[0];\n\t}\n\tif (errors.length > 1) {\n\t\tthrow new AggregateError(errors, \"batch drain: multiple callbacks threw\");\n\t}\n}\n\n/**\n * Splits a message array into three groups by signal tier (see `messages.ts`):\n *\n * - **immediate** — tier 0–2, 5: START, DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN, unknown\n * - **deferred** — tier 3: DATA, RESOLVED (phase-2, deferred inside `batch()`)\n * - **terminal** — tier 4: COMPLETE, ERROR (delivered after phase-2)\n *\n * Order within each group is preserved.\n *\n * @param messages — One `down()` payload.\n * @returns Three groups in canonical delivery order.\n *\n * @example\n * ```ts\n * import { DATA, DIRTY, COMPLETE, partitionForBatch } from \"@graphrefly/graphrefly-ts\";\n *\n * partitionForBatch([[DIRTY], [DATA, 1], [COMPLETE]]);\n * // { immediate: [[DIRTY]], deferred: [[DATA, 1]], terminal: [[COMPLETE]] }\n * ```\n *\n * @category core\n */\nexport function partitionForBatch(messages: Messages): {\n\timmediate: Messages;\n\tdeferred: Messages;\n\tterminal: Messages;\n} {\n\tconst immediate: Message[] = [];\n\tconst deferred: Message[] = [];\n\tconst terminal: Message[] = [];\n\tfor (const m of messages) {\n\t\tif (isPhase2Message(m)) {\n\t\t\tdeferred.push(m);\n\t\t} else if (isTerminalMessage(m[0])) {\n\t\t\tterminal.push(m);\n\t\t} else {\n\t\t\timmediate.push(m);\n\t\t}\n\t}\n\treturn { immediate, deferred, terminal };\n}\n\n/**\n * Delivers messages downstream through `sink`, applying batch semantics and\n * canonical tier-based ordering (see `messages.ts`):\n *\n * 1. **Immediate** (tier 0–2, 5): START, DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN,\n * unknown — delivered synchronously.\n * 2. **Phase-2** (tier 3): DATA, RESOLVED — deferred while `isBatching()`.\n * 3. **Terminal** (tier 4): COMPLETE, ERROR — always delivered after phase-2.\n * When batching, terminal is queued after deferred phase-2 in the pending list.\n * When not batching, terminal is delivered after phase-2 synchronously.\n *\n * This ordering prevents the \"COMPLETE-before-DATA\" class of bugs: terminal\n * signals never make a node terminal before phase-2 values reach sinks,\n * regardless of how the source assembled the message array.\n *\n * @param sink — Sink callback. May be called up to three times per invocation\n * (immediate, deferred, terminal) when not batching.\n * @param messages — Full `[[Type, Data?], ...]` array for one downstream delivery.\n * @param phase — Starting delivery phase (`2` = data, `3` = terminal). Default `2`.\n * @param options - Optional configuration.\n * @option strategy | `\"partition\"` or `\"sequential\"` | `\"partition\"` | `\"partition\"` groups by tier; `\"sequential\"` preserves message order within each tier using `messageTier()` classification.\n * @returns `void` — delivery is performed through `sink` callbacks, synchronously\n * or deferred into the active batch queue.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * core.downWithBatch((msgs) => console.log(msgs), [[core.DIRTY], [core.DATA, 42]]);\n * ```\n *\n * @category core\n */\n/** Delivery strategy for {@link downWithBatch}. Mirrors Python `DownStrategy`. */\nexport type DownStrategy = \"partition\" | \"sequential\";\n\nexport function downWithBatch(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n\toptions?: { strategy?: DownStrategy },\n): void {\n\tif (messages.length === 0) {\n\t\treturn;\n\t}\n\n\tif (options?.strategy === \"sequential\") {\n\t\t_downSequential(sink, messages, phase);\n\t\treturn;\n\t}\n\n\tconst queue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\n\t// Fast path: single-message batches (most common in graph-internal propagation)\n\t// skip partitionForBatch allocation entirely.\n\tif (messages.length === 1) {\n\t\tconst t = messages[0][0];\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else if (isTerminalMessage(t)) {\n\t\t\t// Terminal single message: defer when batching so any preceding\n\t\t\t// phase-2 in the queue flushes first.\n\t\t\tif (isBatching()) {\n\t\t\t\tqueue.push(() => sink(messages));\n\t\t\t} else {\n\t\t\t\tsink(messages);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate: deliver synchronously.\n\t\t\tsink(messages);\n\t\t}\n\t\treturn;\n\t}\n\t// Multi-message: three-way partition by tier.\n\tconst { immediate, deferred, terminal } = partitionForBatch(messages);\n\n\t// 1. Immediate signals (tier 0–2, 5) — deliver synchronously now.\n\tif (immediate.length > 0) {\n\t\tsink(immediate);\n\t}\n\n\t// 2. Deferred (tier 3) + Terminal (tier 4) — canonical order preserved.\n\tif (isBatching()) {\n\t\tif (deferred.length > 0) {\n\t\t\tqueue.push(() => sink(deferred));\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tqueue.push(() => sink(terminal));\n\t\t}\n\t} else {\n\t\tif (deferred.length > 0) {\n\t\t\tsink(deferred);\n\t\t}\n\t\tif (terminal.length > 0) {\n\t\t\tsink(terminal);\n\t\t}\n\t}\n}\n\n/**\n * Sequential strategy: walk messages one at a time. Phase-2 (DATA/RESOLVED) and\n * terminal (COMPLETE/ERROR) messages are deferred while batching; immediate\n * messages deliver synchronously. Matches graphrefly-py `_down_sequential`.\n *\n * Tier legend (after START introduction):\n * 0 = START — immediate, delivered before other tiers\n * 1 = DIRTY, INVALIDATE — immediate\n * 2 = PAUSE, RESUME — immediate\n * 3 = DATA, RESOLVED — deferred inside batch\n * 4 = COMPLETE, ERROR — deferred to phase-3 queue (drains after data)\n * 5 = TEARDOWN — deferred to phase-3 queue (drains after data)\n */\nfunction _downSequential(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\tphase: 2 | 3 = 2,\n): void {\n\tconst dataQueue = phase === 3 ? pendingPhase3 : pendingPhase2;\n\tfor (const msg of messages) {\n\t\tconst tier = messageTier(msg[0]);\n\t\tif (tier === 3) {\n\t\t\t// Phase-2 (DATA/RESOLVED): defer while batching.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tdataQueue.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else if (tier >= 4) {\n\t\t\t// Terminal + destruction (COMPLETE/ERROR/TEARDOWN): always route to\n\t\t\t// phase-3 queue — terminals and teardown must drain after all phase-2\n\t\t\t// work to prevent premature termination or early resource release.\n\t\t\tif (isBatching()) {\n\t\t\t\tconst m = msg;\n\t\t\t\tpendingPhase3.push(() => sink([m]));\n\t\t\t} else {\n\t\t\t\tsink([msg]);\n\t\t\t}\n\t\t} else {\n\t\t\t// Immediate (START, DIRTY, INVALIDATE, PAUSE, RESUME):\n\t\t\t// deliver synchronously.\n\t\t\tsink([msg]);\n\t\t}\n\t}\n}\n","/**\n * Node versioning — GRAPHREFLY-SPEC §7.\n *\n * Progressive, optional versioning for node identity and change tracking.\n *\n * - **V0**: `id` + `version` — identity & change detection (~16 bytes overhead)\n * - **V1**: + `cid` + `prev` — content addressing & linked history (~60 bytes overhead)\n *\n * **Lifecycle notes:**\n * - Version advances only on DATA (not RESOLVED, INVALIDATE, or TEARDOWN).\n * - `resetOnTeardown` clears the cached value but does NOT reset versioning state.\n * After teardown, `v.cid` still reflects the last DATA value, not the cleared cache.\n * The invariant `hash(node.get()) === v.cid` only holds in `settled`/`resolved` status.\n * - Resubscribable nodes preserve versioning across subscription lifetimes (monotonic counter).\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** V0: identity + monotonic version counter. */\nexport type V0 = {\n\treadonly id: string;\n\tversion: number;\n};\n\n/** V1: V0 + content-addressed identifier + previous cid link. */\nexport type V1 = V0 & {\n\tcid: string;\n\tprev: string | null;\n};\n\n/** Union of all versioning info shapes. */\nexport type NodeVersionInfo = V0 | V1;\n\n/** Supported versioning levels (extensible to 2, 3 later). */\nexport type VersioningLevel = 0 | 1;\n\n/** Function that hashes a value to a hex string (for V1 cid). */\nexport type HashFn = (value: unknown) => string;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface VersioningOptions {\n\t/** Override auto-generated id. */\n\tid?: string;\n\t/** Custom hash function for V1 cid (default: SHA-256 truncated to 16 hex chars). */\n\thash?: HashFn;\n}\n\n// ---------------------------------------------------------------------------\n// Default hash\n// ---------------------------------------------------------------------------\n\n/**\n * Canonicalize a value for deterministic cross-language hashing.\n *\n * - Integer-valued floats normalize to integer strings (`1.0` → `1`).\n * - `NaN`, `Infinity`, `-Infinity` are rejected (no JSON equivalent).\n * - `undefined` normalizes to `null`.\n * - Object keys are sorted lexicographically.\n *\n * This ensures TS `JSON.stringify` and Python `json.dumps(sort_keys=True)`\n * produce identical output for the same logical value.\n */\nexport function canonicalizeForHash(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow new TypeError(`Cannot hash non-finite number: ${value}`);\n\t\t}\n\t\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. ` +\n\t\t\t\t\t\"Cross-language cid parity is not guaranteed for unsafe integers.\",\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\" || typeof value === \"boolean\" || value === null) {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalizeForHash);\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst sorted: Record<string, unknown> = {};\n\t\tfor (const k of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tsorted[k] = canonicalizeForHash((value as Record<string, unknown>)[k]);\n\t\t}\n\t\treturn sorted;\n\t}\n\t// Fallback: coerce to null (bigint, symbol, function)\n\treturn null;\n}\n\n/**\n * Default content hash: SHA-256 of deterministic JSON, truncated to 16 hex chars (~64-bit).\n * Uses {@link canonicalizeForHash} for cross-language parity with Python `default_hash`.\n */\nexport function defaultHash(value: unknown): string {\n\tconst canonical = canonicalizeForHash(value ?? null);\n\tconst json = JSON.stringify(canonical);\n\treturn createHash(\"sha256\").update(json).digest(\"hex\").slice(0, 16);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create initial versioning state for a node.\n *\n * @param level - 0 for V0, 1 for V1.\n * @param initialValue - The node's initial cached value (used for V1 cid).\n * @param opts - Optional overrides (id, hash).\n */\nexport function createVersioning(\n\tlevel: VersioningLevel,\n\tinitialValue: unknown,\n\topts?: VersioningOptions,\n): NodeVersionInfo {\n\tconst id = opts?.id ?? randomUUID();\n\tif (level === 0) {\n\t\treturn { id, version: 0 } satisfies V0;\n\t}\n\tconst hash = opts?.hash ?? defaultHash;\n\tconst cid = hash(initialValue);\n\treturn { id, version: 0, cid, prev: null } satisfies V1;\n}\n\n// ---------------------------------------------------------------------------\n// Advance\n// ---------------------------------------------------------------------------\n\n/**\n * Advance versioning state after a DATA emission (value changed).\n *\n * Mutates `info` in place for performance (called on every DATA).\n * Only call when the cached value has actually changed (not on RESOLVED).\n *\n * @param info - The node's current versioning state.\n * @param newValue - The new cached value.\n * @param hashFn - Hash function (only used for V1).\n */\nexport function advanceVersion(info: NodeVersionInfo, newValue: unknown, hashFn: HashFn): void {\n\tinfo.version += 1;\n\tif (\"cid\" in info) {\n\t\t(info as V1).prev = (info as V1).cid;\n\t\t(info as V1).cid = hashFn(newValue);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this V1 versioning info? */\nexport function isV1(info: NodeVersionInfo): info is V1 {\n\treturn \"cid\" in info;\n}\n","/**\n * `NodeBase` — abstract class implementing the {@link Node} protocol with\n * lifecycle machinery shared between {@link NodeImpl} (static deps) and\n * {@link DynamicNodeImpl} (runtime-tracked deps).\n *\n * **Responsibilities (shared):**\n * - Identity (name, describeKind, meta, guard, versioning)\n * - Cache + status lifecycle (`_cached`, `_status`, `_terminal`)\n * - Sink storage (null / single / Set fast paths)\n * - `subscribe()` with START handshake + first-subscriber activation\n * - `_downInternal` → `_downToSinks` delivery pipeline (via `downWithBatch`)\n * - `_downAutoValue` (value → protocol framing with equals)\n * - `_handleLocalLifecycle` (cached/status/terminal updates + meta propagation)\n *\n * **Subclass hooks (abstract):**\n * - `_onActivate()` — called when sinkCount transitions 0 → 1\n * - `_doDeactivate()` — cleanup on deactivation (at-most-once, guarded by `_onDeactivate`)\n * - `up()` / `unsubscribe()` / `_upInternal()` — dep-iteration specifics\n * - `_createMetaNode()` — meta companion factory (avoids circular imports)\n *\n * See GRAPHREFLY-SPEC §2 and COMPOSITION-GUIDE §1 for protocol contracts.\n */\n\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { downWithBatch } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\tpropagatesToMeta,\n\tRESOLVED,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, NodeVersionInfo, VersioningLevel } from \"./versioning.js\";\nimport { advanceVersion, createVersioning, defaultHash } from \"./versioning.js\";\n\n// ---------------------------------------------------------------------------\n// Symbols\n// ---------------------------------------------------------------------------\n\n/**\n * Internal sentinel value: \"no cached value has been set or emitted.\"\n * Used instead of `undefined` so that `undefined` can be a valid emitted value.\n */\nexport const NO_VALUE: unique symbol = Symbol.for(\"graphrefly/NO_VALUE\");\n\n/**\n * Branded symbol that marks a {@link CleanupResult} wrapper — prevents\n * duck-type collisions with domain objects that happen to have a `cleanup`\n * property.\n */\nexport const CLEANUP_RESULT: unique symbol = Symbol.for(\"graphrefly/CLEANUP_RESULT\");\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Lifecycle status of a node (GRAPHREFLY-SPEC §2.2). */\nexport type NodeStatus =\n\t| \"disconnected\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\n/** Callback that receives downstream message batches. */\nexport type NodeSink = (messages: Messages) => void;\n\n/** Imperative actions available inside a node's compute function. */\nexport interface NodeActions {\n\t/** Emit raw messages downstream. */\n\tdown(messages: Messages): void;\n\t/** Emit a single value (auto-wraps in DIRTY/DATA or DIRTY/RESOLVED). */\n\temit(value: unknown): void;\n\t/** Send messages upstream toward sources. */\n\tup(messages: Messages): void;\n}\n\n/**\n * Callback for intercepting messages before the default dispatch (§2.6).\n *\n * Called for every message from every dep. Return `true` to consume\n * (skip default handling), or `false` to let default dispatch run.\n */\nexport type OnMessageHandler = (msg: Message, depIndex: number, actions: NodeActions) => boolean;\n\n/**\n * Internal inspector hook (opt-in): emits dependency message and run events\n * for graph-level observability features (`observe(..., { causal|derived })`).\n */\nexport type NodeInspectorHookEvent =\n\t| { kind: \"dep_message\"; depIndex: number; message: Message }\n\t| { kind: \"run\"; depValues: readonly unknown[] };\n\nexport type NodeInspectorHook = (event: NodeInspectorHookEvent) => void;\n\n/** Explicit describe `type` for {@link Graph.describe} (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\n/** Options accepted by every node constructor. */\nexport interface NodeOptions {\n\tname?: string;\n\t/**\n\t * Overrides inferred `type` in describe output. Sugar constructors set this;\n\t * omit to infer from deps / fn / manual emit usage.\n\t */\n\tdescribeKind?: NodeDescribeKind;\n\t/** Equality check for RESOLVED detection. Defaults to `Object.is`. */\n\tequals?: (a: unknown, b: unknown) => boolean;\n\tinitial?: unknown;\n\t/**\n\t * Each key becomes an independently subscribable companion node.\n\t * Meta nodes outlive the parent's subscription lifecycle: when all sinks\n\t * unsubscribe the parent deactivates but meta nodes stay alive.\n\t * Send `[[TEARDOWN]]` to the parent to release meta node resources.\n\t */\n\tmeta?: Record<string, unknown>;\n\t/** Allow fresh subscriptions after COMPLETE/ERROR. */\n\tresubscribable?: boolean;\n\t/**\n\t * Invoked when a new {@link Node.subscribe} clears a terminal state on a\n\t * resubscribable node — reset operator-local counters/accumulators here.\n\t */\n\tonResubscribe?: () => void;\n\t/** Clear cached value on TEARDOWN. */\n\tresetOnTeardown?: boolean;\n\t/**\n\t * When `true` (default), auto-emit `[[COMPLETE]]` when all deps complete\n\t * (spec §1.3.5). Set `false` for derived/operator nodes that should not\n\t * auto-complete.\n\t */\n\tcompleteWhenDepsComplete?: boolean;\n\t/**\n\t * Intercept messages before the default dispatch (spec §2.6).\n\t *\n\t * Return `true` to consume the message (skip default handling),\n\t * or `false` to let the default dispatch run.\n\t */\n\tonMessage?: OnMessageHandler;\n\t/**\n\t * ABAC: `(actor, action) => boolean`. `write` applies to both {@link Node.down} and {@link Node.up}.\n\t * Companion {@link NodeOptions.meta | meta} nodes inherit this guard from the primary.\n\t */\n\tguard?: NodeGuard;\n\t/** Opt-in versioning level (GRAPHREFLY-SPEC §7). */\n\tversioning?: VersioningLevel;\n\t/** Override auto-generated versioning id. */\n\tversioningId?: string;\n\t/** Custom hash function for V1 cid computation. */\n\tversioningHash?: HashFn;\n}\n\n/** Actor/delivery context for {@link Node.down} and {@link Node.up}. */\nexport type NodeTransportOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips guard checks (reactive internals, graph lifecycle TEARDOWN, etc.).\n\t * Not for untrusted call sites.\n\t */\n\tinternal?: boolean;\n\t/**\n\t * `signal` for {@link Graph.signal} deliveries; default `write` for {@link Graph.set}\n\t * and direct `down`.\n\t */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/** Optional hints passed to {@link Node.subscribe}. */\nexport interface SubscribeHints {\n\t/**\n\t * Subscriber has exactly one dep with `fn` — the source may skip DIRTY\n\t * dispatch when this is the sole subscriber. The subscriber synthesizes\n\t * dirty state locally.\n\t */\n\tsingleDep?: boolean;\n\t/**\n\t * Actor to check against the node's `observe` guard. When set,\n\t * `subscribe()` throws {@link GuardDenied} if the actor is not permitted\n\t * to observe this node.\n\t */\n\tactor?: Actor;\n}\n\n/** A reactive node in the GraphReFly protocol. */\nexport interface Node<T = unknown> {\n\treadonly name?: string;\n\treadonly status: NodeStatus;\n\treadonly meta: Record<string, Node>;\n\t/** Returns the current cached value. */\n\tget(): T | undefined;\n\t/** Push messages downstream. */\n\tdown(messages: Messages, options?: NodeTransportOptions): void;\n\t/**\n\t * Registers a sink to receive downstream messages.\n\t *\n\t * @param sink - Callback receiving message batches.\n\t * @param hints - Optional optimization hints (e.g. `{ singleDep: true }`).\n\t * @returns An unsubscribe function (idempotent).\n\t */\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void;\n\t/** Send messages upstream (present on nodes with deps). */\n\tup?: (messages: Messages, options?: NodeTransportOptions) => void;\n\t/** Disconnect from upstream deps (present on nodes with deps). */\n\tunsubscribe?: () => void;\n\t/** Last successful guarded `down` / `up` (not set for `internal` deliveries). */\n\treadonly lastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/** Whether `actor` may {@link Graph.observe} this node. */\n\tallowsObserve(actor: Actor): boolean;\n\t/** Whether a {@link NodeOptions.guard | guard} is installed. */\n\thasGuard(): boolean;\n\t/** Versioning info (GRAPHREFLY-SPEC §7). `undefined` when versioning is not enabled. */\n\treadonly v: Readonly<NodeVersionInfo> | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Cleanup result wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Explicit cleanup wrapper. When a node fn returns `{ cleanup, value? }`,\n * `cleanup` is registered as the teardown/recompute cleanup and `value`\n * (if present) is emitted as data. This avoids the ambiguity where returning\n * a plain function is silently consumed as cleanup instead of emitted as data.\n */\nexport type CleanupResult<T = unknown> = {\n\treadonly [CLEANUP_RESULT]: true;\n\tcleanup: () => void;\n\tvalue?: T;\n};\n\n/** Create a branded {@link CleanupResult}. */\nexport function cleanupResult<T>(cleanup: () => void): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, value: T): CleanupResult<T>;\nexport function cleanupResult<T>(cleanup: () => void, ...args: [] | [T]): CleanupResult<T> {\n\tconst r: CleanupResult<T> = { [CLEANUP_RESULT]: true, cleanup };\n\tif (args.length > 0) r.value = args[0];\n\treturn r;\n}\n\nexport const isCleanupResult = (value: unknown): value is CleanupResult =>\n\ttypeof value === \"object\" && value !== null && CLEANUP_RESULT in value;\n\nexport const isCleanupFn = (value: unknown): value is () => void => typeof value === \"function\";\n\n// ---------------------------------------------------------------------------\n// Status transitions\n// ---------------------------------------------------------------------------\n\n/**\n * Returns the post-message status for `status` after processing `msg`.\n * START is informational and does not transition status.\n */\nexport function statusAfterMessage(status: NodeStatus, msg: Message): NodeStatus {\n\tconst t = msg[0];\n\tif (t === DIRTY) return \"dirty\";\n\tif (t === DATA) return \"settled\";\n\tif (t === RESOLVED) return \"resolved\";\n\tif (t === COMPLETE) return \"completed\";\n\tif (t === ERROR) return \"errored\";\n\tif (t === INVALIDATE) return \"dirty\";\n\tif (t === TEARDOWN) return \"disconnected\";\n\treturn status;\n}\n\n// ---------------------------------------------------------------------------\n// BitSet — dep mask helper (int fast path for ≤31 deps, array for more)\n// ---------------------------------------------------------------------------\n\n/**\n * Dep settlement tracker. IMPORTANT: `covers()` requires both operands to be\n * the same concrete type (both IntBitSet or both ArrayBitSet). Within a node,\n * all masks share the same `createBitSet(deps.length)` factory, so this is\n * always satisfied.\n */\nexport interface BitSet {\n\tset(index: number): void;\n\tclear(index: number): void;\n\thas(index: number): boolean;\n\t/** True when all bits in `other` are also set in `this`. */\n\tcovers(other: BitSet): boolean;\n\t/** True when at least one bit is set. */\n\tany(): boolean;\n\treset(): void;\n\t/** Set all bits in [0, size) — used for the pre-set-dirty wave trick. */\n\tsetAll(): void;\n}\n\nfunction createIntBitSet(size: number): BitSet {\n\tconst fullMask = size >= 32 ? -1 : ~(-1 << size);\n\tlet bits = 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\tbits |= 1 << i;\n\t\t},\n\t\tclear(i: number) {\n\t\t\tbits &= ~(1 << i);\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (bits & (1 << i)) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst otherBits = (other as unknown as { _bits(): number })._bits();\n\t\t\treturn (bits & otherBits) === otherBits;\n\t\t},\n\t\tany() {\n\t\t\treturn bits !== 0;\n\t\t},\n\t\treset() {\n\t\t\tbits = 0;\n\t\t},\n\t\tsetAll() {\n\t\t\tbits = fullMask;\n\t\t},\n\t\t_bits() {\n\t\t\treturn bits;\n\t\t},\n\t} as BitSet & { _bits(): number };\n}\n\nfunction createArrayBitSet(size: number): BitSet {\n\tconst words = new Uint32Array(Math.ceil(size / 32));\n\tconst lastBits = size % 32;\n\tconst lastWordMask = lastBits === 0 ? 0xffffffff : ((1 << lastBits) - 1) >>> 0;\n\treturn {\n\t\tset(i: number) {\n\t\t\twords[i >>> 5] |= 1 << (i & 31);\n\t\t},\n\t\tclear(i: number) {\n\t\t\twords[i >>> 5] &= ~(1 << (i & 31));\n\t\t},\n\t\thas(i: number) {\n\t\t\treturn (words[i >>> 5] & (1 << (i & 31))) !== 0;\n\t\t},\n\t\tcovers(other: BitSet) {\n\t\t\tconst ow = (other as unknown as { _words: Uint32Array })._words;\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif ((words[w] & ow[w]) >>> 0 !== ow[w]) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\t\tany() {\n\t\t\tfor (let w = 0; w < words.length; w++) {\n\t\t\t\tif (words[w] !== 0) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\treset() {\n\t\t\twords.fill(0);\n\t\t},\n\t\tsetAll() {\n\t\t\tfor (let w = 0; w < words.length - 1; w++) words[w] = 0xffffffff;\n\t\t\tif (words.length > 0) words[words.length - 1] = lastWordMask;\n\t\t},\n\t\t_words: words,\n\t} as unknown as BitSet;\n}\n\n/** Create a BitSet sized for `size` bits (≤31 uses fast int path). */\nexport function createBitSet(size: number): BitSet {\n\treturn size <= 31 ? createIntBitSet(size) : createArrayBitSet(size);\n}\n\n// ---------------------------------------------------------------------------\n// NodeBase\n// ---------------------------------------------------------------------------\n\n/**\n * Abstract base class for every node in the graph. Both {@link NodeImpl}\n * (static deps) and {@link DynamicNodeImpl} (runtime-tracked deps) extend\n * this to share subscribe/sink/lifecycle machinery.\n *\n * Invariants (see GRAPHREFLY-SPEC §2.2):\n * - `_sinkCount` always reflects the size of `_sinks`.\n * - `_cached === NO_VALUE` iff the node has never produced a value (SENTINEL).\n * - `_terminal` is set exactly once (per subscription cycle for resubscribable).\n * - `_onActivate` runs exactly once per activation cycle; `_doDeactivate`\n * runs at most once per deactivation (guarded by `_active` flag).\n *\n * ROM/RAM rule (GRAPHREFLY-SPEC §2.2): state nodes (no fn) preserve `_cached`\n * across disconnect — intrinsic, non-volatile. Compute nodes (derived,\n * producer, dynamic) clear `_cached` on disconnect in their subclass\n * `_doDeactivate` — their value is a function of live subscriptions.\n */\nexport abstract class NodeBase<T = unknown> implements Node<T> {\n\t// --- Identity (set once) ---\n\tprotected readonly _optsName: string | undefined;\n\tprivate _registryName: string | undefined;\n\t/** @internal Read by `describeNode` before inference. */\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\n\t// --- Options ---\n\tprotected readonly _equals: (a: unknown, b: unknown) => boolean;\n\tprotected readonly _resubscribable: boolean;\n\tprotected readonly _resetOnTeardown: boolean;\n\tprotected readonly _onResubscribe: (() => void) | undefined;\n\tprotected readonly _onMessage: OnMessageHandler | undefined;\n\t/** @internal Read by `describeNode` for `accessHintForGuard`. */\n\treadonly _guard: NodeGuard | undefined;\n\t/** @internal Subclasses update this through {@link _recordMutation}. */\n\tprotected _lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\n\t// --- Versioning ---\n\tprotected _hashFn: HashFn;\n\tprivate _versioning: NodeVersionInfo | undefined;\n\n\t// --- Lifecycle state ---\n\t/** @internal Read by `describeNode` and `graph.ts`. */\n\t_cached: T | typeof NO_VALUE;\n\t/** @internal Read externally via `get status()`. */\n\t_status: NodeStatus;\n\tprotected _terminal = false;\n\tprivate _active = false;\n\n\t// --- Sink storage ---\n\t/** @internal Read by `graph/profile.ts` for subscriber counts. */\n\t_sinkCount = 0;\n\tprotected _singleDepSinkCount = 0;\n\tprotected _singleDepSinks = new WeakSet<NodeSink>();\n\tprotected _sinks: NodeSink | Set<NodeSink> | null = null;\n\n\t// --- Actions + bound helpers ---\n\tprotected readonly _actions: NodeActions;\n\tprotected readonly _boundDownToSinks: (messages: Messages) => void;\n\n\t// --- Inspector hook (Graph observability) ---\n\tprivate _inspectorHook: NodeInspectorHook | undefined;\n\n\tconstructor(opts: NodeOptions) {\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = opts.equals ?? Object.is;\n\t\tthis._resubscribable = opts.resubscribable ?? false;\n\t\tthis._resetOnTeardown = opts.resetOnTeardown ?? false;\n\t\tthis._onResubscribe = opts.onResubscribe;\n\t\tthis._onMessage = opts.onMessage;\n\t\tthis._guard = opts.guard;\n\n\t\t// Cache pre-populated from `initial`, or SENTINEL.\n\t\tthis._cached = \"initial\" in opts ? (opts.initial as T) : NO_VALUE;\n\t\t// Initial status: state with value starts settled, otherwise disconnected.\n\t\tthis._status = \"disconnected\";\n\n\t\t// Versioning (GRAPHREFLY-SPEC §7)\n\t\tthis._hashFn = opts.versioningHash ?? defaultHash;\n\t\tthis._versioning =\n\t\t\topts.versioning != null\n\t\t\t\t? createVersioning(opts.versioning, this._cached === NO_VALUE ? undefined : this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\t// Build companion meta nodes — dispatched to subclass to avoid\n\t\t// circular imports (node-base → node → node-base).\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tmeta[k] = this._createMetaNode(k, v, opts);\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\n\t\t// Actions captured once — references `this` via an arrow/closure so\n\t\t// subclass hooks (e.g. `_onManualEmit`) fire on the right instance.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\tdown(messages): void {\n\t\t\t\tself._onManualEmit();\n\t\t\t\tself._downInternal(messages);\n\t\t\t},\n\t\t\temit(value): void {\n\t\t\t\tself._onManualEmit();\n\t\t\t\tself._downAutoValue(value);\n\t\t\t},\n\t\t\tup(messages): void {\n\t\t\t\tself._upInternal(messages);\n\t\t\t},\n\t\t};\n\n\t\tthis._boundDownToSinks = this._downToSinks.bind(this);\n\t}\n\n\t/**\n\t * Subclass hook invoked by `actions.down` / `actions.emit`. Default no-op;\n\t * {@link NodeImpl} overrides to set `_manualEmitUsed`.\n\t */\n\tprotected _onManualEmit(): void {\n\t\t/* no-op */\n\t}\n\n\t/**\n\t * Create a companion meta node. Called from the base constructor; must\n\t * not touch subclass fields that haven't been initialized yet (safe to\n\t * read from `opts`).\n\t */\n\tprotected abstract _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node;\n\n\t// --- Identity getters ---\n\n\tget name(): string | undefined {\n\t\treturn this._registryName ?? this._optsName;\n\t}\n\n\t/** @internal Assigned by `Graph.add` when registered without an options `name`. */\n\t_assignRegistryName(localName: string): void {\n\t\tif (this._optsName !== undefined || this._registryName !== undefined) return;\n\t\tthis._registryName = localName;\n\t}\n\n\t/**\n\t * @internal Attach/remove inspector hook for graph-level observability.\n\t * Returns a disposer that restores the previous hook.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tconst prev = this._inspectorHook;\n\t\tthis._inspectorHook = hook;\n\t\treturn () => {\n\t\t\tif (this._inspectorHook === hook) {\n\t\t\t\tthis._inspectorHook = prev;\n\t\t\t}\n\t\t};\n\t}\n\n\t/** @internal Used by subclasses to surface inspector events. */\n\tprotected _emitInspectorHook(event: NodeInspectorHookEvent): void {\n\t\tthis._inspectorHook?.(event);\n\t}\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\tget v(): Readonly<NodeVersionInfo> | undefined {\n\t\treturn this._versioning;\n\t}\n\n\t/** @internal Used by `Graph.setVersioning` to retroactively apply versioning. */\n\t_applyVersioning(level: VersioningLevel, opts?: { id?: string; hash?: HashFn }): void {\n\t\tif (this._versioning != null) return;\n\t\tthis._hashFn = opts?.hash ?? this._hashFn;\n\t\tthis._versioning = createVersioning(\n\t\t\tlevel,\n\t\t\tthis._cached === NO_VALUE ? undefined : this._cached,\n\t\t\t{\n\t\t\t\tid: opts?.id,\n\t\t\t\thash: this._hashFn,\n\t\t\t},\n\t\t);\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null) return true;\n\t\treturn this._guard(normalizeActor(actor), \"observe\");\n\t}\n\n\t// --- Public transport ---\n\n\tget(): T | undefined {\n\t\treturn this._cached === NO_VALUE ? undefined : this._cached;\n\t}\n\n\tdown(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (messages.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tconst delivery = options?.delivery ?? \"write\";\n\t\t\tconst action: GuardAction = delivery === \"signal\" ? \"signal\" : \"write\";\n\t\t\tif (!this._guard(actor, action)) {\n\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tthis._downInternal(messages);\n\t}\n\n\t/** @internal Record a successful guarded mutation (called by `down` and subclass `up`). */\n\tprotected _recordMutation(actor: Actor): void {\n\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t}\n\n\t/** Abstract — subclasses forward messages to dependencies (or no-op for sources). */\n\tabstract up(messages: Messages, options?: NodeTransportOptions): void;\n\n\t/** Abstract — subclasses release upstream subscriptions (or no-op for sources). */\n\tabstract unsubscribe(): void;\n\n\t/** Internal upstream-send used by `actions.up`. */\n\tprotected abstract _upInternal(messages: Messages): void;\n\n\t/** Called when `_sinkCount` transitions 0 → 1. */\n\tprotected abstract _onActivate(): void;\n\n\t/**\n\t * At-most-once deactivation guard. Both TEARDOWN (eager) and\n\t * unsubscribe-body (lazy) call this. The `_active` flag ensures\n\t * `_doDeactivate` runs exactly once per activation cycle.\n\t */\n\tprotected _onDeactivate(): void {\n\t\tif (!this._active) return;\n\t\tthis._active = false;\n\t\tthis._doDeactivate();\n\t}\n\n\t/** Subclass hook: cleanup on deactivation (called at most once). */\n\tprotected abstract _doDeactivate(): void;\n\n\t// --- Subscribe (uniform across node shapes) ---\n\n\tsubscribe(sink: NodeSink, hints?: SubscribeHints): () => void {\n\t\tif (hints?.actor != null && this._guard != null) {\n\t\t\tconst actor = normalizeActor(hints.actor);\n\t\t\tif (!this._guard(actor, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\t// Resubscribable terminal reset — clear terminal + cache, fire hook.\n\t\tif (this._terminal && this._resubscribable) {\n\t\t\tthis._terminal = false;\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._status = \"disconnected\";\n\t\t\tthis._onResubscribe?.();\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\t\tif (hints?.singleDep) {\n\t\t\tthis._singleDepSinkCount += 1;\n\t\t\tthis._singleDepSinks.add(sink);\n\t\t}\n\n\t\t// §2.2 START handshake — delivered BEFORE registering sink in\n\t\t// `_sinks` so that re-entrant `_downToSinks` calls during\n\t\t// activation cannot reach the new sink before it receives START\n\t\t// (spec §1.3.8: START precedes any other message on a subscription).\n\t\t//\n\t\t// Wire shape:\n\t\t// SENTINEL cache → [[START]]\n\t\t// cached value → [[START], [DATA, cached]]\n\t\t//\n\t\t// DIRTY is intentionally NOT part of the handshake: nothing is\n\t\t// transitioning here, we're simply delivering the current state.\n\t\t// Downstream derived nodes mark both dirty+settled on DATA-without-\n\t\t// prior-DIRTY (spec §1.3.1 compat path), so wave tracking still\n\t\t// works without polluting observers with a spurious DIRTY.\n\t\t// §2.2 handshake: START (+ cached DATA if available). Terminal nodes\n\t\t// skip entirely — absence of START tells the subscriber the stream is\n\t\t// over (spec §2.2: \"absence of START means the subscription was never\n\t\t// established or the node is terminal\"). This is intentional: terminal\n\t\t// nodes release resources; replaying COMPLETE/ERROR to late subscribers\n\t\t// would require retaining the terminal cause indefinitely.\n\t\tif (!this._terminal) {\n\t\t\tconst startMessages: Messages =\n\t\t\t\tthis._cached === NO_VALUE ? [[START]] : [[START], [DATA, this._cached]];\n\t\t\tdownWithBatch(sink, startMessages);\n\t\t}\n\n\t\t// Register sink in the singleton / set storage — AFTER START so\n\t\t// re-entrant `_downToSinks` during `_onActivate` can reach it.\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\t// First subscriber triggers activation. May cause fn to run and emit\n\t\t// via `_downInternal` → `_downToSinks` to the new sink.\n\t\tif (this._sinkCount === 1 && !this._terminal) {\n\t\t\tthis._active = true;\n\t\t\tthis._onActivate();\n\t\t}\n\n\t\t// If activation did not produce a value (compute node blocked on\n\t\t// SENTINEL deps, or a source with no initial), surface \"pending\".\n\t\tif (!this._terminal && this._status === \"disconnected\" && this._cached === NO_VALUE) {\n\t\t\tthis._status = \"pending\";\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn () => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tif (this._singleDepSinks.has(sink)) {\n\t\t\t\tthis._singleDepSinkCount -= 1;\n\t\t\t\tthis._singleDepSinks.delete(sink);\n\t\t\t}\n\t\t\tif (this._sinks == null) return;\n\t\t\tif (typeof this._sinks === \"function\") {\n\t\t\t\tif (this._sinks === sink) this._sinks = null;\n\t\t\t} else {\n\t\t\t\tthis._sinks.delete(sink);\n\t\t\t\tif (this._sinks.size === 1) {\n\t\t\t\t\tconst [only] = this._sinks;\n\t\t\t\t\tthis._sinks = only;\n\t\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\t\tthis._sinks = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._sinks == null) {\n\t\t\t\tthis._onDeactivate();\n\t\t\t}\n\t\t};\n\t}\n\n\t// --- Down pipeline ---\n\n\t/**\n\t * Core outgoing dispatch. Applies terminal filter + local lifecycle\n\t * update, then hands messages to `downWithBatch` for tier-aware delivery.\n\t */\n\tprotected _downInternal(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\t\tlet sinkMessages = messages;\n\t\tif (this._terminal && !this._resubscribable) {\n\t\t\t// After terminal, only TEARDOWN / INVALIDATE still propagate\n\t\t\t// (so graph teardown and cache-clear still work).\n\t\t\tconst pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (pass.length === 0) return;\n\t\t\tsinkMessages = pass as Messages;\n\t\t}\n\t\tthis._handleLocalLifecycle(sinkMessages);\n\t\t// Single-dep DIRTY-skip optimization: when this node's only sink is\n\t\t// single-dep AND the batch contains a phase-2 message (DATA/RESOLVED),\n\t\t// strip DIRTY from the outgoing batch. The downstream learns of the\n\t\t// value via the phase-2 message directly.\n\t\tif (this._canSkipDirty()) {\n\t\t\tlet hasPhase2 = false;\n\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\tconst t = sinkMessages[i][0];\n\t\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\t\thasPhase2 = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPhase2) {\n\t\t\t\tconst filtered: Message[] = [];\n\t\t\t\tfor (let i = 0; i < sinkMessages.length; i++) {\n\t\t\t\t\tif (sinkMessages[i][0] !== DIRTY) filtered.push(sinkMessages[i]);\n\t\t\t\t}\n\t\t\t\tif (filtered.length > 0) {\n\t\t\t\t\tdownWithBatch(this._boundDownToSinks, filtered);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tdownWithBatch(this._boundDownToSinks, sinkMessages);\n\t}\n\n\tprotected _canSkipDirty(): boolean {\n\t\treturn this._sinkCount === 1 && this._singleDepSinkCount === 1;\n\t}\n\n\tprotected _downToSinks(messages: Messages): void {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others mid-iteration.\n\t\t// Iterating the live Set would skip not-yet-visited sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) {\n\t\t\tsink(messages);\n\t\t}\n\t}\n\n\t/**\n\t * Update `_cached`, `_status`, `_terminal` from message batch before\n\t * delivery. Subclass hooks `_onInvalidate` / `_onTeardown` let\n\t * {@link NodeImpl} clear `_lastDepValues` and invoke cleanup fns.\n\t */\n\tprotected _handleLocalLifecycle(messages: Messages): void {\n\t\tfor (const m of messages) {\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (m.length < 2) {\n\t\t\t\t\t// §1.2: bare [DATA] without payload is a protocol violation.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t === INVALIDATE) {\n\t\t\t\tthis._onInvalidate();\n\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t}\n\t\t\tthis._status = statusAfterMessage(this._status, m);\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\tthis._terminal = true;\n\t\t\t}\n\t\t\tif (t === TEARDOWN) {\n\t\t\t\tif (this._resetOnTeardown) {\n\t\t\t\t\tthis._cached = NO_VALUE;\n\t\t\t\t}\n\t\t\t\tthis._onTeardown();\n\t\t\t\ttry {\n\t\t\t\t\tthis._propagateToMeta(t);\n\t\t\t\t} finally {\n\t\t\t\t\t// Force upstream disconnect immediately — don't wait for\n\t\t\t\t\t// downstream to unsubscribe. _onDeactivate's _active\n\t\t\t\t\t// guard ensures _doDeactivate runs at most once.\n\t\t\t\t\tthis._onDeactivate();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (t !== TEARDOWN && propagatesToMeta(t)) {\n\t\t\t\tthis._propagateToMeta(t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Subclass hook: invoked when INVALIDATE arrives (before `_cached` is\n\t * cleared). {@link NodeImpl} uses this to run the fn cleanup fn and\n\t * drop `_lastDepValues` so the next wave re-runs fn.\n\t */\n\tprotected _onInvalidate(): void {\n\t\t/* no-op default */\n\t}\n\n\t/**\n\t * Subclass hook: invoked when TEARDOWN arrives, before `_onDeactivate`.\n\t * {@link NodeImpl} uses this to run any pending cleanup fn.\n\t */\n\tprotected _onTeardown(): void {\n\t\t/* no-op default */\n\t}\n\n\t/** Forward a signal to all companion meta nodes (best-effort). */\n\tprotected _propagateToMeta(t: symbol): void {\n\t\tfor (const metaNode of Object.values(this.meta)) {\n\t\t\ttry {\n\t\t\t\t// Direct access through NodeBase — meta nodes are always NodeBase instances.\n\t\t\t\t(metaNode as NodeBase)._downInternal([[t]]);\n\t\t\t} catch {\n\t\t\t\t/* best-effort — other meta nodes still receive the signal */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Frame a computed value into the right protocol messages and dispatch\n\t * via `_downInternal`. Used by `_runFn` and `actions.emit`.\n\t */\n\tprotected _downAutoValue(value: unknown): void {\n\t\tconst wasDirty = this._status === \"dirty\";\n\t\tlet unchanged: boolean;\n\t\ttry {\n\t\t\tunchanged = this._cached !== NO_VALUE && this._equals(this._cached, value);\n\t\t} catch (eqErr) {\n\t\t\tconst eqMsg = eqErr instanceof Error ? eqErr.message : String(eqErr);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": equals threw: ${eqMsg}`, {\n\t\t\t\tcause: eqErr,\n\t\t\t});\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\treturn;\n\t\t}\n\t\tif (unchanged) {\n\t\t\tthis._downInternal(wasDirty ? [[RESOLVED]] : [[DIRTY], [RESOLVED]]);\n\t\t\treturn;\n\t\t}\n\t\tthis._downInternal(wasDirty ? [[DATA, value]] : [[DIRTY], [DATA, value]]);\n\t}\n}\n","/**\n * `NodeImpl` — the canonical node primitive for static (compile-time known)\n * dependency graphs. Covers state, producer, derived, effect, operator, and\n * passthrough shapes from a single class.\n *\n * Lifecycle machinery (subscribe + START handshake + `_downInternal` pipeline)\n * lives in {@link NodeBase}. This file only adds:\n * - Dep-wave tracking via pre-set dirty masks (first run and subsequent waves\n * share the same code path — see `_connectUpstream` + `_handleDepMessages`)\n * - `_runFn` with identity-skip optimization on `_lastDepValues`\n * - Producer start/stop tied to sink count\n * - ROM/RAM cache semantics: compute nodes clear `_cached` on disconnect,\n * state sources preserve it (see `_onDeactivate`).\n *\n * See GRAPHREFLY-SPEC §§2.1–2.8 and COMPOSITION-GUIDE §§1, 9.\n */\n\nimport { normalizeActor } from \"./actor.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport {\n\ttype BitSet,\n\tcreateBitSet,\n\tisCleanupFn,\n\tisCleanupResult,\n\tNO_VALUE,\n\ttype Node,\n\ttype NodeActions,\n\tNodeBase,\n\ttype NodeOptions,\n\ttype NodeTransportOptions,\n\ttype SubscribeHints,\n} from \"./node-base.js\";\n\n// Re-exports so downstream files keep importing from \"./node.js\".\nexport {\n\tCLEANUP_RESULT,\n\ttype CleanupResult,\n\tcleanupResult,\n\tNO_VALUE,\n\ttype Node,\n\ttype NodeActions,\n\ttype NodeDescribeKind,\n\ttype NodeInspectorHook,\n\ttype NodeInspectorHookEvent,\n\ttype NodeOptions,\n\ttype NodeSink,\n\ttype NodeStatus,\n\ttype NodeTransportOptions,\n\ttype OnMessageHandler,\n\ttype SubscribeHints,\n} from \"./node-base.js\";\n\n/**\n * Compute function passed to `node(deps, fn, opts?)`.\n *\n * @returns A value to emit, `undefined` to skip emission, or a cleanup\n * function invoked before the next run or on teardown.\n */\nexport type NodeFn<T = unknown> = (\n\tdeps: readonly unknown[],\n\tactions: NodeActions,\n) => T | undefined | (() => void);\n\n// ---------------------------------------------------------------------------\n// NodeImpl\n// ---------------------------------------------------------------------------\n\n/**\n * Class-based implementation of the {@link Node} interface for static deps.\n *\n * All internal state is exposed as package-visible fields so introspection\n * (e.g. `describeNode`) can read them via `instanceof NodeImpl`.\n */\nexport class NodeImpl<T = unknown> extends NodeBase<T> {\n\t// --- Dep configuration (set once) ---\n\t_deps: readonly Node[];\n\t_fn: NodeFn<T> | undefined;\n\t_opts: NodeOptions;\n\t_hasDeps: boolean;\n\t_isSingleDep: boolean;\n\t_autoComplete: boolean;\n\n\t// --- Wave tracking masks ---\n\tprivate _depDirtyMask: BitSet;\n\tprivate _depSettledMask: BitSet;\n\tprivate _depCompleteMask: BitSet;\n\tprivate _allDepsCompleteMask: BitSet;\n\n\t// --- Identity-skip optimization ---\n\tprivate _lastDepValues: readonly unknown[] | undefined;\n\tprivate _cleanup: (() => void) | undefined;\n\n\t// --- Upstream bookkeeping ---\n\tprivate _upstreamUnsubs: Array<() => void> = [];\n\n\t// --- Fn behavior flag ---\n\t/** @internal Read by `describeNode` to infer `\"operator\"` label. */\n\t_manualEmitUsed = false;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn<T> | undefined, opts: NodeOptions) {\n\t\tsuper(opts);\n\t\tthis._deps = deps;\n\t\tthis._fn = fn;\n\t\tthis._opts = opts;\n\t\tthis._hasDeps = deps.length > 0;\n\t\tthis._isSingleDep = deps.length === 1 && fn != null;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\n\t\t// State-with-initial-value starts `settled`; everything else starts\n\t\t// `disconnected` and flips to `pending` at first subscribe if fn\n\t\t// hasn't produced a value yet.\n\t\tif (!this._hasDeps && fn == null && this._cached !== NO_VALUE) {\n\t\t\tthis._status = \"settled\";\n\t\t}\n\n\t\tthis._depDirtyMask = createBitSet(deps.length);\n\t\tthis._depSettledMask = createBitSet(deps.length);\n\t\tthis._depCompleteMask = createBitSet(deps.length);\n\t\tthis._allDepsCompleteMask = createBitSet(deps.length);\n\t\tfor (let i = 0; i < deps.length; i++) this._allDepsCompleteMask.set(i);\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\t// --- Meta node factory (called from base constructor) ---\n\n\tprotected _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node {\n\t\treturn node({\n\t\t\tinitial: initialValue,\n\t\t\tname: `${opts.name ?? \"node\"}:meta:${key}`,\n\t\t\tdescribeKind: \"state\",\n\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t});\n\t}\n\n\t// --- Manual emit tracker (set by actions.down / actions.emit) ---\n\n\tprotected override _onManualEmit(): void {\n\t\tthis._manualEmitUsed = true;\n\t}\n\n\t// --- Up / unsubscribe ---\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tif (options === undefined) {\n\t\t\t\tdep.up?.(messages);\n\t\t\t} else {\n\t\t\t\tdep.up?.(messages, options);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected _upInternal(messages: Messages): void {\n\t\tif (!this._hasDeps) return;\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tif (!this._hasDeps) return;\n\t\tthis._disconnectUpstream();\n\t}\n\n\t// --- Activation (first-subscriber / last-subscriber hooks) ---\n\n\tprotected _onActivate(): void {\n\t\tif (this._hasDeps) {\n\t\t\tthis._connectUpstream();\n\t\t\treturn;\n\t\t}\n\t\tif (this._fn) {\n\t\t\tthis._runFn();\n\t\t\treturn;\n\t\t}\n\t\t// Pure state node: no-op. Cached value (if any) is already delivered\n\t\t// through the subscribe-time START handshake.\n\t}\n\n\tprotected _doDeactivate(): void {\n\t\t// Release upstream subscriptions (for compute nodes with deps).\n\t\tthis._disconnectUpstream();\n\t\t// Flush pending cleanup fn (producers + derived both use `_cleanup`).\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\n\t\t// ROM/RAM rule (GRAPHREFLY-SPEC §2.2): compute nodes (anything with\n\t\t// `fn`) clear their cache on disconnect because their value is a\n\t\t// function of live subscriptions. State nodes (no fn) preserve\n\t\t// `_cached` — runtime writes survive across disconnect.\n\t\tif (this._fn != null) {\n\t\t\tthis._cached = NO_VALUE;\n\t\t\tthis._lastDepValues = undefined;\n\t\t}\n\n\t\t// Status: only transition to \"disconnected\" for compute nodes.\n\t\t// Pure state nodes remain in whatever status they were (usually\n\t\t// \"settled\" if they hold a value).\n\t\tif (this._hasDeps || this._fn != null) {\n\t\t\tthis._status = \"disconnected\";\n\t\t}\n\t}\n\n\t// --- INVALIDATE / TEARDOWN hooks (clear fn state) ---\n\n\tprotected override _onInvalidate(): void {\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\t\tthis._lastDepValues = undefined;\n\t}\n\n\tprotected override _onTeardown(): void {\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tcleanup?.();\n\t}\n\n\t// --- Upstream connect / disconnect ---\n\n\tprivate _connectUpstream(): void {\n\t\tif (!this._hasDeps) return;\n\t\tif (this._upstreamUnsubs.length > 0) return; // already connected\n\n\t\t// Pre-set dirty mask to all-ones — wave completes when every dep\n\t\t// has settled at least once (spec §2.7, first-run gating).\n\t\tthis._depDirtyMask.setAll();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t\t// Stay in \"disconnected\" until fn runs and updates status via\n\t\t// `_handleLocalLifecycle`. `subscribe()` will flip to \"pending\"\n\t\t// if fn did not run before returning.\n\n\t\tconst depValuesBefore = this._lastDepValues;\n\t\tconst subHints: SubscribeHints | undefined = this._isSingleDep\n\t\t\t? { singleDep: true }\n\t\t\t: undefined;\n\t\tfor (let i = 0; i < this._deps.length; i += 1) {\n\t\t\tconst dep = this._deps[i];\n\t\t\tthis._upstreamUnsubs.push(\n\t\t\t\tdep.subscribe((msgs) => this._handleDepMessages(i, msgs), subHints),\n\t\t\t);\n\t\t}\n\t\t// Fallback for `onMessage`-driven operators: if the subscribe loop\n\t\t// did not drive a wave completion (e.g. `concatMap`, `sample` —\n\t\t// operators whose `onMessage` consumes every dep message without\n\t\t// letting the mask-based wave progress), still run fn once so the\n\t\t// operator can initialize side-effect state (inner subscriptions,\n\t\t// cleanup fns, etc.). The fn-is-identity-check guards against\n\t\t// double runs when the normal wave path already fired.\n\t\tif (this._fn && this._onMessage && !this._terminal && this._lastDepValues === depValuesBefore) {\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\tprivate _disconnectUpstream(): void {\n\t\tif (this._upstreamUnsubs.length === 0) return;\n\t\tfor (const unsub of this._upstreamUnsubs.splice(0)) {\n\t\t\tunsub();\n\t\t}\n\t\tthis._depDirtyMask.reset();\n\t\tthis._depSettledMask.reset();\n\t\tthis._depCompleteMask.reset();\n\t}\n\n\t// --- Wave handling ---\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\tfor (const msg of messages) {\n\t\t\tthis._emitInspectorHook({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\t\t\t// User-defined message handler gets first look (spec §2.6).\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tconst consumed = this._onMessage(msg, index, this._actions);\n\t\t\t\t\tif (consumed) {\n\t\t\t\t\t\t// If the operator consumes this dep's subscribe\n\t\t\t\t\t\t// handshake (START), treat the dep as fully\n\t\t\t\t\t\t// user-managed: clear its pre-set dirty bit so the\n\t\t\t\t\t\t// first-run wave gate doesn't block on it.\n\t\t\t\t\t\t// Notifier deps in operators like `takeUntil` rely\n\t\t\t\t\t\t// on this — they're signaling deps, not data deps.\n\t\t\t\t\t\tif (t === START) {\n\t\t\t\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\t\t\t\tthis._runFn();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Tier-0 (START) from a dep is informational — it's the dep's\n\t\t\t// subscribe handshake. It carries no wave-state implication: the\n\t\t\t// paired DATA (if present) is handled by the DATA branch.\n\t\t\tif (messageTier(t) < 1) continue;\n\n\t\t\tif (!this._fn) {\n\t\t\t\t// Passthrough: forward everything except COMPLETE when multi-dep\n\t\t\t\t// (multi-dep passthrough waits for all deps to complete, §1.3.5).\n\t\t\t\tif (t === COMPLETE && this._deps.length > 1) {\n\t\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (t === DIRTY) {\n\t\t\t\tthis._onDepDirty(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._onDepSettled(index);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteMask.set(index);\n\t\t\t\tthis._depDirtyMask.clear(index);\n\t\t\t\tthis._depSettledMask.clear(index);\n\t\t\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\t\t\tthis._depDirtyMask.reset();\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t} else if (!this._depDirtyMask.any() && this._status === \"dirty\") {\n\t\t\t\t\t// D2: dep went DIRTY→COMPLETE without DATA — the node is\n\t\t\t\t\t// stuck in \"dirty\" with no pending wave to resolve it.\n\t\t\t\t\t// Recompute so downstream sees RESOLVED (unchanged) or\n\t\t\t\t\t// DATA (changed).\n\t\t\t\t\tthis._depSettledMask.reset();\n\t\t\t\t\tthis._runFn();\n\t\t\t\t}\n\t\t\t\tthis._maybeCompleteFromDeps();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Forward unknown message types.\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\tprivate _onDepDirty(index: number): void {\n\t\t// Track wave transition: propagate DIRTY to our downstream ONLY on\n\t\t// the first dirty of a wave. During the initial wave, the dirty mask\n\t\t// is pre-set to all-ones by `_connectUpstream` so this branch never\n\t\t// fires — our own `_downAutoValue` emits `[[DIRTY],[DATA,v]]` to\n\t\t// downstream when fn completes.\n\t\tconst wasDirty = this._depDirtyMask.has(index);\n\t\tthis._depDirtyMask.set(index);\n\t\tthis._depSettledMask.clear(index);\n\t\tif (!wasDirty) {\n\t\t\tthis._downInternal([[DIRTY]]);\n\t\t}\n\t}\n\n\tprivate _onDepSettled(index: number): void {\n\t\t// Ensure dep is marked dirty. If the dep settled without a prior\n\t\t// DIRTY (spec §1.3.1 compat path for raw external sources), route\n\t\t// through `_onDepDirty` so that our own downstream sees DIRTY\n\t\t// before the resulting DATA/RESOLVED — preserving the two-phase\n\t\t// invariant from our node's perspective.\n\t\tif (!this._depDirtyMask.has(index)) {\n\t\t\tthis._onDepDirty(index);\n\t\t}\n\t\tthis._depSettledMask.set(index);\n\t\tif (this._depDirtyMask.any() && this._depSettledMask.covers(this._depDirtyMask)) {\n\t\t\tthis._depDirtyMask.reset();\n\t\t\tthis._depSettledMask.reset();\n\t\t\tthis._runFn();\n\t\t}\n\t}\n\n\tprivate _maybeCompleteFromDeps(): void {\n\t\tif (\n\t\t\tthis._autoComplete &&\n\t\t\tthis._deps.length > 0 &&\n\t\t\tthis._depCompleteMask.covers(this._allDepsCompleteMask)\n\t\t) {\n\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t}\n\t}\n\n\t// --- Fn execution ---\n\n\tprivate _runFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._terminal && !this._resubscribable) return;\n\n\t\ttry {\n\t\t\tconst n = this._deps.length;\n\t\t\tconst depValues = new Array(n);\n\t\t\tfor (let i = 0; i < n; i++) depValues[i] = this._deps[i].get();\n\n\t\t\t// Identity skip BEFORE cleanup: if all dep values are unchanged,\n\t\t\t// skip cleanup+fn so effect nodes don't teardown/restart on no-op.\n\t\t\tconst prev = this._lastDepValues;\n\t\t\tif (n > 0 && prev != null && prev.length === n) {\n\t\t\t\tlet allSame = true;\n\t\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\t\tif (!Object.is(depValues[i], prev[i])) {\n\t\t\t\t\t\tallSame = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (allSame) {\n\t\t\t\t\tif (this._status === \"dirty\") {\n\t\t\t\t\t\tthis._downInternal([[RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst prevCleanup = this._cleanup;\n\t\t\tthis._cleanup = undefined;\n\t\t\tprevCleanup?.();\n\n\t\t\tthis._manualEmitUsed = false;\n\t\t\tthis._lastDepValues = depValues;\n\t\t\tthis._emitInspectorHook({ kind: \"run\", depValues });\n\n\t\t\tconst out = this._fn(depValues, this._actions);\n\n\t\t\t// Explicit cleanup wrapper: { cleanup, value? }\n\t\t\tif (isCleanupResult(out)) {\n\t\t\t\tthis._cleanup = out.cleanup;\n\t\t\t\tif (this._manualEmitUsed) return;\n\t\t\t\tif (\"value\" in out) {\n\t\t\t\t\tthis._downAutoValue(out.value);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Legacy: plain function return → cleanup.\n\t\t\tif (isCleanupFn(out)) {\n\t\t\t\tthis._cleanup = out;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this._manualEmitUsed) return;\n\t\t\tif (out === undefined) return;\n\t\t\tthis._downAutoValue(out);\n\t\t} catch (err) {\n\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, { cause: err });\n\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nconst isNodeArray = (value: unknown): value is readonly Node[] => Array.isArray(value);\n\nconst isNodeOptions = (value: unknown): value is NodeOptions =>\n\ttypeof value === \"object\" && value != null && !Array.isArray(value);\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (§2).\n *\n * Typical shapes: `node([])` / `node([], opts)` for a manual source;\n * `node(producerFn, opts)` for a producer; `node(deps, computeFn, opts)` for\n * derived nodes and operators.\n *\n * @param depsOrFn - Dependency nodes, a {@link NodeFn} (producer), or {@link NodeOptions} alone.\n * @param fnOrOpts - With deps: compute function or options. Omitted for producer-only form.\n * @param optsArg - Options when both `deps` and `fn` are provided.\n * @returns `Node<T>` — lazy until subscribed.\n *\n * @remarks\n * **Protocol:** START handshake, DIRTY / DATA / RESOLVED ordering, completion,\n * and batch deferral follow `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n *\n * **`equals` and mutable values:** The default `Object.is` identity check is\n * correct for the common immutable-value case. If your node produces mutable\n * objects, provide a custom `equals` — otherwise `Object.is` always returns\n * `true` for the same reference and the node emits `RESOLVED` instead of `DATA`.\n *\n * **ROM/RAM (§2.2):** State nodes (no fn) preserve their cache across\n * disconnect — runtime writes survive. Compute nodes (derived, producer)\n * clear their cache on disconnect; reconnect re-runs fn.\n *\n * @example\n * ```ts\n * import { node, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = node([a], ([x]) => (x as number) + 1);\n * ```\n *\n * @category core\n */\nexport function node<T = unknown>(\n\tdepsOrFn?: readonly Node[] | NodeFn<T> | NodeOptions,\n\tfnOrOpts?: NodeFn<T> | NodeOptions,\n\toptsArg?: NodeOptions,\n): Node<T> {\n\tconst deps: readonly Node[] = isNodeArray(depsOrFn) ? depsOrFn : [];\n\tconst fn: NodeFn<T> | undefined =\n\t\ttypeof depsOrFn === \"function\"\n\t\t\t? depsOrFn\n\t\t\t: typeof fnOrOpts === \"function\"\n\t\t\t\t? fnOrOpts\n\t\t\t\t: undefined;\n\tlet opts: NodeOptions = {};\n\tif (isNodeArray(depsOrFn)) {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t} else if (isNodeOptions(depsOrFn)) {\n\t\topts = depsOrFn;\n\t} else {\n\t\topts = (isNodeOptions(fnOrOpts) ? fnOrOpts : optsArg) ?? {};\n\t}\n\n\treturn new NodeImpl<T>(deps, fn, opts);\n}\n","import { type Node, type NodeFn, type NodeOptions, node } from \"./node.js\";\n\n/**\n * Creates a manual source with no upstream deps. Emit values with {@link Node.down}.\n *\n * Spec: `state(initial, opts?)` is `node([], { initial, ...opts })` (GRAPHREFLY-SPEC §2.7).\n *\n * @param initial - Initial cached value. Because `initial` is provided, `equals` is\n * called on the first {@link Node.down | down()} emission — if the value matches\n * `initial`, the node emits `RESOLVED` instead of `DATA` (spec §2.5).\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n * @returns `Node<T>` - Stateful node you drive imperatively.\n *\n * @example\n * ```ts\n * import { DATA, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(0);\n * n.down([[DATA, 1]]);\n * ```\n *\n * @category core\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n/**\n * Creates a producer node with no deps; `fn` runs when the first subscriber connects.\n *\n * @param fn - Receives deps (empty) and {@link NodeActions}; use `emit` / `down` to push.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Producer node.\n *\n * @example\n * ```ts\n * import { producer } from \"@graphrefly/graphrefly-ts\";\n *\n * const tick = producer((_d, a) => {\n * a.emit(1);\n * });\n * ```\n *\n * @category core\n */\nexport function producer<T = unknown>(fn: NodeFn<T>, opts?: NodeOptions): Node<T> {\n\treturn node<T>(fn, { describeKind: \"producer\", ...opts });\n}\n\n/**\n * Creates a derived node from dependencies and a compute function (same primitive as operators).\n *\n * @param deps - Upstream nodes.\n * @param fn - Compute function; return value is emitted, or use `actions` explicitly.\n * @param opts - Optional {@link NodeOptions}.\n * @returns `Node<T>` - Derived node.\n *\n * @example\n * ```ts\n * import { derived, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n *\n * @category core\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: NodeFn<T>,\n\topts?: NodeOptions,\n): Node<T> {\n\treturn node<T>(deps, fn, { describeKind: \"derived\", ...opts });\n}\n\n/**\n * Runs a side-effect when deps settle; return value is not auto-emitted.\n *\n * @param deps - Nodes to watch.\n * @param fn - Side-effect body.\n * @returns `Node<unknown>` - Effect node.\n *\n * @example\n * ```ts\n * import { effect, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = state(1);\n * effect([n], ([v]) => {\n * console.log(v);\n * });\n * ```\n *\n * @category core\n */\nexport function effect(deps: readonly Node[], fn: NodeFn<unknown>): Node<unknown> {\n\treturn node(deps, fn, { describeKind: \"effect\" });\n}\n\n/** Unary transform used by {@link pipe} (typically returns a new node wrapping `n`). */\nexport type PipeOperator = (n: Node) => Node;\n\n/**\n * Composes unary operators left-to-right; returns the final node. Does not register a {@link Graph}.\n *\n * @param source - Starting node.\n * @param ops - Each operator maps `Node` to `Node` (curried operators from `extra` use a factory pattern — wrap or use direct calls).\n * @returns `Node` - Result of the last operator.\n *\n * @example\n * ```ts\n * import { filter, map, pipe, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const src = state(1);\n * const out = pipe(\n * src,\n * (n) => map(n, (x) => x + 1),\n * (n) => filter(n, (x) => x > 0),\n * );\n * ```\n *\n * @category core\n */\nexport function pipe(source: Node, ...ops: PipeOperator[]): Node {\n\tlet current = source;\n\tfor (const op of ops) {\n\t\tcurrent = op(current);\n\t}\n\treturn current;\n}\n","/**\n * 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 existingEntries = eventNode.get() as readonly { seq: number }[] | undefined;\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 entries = m[1] as readonly { seq: number }[];\n\t\t\t\t\tfor (const entry of 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","/**\n * `dynamicNode` — runtime dep tracking with diamond resolution (Phase 0.3b).\n *\n * Unlike `node()` where deps are fixed at construction, `dynamicNode`\n * discovers deps at runtime via a tracking `get()` proxy. After each\n * recompute, deps are diffed: new deps are connected, removed deps are\n * disconnected, and bitmasks are rebuilt.\n *\n * Shares subscribe / sink / lifecycle machinery with {@link NodeImpl} via\n * {@link NodeBase}. The only things that diverge from static nodes:\n * - deps are discovered inside `_runFn` via a tracking `get` proxy\n * - `_rewire` installs subscriptions lazily during `_runFn`\n * - during rewire, new dep messages are **buffered** (option C from the\n * Apr-2026 refactor); after rewire we scan the buffer for DATA values\n * that differ from what fn tracked, and re-run fn if any found\n * (bounded by `MAX_RERUN`)\n */\n\nimport { normalizeActor } from \"./actor.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport { node as createNode } from \"./node.js\";\nimport {\n\tNO_VALUE,\n\ttype Node,\n\tNodeBase,\n\ttype NodeOptions,\n\ttype NodeTransportOptions,\n} from \"./node-base.js\";\n\n/**\n * The tracking `get` function passed to `dynamicNode`'s compute function.\n * Each call to `get(dep)` reads the dep's current value and records it as a dependency.\n */\nexport type DynGet = <V>(dep: Node<V>) => V | undefined;\n\n/**\n * Compute function for `dynamicNode`. Receives a tracking `get` proxy.\n * Deps are discovered by which nodes are passed to `get()` during execution.\n */\nexport type DynamicNodeFn<T> = (get: DynGet) => T;\n\n/** Options for `dynamicNode`. */\nexport type DynamicNodeOptions = Pick<\n\tNodeOptions,\n\t| \"name\"\n\t| \"equals\"\n\t| \"meta\"\n\t| \"resubscribable\"\n\t| \"resetOnTeardown\"\n\t| \"guard\"\n\t| \"onMessage\"\n\t| \"onResubscribe\"\n\t| \"completeWhenDepsComplete\"\n\t| \"describeKind\"\n>;\n\n/** Bounded rerun cap for dynamic fn activation loop (lazy-dep stabilization). */\nconst MAX_RERUN = 16;\n\n/**\n * Creates a node with runtime dep tracking. Deps are discovered each time the\n * compute function runs by tracking which nodes are passed to the `get()` proxy.\n *\n * After each recompute:\n * - New deps (not in previous set) are subscribed\n * - Removed deps (not in current set) are unsubscribed\n * - Kept deps retain their existing subscriptions\n *\n * The node participates in diamond resolution via the pre-set dirty mask\n * (shared with {@link NodeImpl}).\n *\n * **Lazy-dep composition:** when a tracked dep is itself a lazy compute node\n * whose first subscribe causes a fresh value to arrive, the rewire buffer\n * detects the discrepancy and re-runs fn once so it observes the real value.\n * Capped at {@link MAX_RERUN} iterations.\n *\n * @param fn - Compute function receiving a tracking `get` proxy.\n * @param opts - Optional configuration.\n * @returns `Node<T>` with dynamic dep tracking.\n *\n * @example\n * ```ts\n * import { dynamicNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const cond = state(true);\n * const a = state(1);\n * const b = state(2);\n *\n * const d = dynamicNode((get) => {\n * const useA = get(cond);\n * return useA ? get(a) : get(b);\n * });\n * ```\n *\n * @category core\n */\nexport function dynamicNode<T = unknown>(fn: DynamicNodeFn<T>, opts?: DynamicNodeOptions): Node<T> {\n\treturn new DynamicNodeImpl<T>(fn, opts ?? {});\n}\n\n/** Pending buffer entry during `_rewire`. */\ntype PendingEntry = { index: number; msgs: Messages };\n\n/** @internal — exported for {@link describeNode} `instanceof` check. */\nexport class DynamicNodeImpl<T = unknown> extends NodeBase<T> {\n\tprivate readonly _fn: DynamicNodeFn<T>;\n\tprivate readonly _autoComplete: boolean;\n\n\t// Dynamic deps tracking\n\t/** @internal Read by `describeNode`. */\n\t_deps: Node[] = [];\n\tprivate _depUnsubs: Array<() => void> = [];\n\tprivate _depIndexMap = new Map<Node, number>();\n\tprivate _depDirtyBits = new Set<number>();\n\tprivate _depSettledBits = new Set<number>();\n\tprivate _depCompleteBits = new Set<number>();\n\n\t// Execution state\n\tprivate _running = false;\n\tprivate _rewiring = false;\n\tprivate _bufferedDepMessages: PendingEntry[] = [];\n\tprivate _trackedValues: Map<Node, unknown> = new Map();\n\tprivate _rerunCount = 0;\n\n\tconstructor(fn: DynamicNodeFn<T>, opts: DynamicNodeOptions) {\n\t\tsuper(opts);\n\t\tthis._fn = fn;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\tprotected _createMetaNode(key: string, initialValue: unknown, opts: NodeOptions): Node {\n\t\treturn createNode({\n\t\t\tinitial: initialValue,\n\t\t\tname: `${opts.name ?? \"dynamicNode\"}:meta:${key}`,\n\t\t\tdescribeKind: \"state\",\n\t\t\t...(opts.guard != null ? { guard: opts.guard } : {}),\n\t\t});\n\t}\n\n\t/** Versioning not supported on DynamicNodeImpl (override base). */\n\toverride get v(): undefined {\n\t\treturn undefined;\n\t}\n\n\t// --- Up / unsubscribe ---\n\n\tup(messages: Messages, options?: NodeTransportOptions): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (!options?.internal && this._guard != null) {\n\t\t\tconst actor = normalizeActor(options?.actor);\n\t\t\tif (!this._guard(actor, \"write\")) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"write\", nodeName: this.name });\n\t\t\t}\n\t\t\tthis._recordMutation(actor);\n\t\t}\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, options);\n\t\t}\n\t}\n\n\tprotected _upInternal(messages: Messages): void {\n\t\tfor (const dep of this._deps) {\n\t\t\tdep.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\tunsubscribe(): void {\n\t\tthis._disconnect();\n\t}\n\n\t// --- Activation hooks ---\n\n\tprotected _onActivate(): void {\n\t\tthis._runFn();\n\t}\n\n\tprotected _doDeactivate(): void {\n\t\tthis._disconnect();\n\t}\n\n\tprivate _disconnect(): void {\n\t\tfor (const unsub of this._depUnsubs) unsub();\n\t\tthis._depUnsubs = [];\n\t\tthis._deps = [];\n\t\tthis._depIndexMap.clear();\n\t\tthis._depDirtyBits.clear();\n\t\tthis._depSettledBits.clear();\n\t\tthis._depCompleteBits.clear();\n\n\t\t// ROM/RAM rule (GRAPHREFLY-SPEC §2.2): compute node clears cache on\n\t\t// disconnect — dynamic nodes are always compute nodes.\n\t\tthis._cached = NO_VALUE;\n\t\tthis._status = \"disconnected\";\n\t}\n\n\t// --- Fn execution with rewire buffer ---\n\n\tprivate _runFn(): void {\n\t\tif (this._terminal && !this._resubscribable) return;\n\t\tif (this._running) return;\n\n\t\tthis._running = true;\n\t\tthis._rerunCount = 0;\n\t\tlet result: T | undefined;\n\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\t// --- Phase 1: execute fn with tracking `get`. ---\n\t\t\t\tconst trackedDeps: Node[] = [];\n\t\t\t\tconst trackedValuesMap = new Map<Node, unknown>();\n\t\t\t\tconst trackedSet = new Set<Node>();\n\n\t\t\t\tconst get: DynGet = <V>(dep: Node<V>): V | undefined => {\n\t\t\t\t\tif (!trackedSet.has(dep)) {\n\t\t\t\t\t\ttrackedSet.add(dep);\n\t\t\t\t\t\ttrackedDeps.push(dep);\n\t\t\t\t\t\t// Spec §2.2: `get()` never triggers computation. If the\n\t\t\t\t\t\t// dep is a disconnected lazy node, this returns\n\t\t\t\t\t\t// undefined — the rewire buffer will detect the\n\t\t\t\t\t\t// discrepancy once the lazy dep's real value arrives\n\t\t\t\t\t\t// via subscribe-time push.\n\t\t\t\t\t\ttrackedValuesMap.set(dep, dep.get());\n\t\t\t\t\t}\n\t\t\t\t\treturn dep.get() as V | undefined;\n\t\t\t\t};\n\n\t\t\t\tthis._trackedValues = trackedValuesMap;\n\n\t\t\t\t// Collect dep values for inspector hook\n\t\t\t\tconst depValues: unknown[] = [];\n\t\t\t\tfor (const dep of this._deps) depValues.push(dep.get());\n\t\t\t\tthis._emitInspectorHook({ kind: \"run\", depValues });\n\n\t\t\t\ttry {\n\t\t\t\t\tresult = this._fn(get);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": fn threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 2: rewire. ---\n\t\t\t\tthis._rewiring = true;\n\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\ttry {\n\t\t\t\t\tthis._rewire(trackedDeps);\n\t\t\t\t} finally {\n\t\t\t\t\tthis._rewiring = false;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 3: scan buffer for discrepancies that require re-run. ---\n\t\t\t\tlet needsRerun = false;\n\t\t\t\tfor (const entry of this._bufferedDepMessages) {\n\t\t\t\t\tfor (const msg of entry.msgs) {\n\t\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\t\tconst dep = this._deps[entry.index];\n\t\t\t\t\t\t\tconst trackedValue = dep != null ? this._trackedValues.get(dep) : undefined;\n\t\t\t\t\t\t\tconst actualValue = msg[1];\n\t\t\t\t\t\t\tif (!this._equals(trackedValue, actualValue)) {\n\t\t\t\t\t\t\t\tneedsRerun = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (needsRerun) break;\n\t\t\t\t}\n\n\t\t\t\tif (needsRerun) {\n\t\t\t\t\tthis._rerunCount += 1;\n\t\t\t\t\tif (this._rerunCount > MAX_RERUN) {\n\t\t\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\t\t\tthis._downInternal([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\tERROR,\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t`dynamicNode \"${this.name ?? \"anonymous\"}\": rewire did not stabilize within ${MAX_RERUN} iterations`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Discard this iteration's buffer and loop.\n\t\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// --- Phase 4: drain buffer — update masks only, no _runFn. ---\n\t\t\t\t//\n\t\t\t\t// Buffered activation-cascade messages are already reflected\n\t\t\t\t// in `_trackedValues` (fn saw the same values). We update\n\t\t\t\t// the wave masks so subsequent dep updates start from a\n\t\t\t\t// consistent state, then clear both masks so the node\n\t\t\t\t// enters post-rewire with clean wave tracking.\n\t\t\t\tconst drain = this._bufferedDepMessages;\n\t\t\t\tthis._bufferedDepMessages = [];\n\t\t\t\tfor (const entry of drain) {\n\t\t\t\t\tfor (const msg of entry.msgs) {\n\t\t\t\t\t\tthis._updateMasksForMessage(entry.index, msg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Clear wave masks — the activation cascade is fully\n\t\t\t\t// consumed; subsequent dep updates should start fresh.\n\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._running = false;\n\t\t}\n\n\t\tthis._downAutoValue(result);\n\t}\n\n\tprivate _rewire(newDeps: Node[]): void {\n\t\tconst oldMap = this._depIndexMap;\n\t\tconst newMap = new Map<Node, number>();\n\t\tconst newUnsubs: Array<() => void> = [];\n\n\t\t// Subscribe to new deps (or reuse existing subscriptions).\n\t\tfor (let i = 0; i < newDeps.length; i++) {\n\t\t\tconst dep = newDeps[i];\n\t\t\tnewMap.set(dep, i);\n\t\t\tconst oldIdx = oldMap.get(dep);\n\t\t\tif (oldIdx !== undefined) {\n\t\t\t\t// Kept dep — reuse subscription.\n\t\t\t\tnewUnsubs.push(this._depUnsubs[oldIdx]);\n\t\t\t\tthis._depUnsubs[oldIdx] = () => {};\n\t\t\t} else {\n\t\t\t\t// New dep — subscribe. Its subscribe-time handshake +\n\t\t\t\t// activation cascade will land in `_handleDepMessages`,\n\t\t\t\t// which routes to the buffer while `_rewiring` is true.\n\t\t\t\tconst idx = i;\n\t\t\t\tconst unsub = dep.subscribe((msgs) => this._handleDepMessages(idx, msgs));\n\t\t\t\tnewUnsubs.push(unsub);\n\t\t\t}\n\t\t}\n\n\t\t// Disconnect removed deps.\n\t\tfor (const [dep, oldIdx] of oldMap) {\n\t\t\tif (!newMap.has(dep)) {\n\t\t\t\tthis._depUnsubs[oldIdx]();\n\t\t\t}\n\t\t}\n\n\t\tthis._deps = newDeps;\n\t\tthis._depUnsubs = newUnsubs;\n\t\tthis._depIndexMap = newMap;\n\t\tthis._depDirtyBits.clear();\n\t\tthis._depSettledBits.clear();\n\n\t\t// Preserve complete bits for deps that are still present (re-indexed).\n\t\tconst newCompleteBits = new Set<number>();\n\t\tfor (const oldIdx of this._depCompleteBits) {\n\t\t\tfor (const [dep, idx] of oldMap) {\n\t\t\t\tif (idx === oldIdx && newMap.has(dep)) {\n\t\t\t\t\tnewCompleteBits.add(newMap.get(dep)!);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis._depCompleteBits = newCompleteBits;\n\t}\n\n\t// --- Dep message handling ---\n\n\tprivate _handleDepMessages(index: number, messages: Messages): void {\n\t\t// During rewire, buffer messages for post-rewire scan.\n\t\tif (this._rewiring) {\n\t\t\tthis._bufferedDepMessages.push({ index, msgs: messages });\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const msg of messages) {\n\t\t\tthis._emitInspectorHook({ kind: \"dep_message\", depIndex: index, message: msg });\n\t\t\tconst t = msg[0];\n\n\t\t\t// Note: unlike NodeImpl, we do NOT clear dirty bits when onMessage\n\t\t\t// consumes START. NodeImpl pre-sets all dirty bits in _connectUpstream\n\t\t\t// and must clear them for consumed-START deps (notifier pattern).\n\t\t\t// DynamicNodeImpl never pre-sets dirty bits — deps are discovered\n\t\t\t// lazily during _runFn — so there are no bits to clear.\n\t\t\tif (this._onMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tif (this._onMessage(msg, index, this._actions)) continue;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst wrapped = new Error(`Node \"${this.name}\": onMessage threw: ${errMsg}`, {\n\t\t\t\t\t\tcause: err,\n\t\t\t\t\t});\n\t\t\t\t\tthis._downInternal([[ERROR, wrapped]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Tier-0 (START) from a dep is informational — see NodeImpl for rationale.\n\t\t\tif (messageTier(t) < 1) continue;\n\n\t\t\tif (t === DIRTY) {\n\t\t\t\tconst wasEmpty = this._depDirtyBits.size === 0;\n\t\t\t\tthis._depDirtyBits.add(index);\n\t\t\t\tthis._depSettledBits.delete(index);\n\t\t\t\tif (wasEmpty) {\n\t\t\t\t\tthis._downInternal([[DIRTY]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tif (!this._depDirtyBits.has(index)) {\n\t\t\t\t\t// DATA-without-prior-DIRTY — propagate DIRTY for the two-phase\n\t\t\t\t\t// invariant (§1.3.1 compat path).\n\t\t\t\t\tconst wasEmpty = this._depDirtyBits.size === 0;\n\t\t\t\t\tthis._depDirtyBits.add(index);\n\t\t\t\t\tif (wasEmpty) {\n\t\t\t\t\t\tthis._downInternal([[DIRTY]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._depSettledBits.add(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\t\tif (!this._running) {\n\t\t\t\t\t\t// Identity check against the values fn already saw — if\n\t\t\t\t\t\t// nothing has actually changed, skip the run. This\n\t\t\t\t\t\t// guards against deferred handshake DATA (arriving\n\t\t\t\t\t\t// after `_rewire` finishes inside an open batch)\n\t\t\t\t\t\t// from triggering a redundant re-run.\n\t\t\t\t\t\tif (this._depValuesDifferFromTracked()) {\n\t\t\t\t\t\t\tthis._runFn();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === COMPLETE) {\n\t\t\t\tthis._depCompleteBits.add(index);\n\t\t\t\tthis._depDirtyBits.delete(index);\n\t\t\t\tthis._depSettledBits.delete(index);\n\t\t\t\tif (this._allDirtySettled()) {\n\t\t\t\t\tthis._depDirtyBits.clear();\n\t\t\t\t\tthis._depSettledBits.clear();\n\t\t\t\t\tif (!this._running) this._runFn();\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tthis._autoComplete &&\n\t\t\t\t\tthis._depCompleteBits.size >= this._deps.length &&\n\t\t\t\t\tthis._deps.length > 0\n\t\t\t\t) {\n\t\t\t\t\tthis._downInternal([[COMPLETE]]);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === ERROR) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (t === INVALIDATE || t === TEARDOWN || t === PAUSE || t === RESUME) {\n\t\t\t\tthis._downInternal([msg]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._downInternal([msg]);\n\t\t}\n\t}\n\n\t/**\n\t * Update dep masks for a message without triggering `_runFn` — used\n\t * during post-rewire drain so the wave state is consistent with the\n\t * buffered activation cascade without recursing.\n\t */\n\tprivate _updateMasksForMessage(index: number, msg: Messages[number]): void {\n\t\tconst t = msg[0];\n\t\tif (t === DIRTY) {\n\t\t\tthis._depDirtyBits.add(index);\n\t\t\tthis._depSettledBits.delete(index);\n\t\t} else if (t === DATA || t === RESOLVED) {\n\t\t\tthis._depDirtyBits.add(index);\n\t\t\tthis._depSettledBits.add(index);\n\t\t} else if (t === COMPLETE) {\n\t\t\tthis._depCompleteBits.add(index);\n\t\t\tthis._depDirtyBits.delete(index);\n\t\t\tthis._depSettledBits.delete(index);\n\t\t}\n\t}\n\n\tprivate _allDirtySettled(): boolean {\n\t\tif (this._depDirtyBits.size === 0) return false;\n\t\tfor (const idx of this._depDirtyBits) {\n\t\t\tif (!this._depSettledBits.has(idx)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * True if any current dep value differs from what the last `_runFn`\n\t * saw via `get()`. Used to suppress redundant re-runs when deferred\n\t * handshake messages arrive after `_rewire` for a dep whose value\n\t * already matches `_trackedValues`.\n\t */\n\tprivate _depValuesDifferFromTracked(): boolean {\n\t\tfor (const dep of this._deps) {\n\t\t\tconst current = dep.get();\n\t\t\tconst tracked = this._trackedValues.get(dep);\n\t\t\tif (!this._equals(current, tracked)) return true;\n\t\t}\n\t\treturn false;\n\t}\n}\n","import type { Actor } from \"./actor.js\";\nimport { DynamicNodeImpl } from \"./dynamic-node.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { NO_VALUE, type Node, NodeImpl } from \"./node.js\";\n\n/** JSON-shaped slice of a node for Phase 1 `Graph.describe()` (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type DescribeNodeOutput = {\n\ttype: \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\";\n\tstatus?: Node[\"status\"];\n\tdeps: string[];\n\tmeta?: Record<string, unknown>;\n\tname?: string;\n\tvalue?: unknown;\n\t/** True when the node has never received or been initialized with a value (cache holds SENTINEL). */\n\tsentinel?: boolean;\n\t/** Node versioning info (GRAPHREFLY-SPEC §7). Present only when versioning is enabled. */\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\n\t/** Guard info (full detail). */\n\tguard?: string;\n\t/** Last mutation attribution (full detail). */\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n};\n\n/**\n * Detail level for `describe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — type + deps only (default). LLM-friendly.\n * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`).\n * - `\"full\"` — standard + guard, lastMutation.\n */\nexport type DescribeDetail = \"minimal\" | \"standard\" | \"full\";\n\n/**\n * Valid field names for `describe({ fields: [...] })` (Phase 3.3b).\n * Dotted paths like `\"meta.label\"` select specific meta keys.\n */\nexport type DescribeField =\n\t| \"type\"\n\t| \"status\"\n\t| \"value\"\n\t| \"deps\"\n\t| \"meta\"\n\t| \"v\"\n\t| \"guard\"\n\t| \"lastMutation\"\n\t| `meta.${string}`;\n\n/** Resolve which fields to include based on detail level or explicit field list. */\nexport function resolveDescribeFields(\n\tdetail?: DescribeDetail,\n\tfields?: readonly DescribeField[],\n): Set<string> | null {\n\t// Explicit fields override detail level\n\tif (fields != null && fields.length > 0) return new Set(fields);\n\tswitch (detail) {\n\t\tcase \"standard\":\n\t\t\treturn new Set([\"type\", \"status\", \"value\", \"deps\", \"meta\", \"v\"]);\n\t\tcase \"full\":\n\t\t\treturn null; // null = include everything\n\t\tdefault:\n\t\t\treturn new Set([\"type\", \"deps\"]);\n\t}\n}\n\nfunction inferDescribeType(n: NodeImpl): DescribeNodeOutput[\"type\"] {\n\tif (n._describeKind != null) return n._describeKind;\n\tif (!n._hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\tif (n._fn == null) return \"derived\";\n\tif (n._manualEmitUsed) return \"operator\";\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON (GRAPHREFLY-SPEC §2.3, §3.6).\n *\n * @remarks\n * Values come from {@link Node.get}, which returns the **last settled** cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status` when\n * freshness matters. Avoid calling mid-batch for the same reason.\n *\n * Meta nodes are **not** terminated when their parent receives COMPLETE or\n * ERROR — they remain writable so callers can record post-mortem metadata\n * (e.g. `meta.error`). They *are* torn down when the parent receives TEARDOWN.\n *\n * @param node - The node whose meta fields to snapshot.\n * @returns Plain object of `{ key: value }` pairs (empty if no meta defined).\n * Keys whose companion node's {@link Node.get} throws are omitted.\n *\n * @example\n * ```ts\n * import { core } from \"@graphrefly/graphrefly-ts\";\n *\n * const n = core.node({ initial: 0, meta: { tag: \"a\" } });\n * core.metaSnapshot(n); // { tag: \"a\" }\n * ```\n */\n/** @internal Used by {@link describeNode} — not part of the public API. */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.get();\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta` snapshot).\n * Parity with graphrefly-py `describe_node`.\n *\n * `type` is inferred from factory configuration, optional `describeKind` in node options,\n * and the last `manualEmitUsed` hint (operator vs derived). {@link effect} sets\n * `describeKind: \"effect\"`. Nodes not created by {@link node} fall back to `type: \"state\"` and empty `deps`.\n *\n * @param node - Any `Node` to introspect.\n * @returns `DescribeNodeOutput` suitable for merging into graph describe maps.\n *\n * @example\n * ```ts\n * import { describeNode, state } from \"@graphrefly/graphrefly-ts\";\n *\n * describeNode(state(0));\n * ```\n */\n/**\n * Builds a single-node slice for `Graph.describe()`.\n *\n * @param node - Node to introspect.\n * @param includeFields - Set of fields to include, or `null` for all. When omitted, all fields are included (legacy behavior).\n */\n/** @internal Used by {@link Graph.describe} — not part of the public API. */\nexport function describeNode(node: Node, includeFields?: Set<string> | null): DescribeNodeOutput {\n\tconst all = includeFields == null; // null or undefined → include everything\n\n\t// Specific meta keys requested via dotted paths (e.g. \"meta.label\")\n\tconst metaKeys: string[] | null =\n\t\t!all && includeFields != null\n\t\t\t? [...includeFields].filter((f) => f.startsWith(\"meta.\")).map((f) => f.slice(5))\n\t\t\t: null;\n\tconst wantsMeta = all || includeFields!.has(\"meta\") || (metaKeys != null && metaKeys.length > 0);\n\n\tlet type: DescribeNodeOutput[\"type\"] = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.name ?? \"\");\n\t} else if (node instanceof DynamicNodeImpl) {\n\t\ttype = node._describeKind ?? \"derived\";\n\t\tdeps = [];\n\t}\n\n\tconst out: DescribeNodeOutput = { type, deps };\n\n\t// status\n\tif (all || includeFields!.has(\"status\")) {\n\t\tout.status = node.status;\n\t}\n\n\t// Resolve guard once — used by both meta.access hint and standalone guard field\n\tconst guard =\n\t\t(node instanceof NodeImpl && node._guard) ||\n\t\t(node instanceof DynamicNodeImpl && node._guard) ||\n\t\tundefined;\n\n\t// meta\n\tif (wantsMeta) {\n\t\tconst rawMeta: Record<string, unknown> = { ...metaSnapshot(node) };\n\t\tif (guard != null && rawMeta.access === undefined) {\n\t\t\trawMeta.access = accessHintForGuard(guard);\n\t\t}\n\n\t\tif (metaKeys != null && metaKeys.length > 0 && !includeFields!.has(\"meta\")) {\n\t\t\t// Only specific meta keys\n\t\t\tconst filtered: Record<string, unknown> = {};\n\t\t\tfor (const k of metaKeys) {\n\t\t\t\tif (k in rawMeta) filtered[k] = rawMeta[k];\n\t\t\t}\n\t\t\tout.meta = filtered;\n\t\t} else {\n\t\t\tout.meta = rawMeta;\n\t\t}\n\t}\n\n\t// name (always include when present — it's identity, not detail)\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\t// value + sentinel indicator\n\tif (all || includeFields!.has(\"value\")) {\n\t\tconst isSentinel =\n\t\t\t(node instanceof NodeImpl && node._cached === NO_VALUE) ||\n\t\t\t(node instanceof DynamicNodeImpl && node._cached === NO_VALUE);\n\t\tif (isSentinel) {\n\t\t\tout.sentinel = true;\n\t\t}\n\t\ttry {\n\t\t\tout.value = node.get();\n\t\t} catch {\n\t\t\t/* omit value */\n\t\t}\n\t}\n\n\t// Versioning (GRAPHREFLY-SPEC §7)\n\tif ((all || includeFields!.has(\"v\")) && node.v != null) {\n\t\tconst vInfo: DescribeNodeOutput[\"v\"] = { id: node.v.id, version: node.v.version };\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo!.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo!.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\t// Guard info (full detail)\n\tif (all || includeFields!.has(\"guard\")) {\n\t\tif (guard != null) {\n\t\t\tout.guard = accessHintForGuard(guard);\n\t\t}\n\t}\n\n\t// Last mutation attribution (full detail)\n\tif (all || includeFields!.has(\"lastMutation\")) {\n\t\tif (node.lastMutation != null) {\n\t\t\tout.lastMutation = node.lastMutation;\n\t\t}\n\t}\n\n\treturn out;\n}\n","/**\n * Approximate in-memory size estimation for arbitrary JS values.\n *\n * Uses a recursive walk with cycle detection. Not exact — provides a\n * reasonable approximation for profiling and hotspot detection.\n *\n * @module\n * @internal\n */\n\n/** Approximate per-type overhead in bytes (V8 heuristics). */\nconst OVERHEAD = {\n\tobject: 56,\n\tarray: 64,\n\tstring: 40, // header; content added separately\n\tnumber: 8,\n\tboolean: 4,\n\tnull: 0,\n\tundefined: 0,\n\tsymbol: 40,\n\tbigint: 16,\n\tfunction: 120,\n\tmap: 72,\n\tset: 72,\n\tmapEntry: 40,\n\tsetEntry: 24,\n} as const;\n\n/**\n * Estimate the approximate retained memory (in bytes) of a JS value.\n *\n * Handles primitives, plain objects, arrays, Maps, Sets, and nested\n * combinations. Uses a `WeakSet` for cycle detection — cyclic refs\n * are counted once.\n *\n * @param value - The value to measure.\n * @returns Approximate size in bytes.\n */\nexport function sizeof(value: unknown): number {\n\tconst seen = new WeakSet();\n\treturn _sizeof(value, seen);\n}\n\nfunction _sizeof(value: unknown, seen: WeakSet<WeakKey>): number {\n\tif (value == null) return 0;\n\n\tconst t = typeof value;\n\n\tswitch (t) {\n\t\tcase \"number\":\n\t\t\treturn OVERHEAD.number;\n\t\tcase \"boolean\":\n\t\t\treturn OVERHEAD.boolean;\n\t\tcase \"string\":\n\t\t\treturn OVERHEAD.string + (value as string).length * 2; // UTF-16\n\t\tcase \"bigint\":\n\t\t\treturn OVERHEAD.bigint;\n\t\tcase \"symbol\":\n\t\t\treturn OVERHEAD.symbol;\n\t\tcase \"function\":\n\t\t\tif (seen.has(value as object)) return 0;\n\t\t\tseen.add(value as object);\n\t\t\treturn OVERHEAD.function;\n\t\tcase \"undefined\":\n\t\t\treturn 0;\n\t}\n\n\t// Object types — cycle detection\n\tconst obj = value as object;\n\tif (seen.has(obj)) return 0;\n\tseen.add(obj);\n\n\tif (obj instanceof Map) {\n\t\tlet size = OVERHEAD.map;\n\t\tfor (const [k, v] of obj) {\n\t\t\tsize += OVERHEAD.mapEntry + _sizeof(k, seen) + _sizeof(v, seen);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (obj instanceof Set) {\n\t\tlet size = OVERHEAD.set;\n\t\tfor (const v of obj) {\n\t\t\tsize += OVERHEAD.setEntry + _sizeof(v, seen);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\tlet size = OVERHEAD.array + obj.length * 8; // pointer slots\n\t\tfor (const item of obj) {\n\t\t\tsize += _sizeof(item, seen);\n\t\t}\n\t\treturn size;\n\t}\n\n\t// ArrayBuffer / TypedArray\n\tif (obj instanceof ArrayBuffer) return obj.byteLength;\n\tif (ArrayBuffer.isView(obj)) return (obj as { byteLength: number }).byteLength;\n\n\t// Plain object\n\tlet size = OVERHEAD.object;\n\tconst keys = Object.keys(obj);\n\tfor (const key of keys) {\n\t\tsize += OVERHEAD.string + key.length * 2; // key\n\t\tsize += _sizeof((obj as Record<string, unknown>)[key], seen);\n\t}\n\treturn size;\n}\n","/**\n * Graph profiling and inspection utilities.\n *\n * Provides per-node memory estimation, connectivity stats, and hotspot\n * detection. Non-invasive — reads from `describe()` and node internals\n * without modifying state.\n *\n * @module\n */\n\nimport { NodeImpl } from \"../core/node.js\";\nimport type { Graph, GraphDescribeOutput } from \"./graph.js\";\nimport { sizeof } from \"./sizeof.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Per-node profile entry. */\nexport interface NodeProfile {\n\t/** Qualified path within the graph. */\n\tpath: string;\n\t/** Node type (state, derived, producer, effect). */\n\ttype: string;\n\t/** Node status (disconnected, dirty, settled, errored, completed). */\n\tstatus: string;\n\t/** Approximate retained bytes for the node's cached value. */\n\tvalueSizeBytes: number;\n\t/** Number of downstream subscribers (sinks). */\n\tsubscriberCount: number;\n\t/** Number of upstream dependencies. */\n\tdepCount: number;\n\t/** True if this is an effect node with no external subscribers (potential leak). */\n\tisOrphanEffect: boolean;\n}\n\n/** Aggregate graph profile. */\nexport interface GraphProfileResult {\n\t/** Total node count. */\n\tnodeCount: number;\n\t/** Total edge count. */\n\tedgeCount: number;\n\t/** Subgraph count. */\n\tsubgraphCount: number;\n\t/** All node profiles. */\n\tnodes: NodeProfile[];\n\t/** Total approximate value memory across all nodes. */\n\ttotalValueSizeBytes: number;\n\t/** Nodes sorted by valueSizeBytes descending (top N). */\n\thotspots: NodeProfile[];\n\t/** Effect nodes with no external subscribers (potential leaks). */\n\torphanEffects: NodeProfile[];\n}\n\n/** Options for {@link graphProfile}. */\nexport interface GraphProfileOptions {\n\t/** Limit hotspot list (default 10). */\n\ttopN?: number;\n\t/** Include subgraph nodes recursively (default true). */\n\trecursive?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Profile a graph's memory and connectivity characteristics.\n *\n * Uses `describe({ detail: \"standard\" })` for node metadata and direct\n * `NodeImpl` access for subscriber counts and cached values.\n *\n * @param graph - The graph to profile.\n * @param opts - Optional configuration.\n * @returns Aggregate profile with per-node details and hotspots.\n */\nexport function graphProfile(graph: Graph, opts?: GraphProfileOptions): GraphProfileResult {\n\tconst topN = opts?.topN ?? 10;\n\n\tconst desc: GraphDescribeOutput = graph.describe({ detail: \"standard\" });\n\n\t// Build path→Node lookup via _collectObserveTargets (same as describe uses).\n\t// Runtime guard: if the internal method is missing (refactored), degrade\n\t// gracefully — profiles will show 0 for valueSizeBytes and subscriberCount.\n\tconst targets: [string, import(\"../core/node.js\").Node][] = [];\n\tif (typeof (graph as any)._collectObserveTargets === \"function\") {\n\t\t(graph as any)._collectObserveTargets(\"\", targets);\n\t}\n\tconst pathToNode = new Map<string, import(\"../core/node.js\").Node>();\n\tfor (const [p, n] of targets) {\n\t\tpathToNode.set(p, n);\n\t}\n\n\tconst profiles: NodeProfile[] = [];\n\n\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\tconst nd = pathToNode.get(path);\n\t\tconst impl = nd instanceof NodeImpl ? nd : null;\n\n\t\tconst valueSizeBytes = impl ? sizeof(impl.get()) : 0;\n\t\tconst subscriberCount = impl ? impl._sinkCount : 0;\n\t\tconst depCount = nodeDesc.deps?.length ?? 0;\n\n\t\tconst isOrphanEffect = nodeDesc.type === \"effect\" && subscriberCount === 0;\n\n\t\tprofiles.push({\n\t\t\tpath,\n\t\t\ttype: nodeDesc.type,\n\t\t\tstatus: nodeDesc.status ?? \"unknown\",\n\t\t\tvalueSizeBytes,\n\t\t\tsubscriberCount,\n\t\t\tdepCount,\n\t\t\tisOrphanEffect,\n\t\t});\n\t}\n\n\tconst totalValueSizeBytes = profiles.reduce((sum, p) => sum + p.valueSizeBytes, 0);\n\n\tconst hotspots = [...profiles].sort((a, b) => b.valueSizeBytes - a.valueSizeBytes).slice(0, topN);\n\n\tconst orphanEffects = profiles.filter((p) => p.isOrphanEffect);\n\n\treturn {\n\t\tnodeCount: profiles.length,\n\t\tedgeCount: desc.edges.length,\n\t\tsubgraphCount: desc.subgraphs.length,\n\t\tnodes: profiles,\n\t\ttotalValueSizeBytes,\n\t\thotspots,\n\t\torphanEffects,\n\t};\n}\n","import type { Actor } from \"../core/actor.js\";\nimport { isBatching } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { GuardDenied } from \"../core/guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tmessageTier,\n\tRESOLVED,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport {\n\ttype DescribeDetail,\n\ttype DescribeField,\n\ttype DescribeNodeOutput,\n\tdescribeNode,\n\tresolveDescribeFields,\n} from \"../core/meta.js\";\nimport {\n\ttype Node,\n\tNodeImpl,\n\ttype NodeInspectorHookEvent,\n\ttype NodeSink,\n\ttype NodeTransportOptions,\n} from \"../core/node.js\";\nimport { state as stateNode } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\nimport { type GraphProfileOptions, type GraphProfileResult, graphProfile } from \"./profile.js\";\n\n/** The separator used for qualified paths in {@link Graph.resolve} et al. */\nconst PATH_SEP = \"::\";\n\n/**\n * Reserved segment for meta companion paths: `nodeName::__meta__::metaKey` (GRAPHREFLY-SPEC §3.6).\n * Forbidden as a local node or mount name.\n */\nexport const GRAPH_META_SEGMENT = \"__meta__\";\n\n/** Options for {@link Graph} (reserved for future hooks). */\nexport type GraphOptions = Record<string, unknown>;\n\n/** Filter for {@link Graph.describe} — object-style partial match or predicate. */\nexport type DescribeFilter =\n\t| Partial<Pick<DescribeNodeOutput, \"type\" | \"status\">>\n\t| {\n\t\t\ttype?: DescribeNodeOutput[\"type\"];\n\t\t\tstatus?: DescribeNodeOutput[\"status\"];\n\t\t\t/** Keep nodes whose `deps` includes this qualified path. */\n\t\t\tdepsIncludes?: string;\n\t\t\t/** Snake-case alias for `depsIncludes` (Python parity). */\n\t\t\tdeps_includes?: string;\n\t\t\t/** Keep nodes whose `meta` contains this key. */\n\t\t\tmetaHas?: string;\n\t\t\t/** Snake-case alias for `metaHas` (Python parity). */\n\t\t\tmeta_has?: string;\n\t }\n\t| ((node: DescribeNodeOutput) => boolean)\n\t| ((nodePath: string, node: DescribeNodeOutput) => boolean);\n\n/** Options for {@link Graph.signal} and {@link Graph.set} (actor context, internal lifecycle). */\nexport type GraphActorOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips node guards (graph lifecycle TEARDOWN, unmount teardown, etc.).\n\t */\n\tinternal?: boolean;\n};\n\n/** Options for {@link Graph.describe} (Phase 3.3b progressive disclosure). */\nexport type GraphDescribeOptions = {\n\tactor?: Actor;\n\t/**\n\t * Node filter. Filters operate on whatever fields the chosen `detail` level\n\t * provides. For `metaHas` and `status` filters, use `detail: \"standard\"` or\n\t * higher — at `\"minimal\"` those fields are absent and the filter silently\n\t * excludes all nodes.\n\t */\n\tfilter?: DescribeFilter;\n\t/**\n\t * Detail level (Phase 3.3b). Default: `\"minimal\"`.\n\t * - `\"minimal\"` — type + deps only\n\t * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`)\n\t * - `\"full\"` — standard + guard, lastMutation\n\t */\n\tdetail?: DescribeDetail;\n\t/**\n\t * Explicit field selection (GraphQL-style). Overrides `detail` when provided.\n\t * Dotted paths like `\"meta.label\"` select specific meta keys.\n\t */\n\tfields?: DescribeField[];\n\t/**\n\t * Output format (Phase 3.3b).\n\t * - `undefined` — normal describe output\n\t * - `\"spec\"` — GraphSpec input format (no status, no value, deps as edges, type labels)\n\t */\n\tformat?: \"spec\";\n};\n\n/** JSON snapshot from {@link Graph.describe} (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type GraphDescribeOutput = {\n\tname: string;\n\tnodes: Record<string, DescribeNodeOutput>;\n\tedges: ReadonlyArray<{ from: string; to: string }>;\n\tsubgraphs: string[];\n\t/**\n\t * Re-read the live graph with higher detail (Phase 3.3b).\n\t * Returns a new `GraphDescribeOutput`; the original remains a snapshot.\n\t * Present on live describe results; absent on deserialized snapshots.\n\t */\n\texpand?: (detailOrFields: DescribeDetail | DescribeField[]) => GraphDescribeOutput;\n};\n\n/**\n * Persisted graph snapshot: {@link GraphDescribeOutput} plus optional format version\n * ({@link Graph.snapshot}, {@link Graph.restore}, {@link Graph.fromSnapshot}, {@link Graph.toObject},\n * {@link Graph.toJSONString} — §3.8).\n */\nexport type GraphPersistSnapshot = GraphDescribeOutput & {\n\tversion?: number;\n};\n\nexport type GraphFactoryContext = {\n\tpath: string;\n\ttype: DescribeNodeOutput[\"type\"];\n\tvalue: unknown;\n\tmeta: Record<string, unknown>;\n\tdeps: readonly string[];\n\tresolvedDeps: readonly Node[];\n};\n\nexport type GraphNodeFactory = (name: string, context: GraphFactoryContext) => Node;\n\n/** @deprecated Use `CheckpointAdapter` from `extra/checkpoint` instead. */\nexport type AutoCheckpointAdapter = {\n\tsave(key: string, data: unknown): void;\n};\n\nexport type GraphCheckpointRecord =\n\t| { mode: \"full\"; snapshot: GraphPersistSnapshot; seq: number }\n\t| { mode: \"diff\"; diff: GraphDiffResult; snapshot: GraphPersistSnapshot; seq: number };\n\nexport type GraphAutoCheckpointOptions = {\n\tdebounceMs?: number;\n\tcompactEvery?: number;\n\tfilter?: (name: string, described: DescribeNodeOutput) => boolean;\n\tonError?: (error: unknown) => void;\n};\n\nexport type GraphAutoCheckpointHandle = {\n\tdispose(): void;\n};\n\n/** Direction options for diagram export helpers. */\nexport type GraphDiagramDirection = \"TD\" | \"LR\" | \"BT\" | \"RL\";\n\n/** Options for {@link Graph.toMermaid} / {@link Graph.toD2}. */\nexport type GraphDiagramOptions = {\n\t/**\n\t * Diagram flow direction.\n\t * - `TD`: top-down\n\t * - `LR`: left-right (default)\n\t * - `BT`: bottom-top\n\t * - `RL`: right-left\n\t */\n\tdirection?: GraphDiagramDirection;\n};\n\n/** Snapshot format version (§3.8). */\nconst SNAPSHOT_VERSION = 1;\n\n/**\n * Validate the snapshot envelope: version, required keys, types. Aligned with\n * Python `_parse_snapshot_envelope`. Throws on invalid data.\n */\nfunction parseSnapshotEnvelope(data: GraphPersistSnapshot): void {\n\tif (data.version !== SNAPSHOT_VERSION) {\n\t\tthrow new Error(\n\t\t\t`unsupported snapshot version ${String(data.version)} (expected ${SNAPSHOT_VERSION})`,\n\t\t);\n\t}\n\tfor (const key of [\"name\", \"nodes\", \"edges\", \"subgraphs\"] as const) {\n\t\tif (!(key in data)) {\n\t\t\tthrow new Error(`snapshot missing required key \"${key}\"`);\n\t\t}\n\t}\n\tif (typeof data.name !== \"string\") {\n\t\tthrow new TypeError(`snapshot 'name' must be a string`);\n\t}\n\tif (typeof data.nodes !== \"object\" || data.nodes === null || Array.isArray(data.nodes)) {\n\t\tthrow new TypeError(`snapshot 'nodes' must be an object`);\n\t}\n\tif (!Array.isArray(data.edges)) {\n\t\tthrow new TypeError(`snapshot 'edges' must be an array`);\n\t}\n\tif (!Array.isArray(data.subgraphs)) {\n\t\tthrow new TypeError(`snapshot 'subgraphs' must be an array`);\n\t}\n}\n\n/** Recursively sort object keys for deterministic JSON (git-diffable). */\nfunction sortJsonValue(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sortJsonValue);\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\tconst out: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tout[k] = sortJsonValue(obj[k]);\n\t}\n\treturn out;\n}\n\nfunction stableJsonStringify(value: unknown): string {\n\treturn `${JSON.stringify(sortJsonValue(value))}\\n`;\n}\n\nfunction escapeMermaidLabel(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction escapeD2Label(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction d2DirectionFromGraphDirection(direction: GraphDiagramDirection): string {\n\tif (direction === \"TD\") return \"down\";\n\tif (direction === \"BT\") return \"up\";\n\tif (direction === \"RL\") return \"left\";\n\treturn \"right\";\n}\n\n/** Collect deduplicated (from, to) arrows from deps + edges. */\nfunction collectDiagramArrows(described: GraphDescribeOutput): [string, string][] {\n\tconst seen = new Set<string>();\n\tconst arrows: [string, string][] = [];\n\tfunction add(from: string, to: string): void {\n\t\tconst key = `${from}\\0${to}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tarrows.push([from, to]);\n\t}\n\tfor (const [path, info] of Object.entries(described.nodes)) {\n\t\tconst deps: string[] | undefined = (info as Record<string, unknown>).deps as\n\t\t\t| string[]\n\t\t\t| undefined;\n\t\tif (deps) {\n\t\t\tfor (const dep of deps) add(dep, path);\n\t\t}\n\t}\n\tfor (const edge of described.edges) add(edge.from, edge.to);\n\treturn arrows;\n}\n\nfunction normalizeDiagramDirection(direction: unknown): GraphDiagramDirection {\n\tif (direction === undefined) return \"LR\";\n\tif (direction === \"TD\" || direction === \"LR\" || direction === \"BT\" || direction === \"RL\") {\n\t\treturn direction;\n\t}\n\tthrow new Error(\n\t\t`invalid diagram direction ${String(direction)}; expected one of: TD, LR, BT, RL`,\n\t);\n}\n\nfunction escapeRegexLiteral(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet re = \"^\";\n\tfor (let i = 0; i < pattern.length; i += 1) {\n\t\tconst ch = pattern[i]!;\n\t\tif (ch === \"*\") {\n\t\t\tre += \".*\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"?\") {\n\t\t\tre += \".\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tconst end = pattern.indexOf(\"]\", i + 1);\n\t\t\tif (end <= i + 1) {\n\t\t\t\tre += \"\\\\[\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet cls = pattern.slice(i + 1, end);\n\t\t\tif (cls.startsWith(\"!\")) cls = `^${cls.slice(1)}`;\n\t\t\tcls = cls.replace(/\\\\/g, \"\\\\\\\\\");\n\t\t\tre += `[${cls}]`;\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tre += escapeRegexLiteral(ch);\n\t}\n\tre += \"$\";\n\treturn new RegExp(re);\n}\n\n/** Fixed-capacity ring buffer — O(1) push and eviction. */\nclass RingBuffer<T> {\n\tprivate buf: (T | undefined)[];\n\tprivate head = 0;\n\tprivate _size = 0;\n\tconstructor(private capacity: number) {\n\t\tthis.buf = new Array(capacity);\n\t}\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\tpush(item: T): void {\n\t\tconst idx = (this.head + this._size) % this.capacity;\n\t\tthis.buf[idx] = item;\n\t\tif (this._size < this.capacity) this._size++;\n\t\telse this.head = (this.head + 1) % this.capacity;\n\t}\n\ttoArray(): T[] {\n\t\tconst result: T[] = [];\n\t\tfor (let i = 0; i < this._size; i++) result.push(this.buf[(this.head + i) % this.capacity]!);\n\t\treturn result;\n\t}\n}\n\nconst OBSERVE_ANSI_THEME: Required<ObserveTheme> = {\n\tdata: \"\\u001b[32m\",\n\tdirty: \"\\u001b[33m\",\n\tresolved: \"\\u001b[36m\",\n\tcomplete: \"\\u001b[34m\",\n\terror: \"\\u001b[31m\",\n\tderived: \"\\u001b[35m\",\n\tpath: \"\\u001b[90m\",\n\treset: \"\\u001b[0m\",\n};\n\nconst OBSERVE_NO_COLOR_THEME: Required<ObserveTheme> = {\n\tdata: \"\",\n\tdirty: \"\",\n\tresolved: \"\",\n\tcomplete: \"\",\n\terror: \"\",\n\tderived: \"\",\n\tpath: \"\",\n\treset: \"\",\n};\n\nfunction describeData(value: unknown): string {\n\tif (typeof value === \"string\") return JSON.stringify(value);\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || value == null)\n\t\treturn String(value);\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction resolveObserveTheme(theme: ObserveOptions[\"theme\"]): Required<ObserveTheme> {\n\tif (theme === \"none\") return OBSERVE_NO_COLOR_THEME;\n\tif (theme === \"ansi\" || theme == null) return OBSERVE_ANSI_THEME;\n\treturn {\n\t\tdata: theme.data ?? \"\",\n\t\tdirty: theme.dirty ?? \"\",\n\t\tresolved: theme.resolved ?? \"\",\n\t\tcomplete: theme.complete ?? \"\",\n\t\terror: theme.error ?? \"\",\n\t\tderived: theme.derived ?? \"\",\n\t\tpath: theme.path ?? \"\",\n\t\treset: theme.reset ?? \"\",\n\t};\n}\n\n/** Resolve observe `detail` level into effective boolean flags. */\nfunction resolveObserveDetail(opts?: ObserveOptions): ObserveOptions {\n\tif (opts == null) return {};\n\tconst detail = opts.detail;\n\tif (detail === \"full\") {\n\t\treturn {\n\t\t\t...opts,\n\t\t\tstructured: opts.structured ?? true,\n\t\t\ttimeline: opts.timeline ?? true,\n\t\t\tcausal: opts.causal ?? true,\n\t\t\tderived: opts.derived ?? true,\n\t\t};\n\t}\n\tif (detail === \"minimal\") {\n\t\treturn { ...opts, structured: opts.structured ?? true };\n\t}\n\treturn opts;\n}\n\n/** {@link Graph.observe} on a single node or meta path — sink receives plain message batches. */\nexport type GraphObserveOne = {\n\tsubscribe(sink: NodeSink): () => void;\n\t/** Send messages upstream toward the observed node's sources (e.g. PAUSE/RESUME). */\n\tup(messages: Messages): void;\n};\n\n/**\n * {@link Graph.observe} on the whole graph — sink receives each batch with the qualified source path.\n * Subscription order follows code-point sort on paths (mounts-first walk, then sorted locals/meta).\n */\nexport type GraphObserveAll = {\n\tsubscribe(sink: (nodePath: string, messages: Messages) => void): () => void;\n\t/** Send messages upstream toward a specific observed node's sources (e.g. PAUSE/RESUME). */\n\tup(path: string, messages: Messages): void;\n};\n\n/**\n * Detail level for `observe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — DATA events only, no timestamps, no causal info.\n * - `\"standard\"` — all message types (DATA, DIRTY, RESOLVED, COMPLETE, ERROR).\n * - `\"full\"` — standard + timeline + causal + derived.\n */\nexport type ObserveDetail = \"minimal\" | \"standard\" | \"full\";\n\n/** Options for structured observation modes on {@link Graph.observe}. */\nexport type ObserveOptions = {\n\tactor?: Actor;\n\t/** Return an {@link ObserveResult} accumulator instead of a raw stream. */\n\tstructured?: boolean;\n\t/** Include causal trace info (which dep triggered each recomputation). */\n\tcausal?: boolean;\n\t/** Include timestamps and batch context on each event. */\n\ttimeline?: boolean;\n\t/** Include per-evaluation dep snapshots for compute/derived nodes. */\n\tderived?: boolean;\n\t/**\n\t * Detail level (Phase 3.3b). Individual flags (`causal`, `timeline`, `derived`)\n\t * override. `\"full\"` implies all three plus structured.\n\t * `\"minimal\"` filters to DATA-only events.\n\t */\n\tdetail?: ObserveDetail;\n\n\t// ——— Format / logging (merged from spy) ———\n\n\t/**\n\t * When set, auto-enables structured mode and attaches a logger.\n\t * `\"pretty\"` renders colored one-line output; `\"json\"` emits one JSON object per event.\n\t */\n\tformat?: \"pretty\" | \"json\";\n\t/** Sink for rendered lines (`console.log` by default). Only used when `format` is set. */\n\tlogger?: (line: string, event: ObserveEvent) => void;\n\t/** Keep only these event types in formatted output. Only used when `format` is set. */\n\tincludeTypes?: ObserveEvent[\"type\"][];\n\t/** Exclude these event types from formatted output. Only used when `format` is set. */\n\texcludeTypes?: ObserveEvent[\"type\"][];\n\t/** Built-in color preset (`ansi` default) or explicit color tokens. Only used when `format` is set. */\n\ttheme?: ObserveThemeName | ObserveTheme;\n};\n\n/** Accumulated observation result (structured mode). */\nexport type ObserveResult<T = unknown> = {\n\t/** Latest DATA value by observed path. */\n\treadonly values: Record<string, T>;\n\t/** Number of DIRTY messages received. */\n\treadonly dirtyCount: number;\n\t/** Number of RESOLVED messages received. */\n\treadonly resolvedCount: number;\n\t/** All events in order. */\n\treadonly events: ObserveEvent[];\n\t/** True if any observed node sent COMPLETE without prior ERROR on that node. */\n\treadonly anyCompletedCleanly: boolean;\n\t/** True if any observed node sent ERROR. */\n\treadonly anyErrored: boolean;\n\t/** True if at least one COMPLETE received and no ERROR from any observed node. */\n\treadonly completedWithoutErrors: boolean;\n\t/** Stop observing. */\n\tdispose(): void;\n\t/**\n\t * Resubscribe with higher detail (Phase 3.3b).\n\t * Disposes current observation, returns new `ObserveResult` with merged options.\n\t */\n\texpand(\n\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t): ObserveResult<T>;\n};\n\n/** A single event in the structured observation log. */\nexport type ObserveEvent = {\n\ttype: \"data\" | \"dirty\" | \"resolved\" | \"complete\" | \"error\" | \"derived\";\n\tpath?: string;\n\tdata?: unknown;\n\ttimestamp_ns?: number;\n\tin_batch?: boolean;\n\t/** Monotonically increasing counter per subscribe-callback invocation. All events in one delivery share the same id. */\n\tbatch_id?: number;\n\ttrigger_dep_index?: number;\n\ttrigger_dep_name?: string;\n\t/**\n\t * V0 version of the triggering dep at observation time (§6.0b).\n\t * This is the dep's post-emission version (after its own `advanceVersion`),\n\t * not the pre-emission version that caused this node's recomputation.\n\t */\n\ttrigger_version?: { id: string; version: number };\n\tdep_values?: unknown[];\n};\n\n/** Built-in color preset names for observe `format` rendering. */\nexport type ObserveThemeName = \"none\" | \"ansi\";\n\n/** ANSI/style overrides for observe `format` event rendering. */\nexport type ObserveTheme = Partial<Record<ObserveEvent[\"type\"] | \"path\" | \"reset\", string>>;\n\n/** Options for {@link Graph.dumpGraph}. */\nexport type GraphDumpOptions = {\n\tactor?: Actor;\n\tfilter?: DescribeFilter;\n\tformat?: \"pretty\" | \"json\";\n\tindent?: number;\n\tincludeEdges?: boolean;\n\tincludeSubgraphs?: boolean;\n\tlogger?: (text: string) => void;\n};\n\nfunction assertLocalName(name: string, graphName: string, label: string): void {\n\tif (name === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": ${label} name must be non-empty`);\n\t}\n}\n\nfunction assertNoPathSep(name: string, graphName: string, label: string): void {\n\tif (name.includes(PATH_SEP)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} \"${name}\" must not contain '${PATH_SEP}' (path separator)`,\n\t\t);\n\t}\n}\n\nfunction assertNotReservedMetaSegment(name: string, graphName: string, label: string): void {\n\tif (name === GRAPH_META_SEGMENT) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} name \"${GRAPH_META_SEGMENT}\" is reserved for meta companion paths`,\n\t\t);\n\t}\n}\n\n/** `connect` / `disconnect` endpoints must be registered graph nodes, not meta paths (graphrefly-py parity). */\nfunction assertConnectPathNotMeta(path: string, graphName: string): void {\n\tif (path.split(PATH_SEP).includes(GRAPH_META_SEGMENT)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": connect/disconnect endpoints must be registered graph nodes, not meta paths (got \"${path}\")`,\n\t\t);\n\t}\n}\n\nfunction splitPath(path: string, graphName: string): string[] {\n\tif (path === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": resolve path must be non-empty`);\n\t}\n\tconst segments = path.split(PATH_SEP);\n\tfor (const s of segments) {\n\t\tif (s === \"\") {\n\t\t\tthrow new Error(`Graph \"${graphName}\": resolve path has empty segment`);\n\t\t}\n\t}\n\treturn segments;\n}\n\n/** Canonical string key for an edge pair (deterministic, splittable). */\nfunction edgeKey(from: string, to: string): string {\n\treturn `${from}\\t${to}`;\n}\n\nfunction parseEdgeKey(key: string): [string, string] {\n\tconst i = key.indexOf(\"\\t\");\n\treturn [key.slice(0, i), key.slice(i + 1)];\n}\n\n/**\n * Lifecycle-destructive message types that meta companion nodes ignore\n * during graph-wide signal propagation (spec §2.3 Companion lifecycle).\n * TEARDOWN: parent already cascades explicitly.\n * INVALIDATE/COMPLETE/ERROR: meta stores outlive these lifecycle events.\n * To target a meta node directly, call `meta.down(...)` on it.\n */\nconst META_FILTERED_TYPES = new Set([TEARDOWN, INVALIDATE, COMPLETE, ERROR]);\n\n/** Strip lifecycle-destructive messages; returns empty array when nothing remains. */\nfunction filterMetaMessages(messages: Messages): Messages {\n\tconst kept = messages.filter((m) => !META_FILTERED_TYPES.has(m[0]));\n\treturn kept as unknown as Messages;\n}\n\n/** TEARDOWN every node in a mounted graph tree (depth-first into mounts). */\nfunction teardownMountedGraph(root: Graph): void {\n\tfor (const child of root._mounts.values()) {\n\t\tteardownMountedGraph(child);\n\t}\n\tfor (const n of root._nodes.values()) {\n\t\tn.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n}\n\n/**\n * Named container for nodes and explicit edges (GRAPHREFLY-SPEC §3.1–§3.7).\n *\n * Qualified paths use `::` as the segment separator (for example `parent::child::node`).\n *\n * Edges are pure wires: `connect` only validates wiring — the target must already list the source in\n * its dependency array; no transforms run on the edge.\n *\n * @example\n * ```ts\n * import { Graph, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * g.add(\"counter\", state(0));\n * ```\n *\n * @category graph\n */\nexport class Graph {\n\tprivate static readonly _factories: Array<{\n\t\tpattern: string;\n\t\tre: RegExp;\n\t\tfactory: GraphNodeFactory;\n\t}> = [];\n\n\treadonly name: string;\n\treadonly opts: Readonly<GraphOptions>;\n\t/** @internal — exposed for {@link teardownMountedGraph} and cross-graph helpers. */\n\treadonly _nodes = new Map<string, Node>();\n\tprivate readonly _edges = new Set<string>();\n\t/** @internal — exposed for {@link teardownMountedGraph}. */\n\treadonly _mounts = new Map<string, Graph>();\n\tprivate readonly _autoCheckpointDisposers = new Set<() => void>();\n\tprivate readonly _disposers = new Set<() => void>();\n\tprivate _defaultVersioningLevel: VersioningLevel | undefined;\n\n\tstatic registerFactory(pattern: string, factory: GraphNodeFactory): void {\n\t\tif (!pattern) {\n\t\t\tthrow new Error(\"Graph.registerFactory requires a non-empty pattern\");\n\t\t}\n\t\tGraph.unregisterFactory(pattern);\n\t\tGraph._factories.push({ pattern, re: globToRegex(pattern), factory });\n\t}\n\n\tstatic unregisterFactory(pattern: string): void {\n\t\tconst i = Graph._factories.findIndex((entry) => entry.pattern === pattern);\n\t\tif (i >= 0) Graph._factories.splice(i, 1);\n\t}\n\n\t/**\n\t * @param name - Non-empty graph id (must not contain `::`).\n\t * @param opts - Reserved for future hooks; currently unused.\n\t */\n\tconstructor(name: string, opts?: GraphOptions) {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(\"Graph name must be non-empty\");\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\tthrow new Error(`Graph name must not contain '${PATH_SEP}' (got \"${name}\")`);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.opts = opts ?? {};\n\t}\n\n\tprivate static _factoryForPath(path: string): GraphNodeFactory | undefined {\n\t\tfor (let i = Graph._factories.length - 1; i >= 0; i -= 1) {\n\t\t\tconst entry = Graph._factories[i]!;\n\t\t\tif (entry.re.test(path)) return entry.factory;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate static _ownerForPath(root: Graph, path: string): [Graph, string] {\n\t\tconst segments = path.split(PATH_SEP);\n\t\tconst local = segments.pop();\n\t\tif (local == null || local.length === 0) {\n\t\t\tthrow new Error(`invalid snapshot path \"${path}\"`);\n\t\t}\n\t\tlet owner = root;\n\t\tfor (const seg of segments) {\n\t\t\tconst next = owner._mounts.get(seg);\n\t\t\tif (!next) throw new Error(`unknown mount \"${seg}\" in path \"${path}\"`);\n\t\t\towner = next;\n\t\t}\n\t\treturn [owner, local];\n\t}\n\n\t/**\n\t * Graphs reachable from this instance via nested {@link Graph.mount} (includes `this`).\n\t */\n\tprivate _graphsReachableViaMounts(seen = new Set<Graph>()): Set<Graph> {\n\t\tif (seen.has(this)) return seen;\n\t\tseen.add(this);\n\t\tfor (const child of this._mounts.values()) {\n\t\t\tchild._graphsReachableViaMounts(seen);\n\t\t}\n\t\treturn seen;\n\t}\n\n\t/**\n\t * Resolve an endpoint: returns `[owningGraph, localName, node]`.\n\t * Accepts both local names and `::` qualified paths.\n\t */\n\tprivate _resolveEndpoint(path: string): [Graph, string, Node] {\n\t\tif (!path.includes(PATH_SEP)) {\n\t\t\tconst n = this._nodes.get(path);\n\t\t\tif (!n) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${path}\"`);\n\t\t\t}\n\t\t\treturn [this, path, n];\n\t\t}\n\t\tconst segments = splitPath(path, this.name);\n\t\treturn this._resolveEndpointFromSegments(segments, path);\n\t}\n\n\tprivate _resolveEndpointFromSegments(\n\t\tsegments: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return [this, head, n];\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${head}\" (from path \"${fullPath}\")`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaEndpointKeys(localN, head, rest, fullPath);\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\t\treturn child._resolveEndpointFromSegments(rest, fullPath);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Node registry\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Registers a node under a local name. Fails if the name is already used,\n\t * reserved by a mount, or the same node instance is already registered.\n\t *\n\t * @param name - Local key (no `::`).\n\t * @param node - Node instance to own.\n\t */\n\tadd(name: string, node: Node): void {\n\t\tassertLocalName(name, this.name, \"add\");\n\t\tassertNoPathSep(name, this.name, \"add\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"node\");\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": name \"${name}\" is already a mount point`);\n\t\t}\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node \"${name}\" already exists`);\n\t\t}\n\t\tfor (const [existingName, existing] of this._nodes) {\n\t\t\tif (existing === node) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": node instance already registered as \"${existingName}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis._nodes.set(name, node);\n\t\tif (node instanceof NodeImpl) {\n\t\t\tnode._assignRegistryName(name);\n\t\t\tif (this._defaultVersioningLevel != null) {\n\t\t\t\tnode._applyVersioning(this._defaultVersioningLevel);\n\t\t\t}\n\t\t\t// Auto-register edges from constructor deps (eliminates dual-bookkeeping).\n\t\t\t// Forward: this node's deps → already-registered nodes.\n\t\t\tif (node._deps.length > 0) {\n\t\t\t\tfor (const dep of node._deps) {\n\t\t\t\t\tfor (const [depName, depNode] of this._nodes) {\n\t\t\t\t\t\tif (depNode === dep) {\n\t\t\t\t\t\t\tthis._edges.add(edgeKey(depName, name));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Reverse: already-registered nodes that depend on this newly added node.\n\t\t\tfor (const [otherName, otherNode] of this._nodes) {\n\t\t\t\tif (otherName === name) continue;\n\t\t\t\tif (otherNode instanceof NodeImpl && otherNode._deps.includes(node)) {\n\t\t\t\t\tthis._edges.add(edgeKey(name, otherName));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Set a default versioning level for all nodes added to this graph (roadmap §6.0).\n\t *\n\t * Nodes already registered are retroactively upgraded. Nodes added later via\n\t * {@link add} will inherit this level unless they already have versioning.\n\t *\n\t * **Scope:** Does not propagate to mounted subgraphs. Call `setVersioning`\n\t * on each child graph separately if needed.\n\t *\n\t * @param level - `0` for V0, `1` for V1, or `undefined` to clear.\n\t */\n\tsetVersioning(level: VersioningLevel | undefined): void {\n\t\tthis._defaultVersioningLevel = level;\n\t\tif (level == null) return;\n\t\tfor (const n of this._nodes.values()) {\n\t\t\tif (n instanceof NodeImpl) {\n\t\t\t\tn._applyVersioning(level);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters a node or unmounts a subgraph, drops incident edges, and sends\n\t * `[[TEARDOWN]]` to the removed node or recursively through the mounted subtree (§3.2).\n\t *\n\t * @param name - Local mount or node name.\n\t */\n\tremove(name: string): void {\n\t\tassertLocalName(name, this.name, \"remove\");\n\t\tassertNoPathSep(name, this.name, \"remove\");\n\n\t\t// Case 1: unmount a subgraph\n\t\tconst child = this._mounts.get(name);\n\t\tif (child) {\n\t\t\tthis._mounts.delete(name);\n\t\t\t// Drop edges touching this mount name or qualified paths under it.\n\t\t\tconst prefix = `${name}${PATH_SEP}`;\n\t\t\tfor (const key of [...this._edges]) {\n\t\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\t\tif (from === name || to === name || from.startsWith(prefix) || to.startsWith(prefix)) {\n\t\t\t\t\tthis._edges.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tteardownMountedGraph(child);\n\t\t\treturn;\n\t\t}\n\n\t\t// Case 2: remove a local node\n\t\tconst node = this._nodes.get(name);\n\t\tif (!node) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node or mount \"${name}\"`);\n\t\t}\n\t\tthis._nodes.delete(name);\n\t\tfor (const key of [...this._edges]) {\n\t\t\tconst [from, to] = parseEdgeKey(key);\n\t\t\tif (from === name || to === name) this._edges.delete(key);\n\t\t}\n\t\tnode.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t}\n\n\t/**\n\t * Returns a node by local name or `::` qualified path.\n\t * Local names are looked up directly; paths with `::` delegate to {@link resolve}.\n\t *\n\t * @param name - Local name or qualified path.\n\t */\n\tnode(name: string): Node {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node name must be non-empty`);\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\treturn this.resolve(name);\n\t\t}\n\t\tconst n = this._nodes.get(name);\n\t\tif (!n) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${name}\"`);\n\t\t}\n\t\treturn n;\n\t}\n\n\t/**\n\t * Reads `graph.node(name).get()` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @returns Cached value or `undefined`.\n\t */\n\tget(name: string): unknown {\n\t\treturn this.node(name).get();\n\t}\n\n\t/**\n\t * Shorthand for `graph.node(name).down([[DATA, value]], { actor })` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @param value - Next `DATA` payload.\n\t * @param options - Optional `actor` and `internal` guard bypass.\n\t */\n\tset(name: string, value: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[DATA, value]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Edges\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Record a wire from `fromPath` → `toPath` (§3.3). Accepts local names or\n\t * `::` qualified paths. The target must be a {@link NodeImpl} whose `_deps`\n\t * includes the source node (same reference). Idempotent.\n\t *\n\t * Same-owner edges are stored on the owning child graph; cross-subgraph edges\n\t * are stored on this (parent) graph's registry.\n\t *\n\t * @param fromPath - Source endpoint (local or qualified).\n\t * @param toPath - Target endpoint whose deps already include the source node.\n\t */\n\tconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": connect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal, fromNode] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal, toNode] = this._resolveEndpoint(toPath);\n\n\t\tif (fromNode === toNode) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot connect a node to itself`);\n\t\t}\n\n\t\tif (!(toNode instanceof NodeImpl)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) requires the target to be a graphrefly NodeImpl so deps can be validated`,\n\t\t\t);\n\t\t}\n\t\tif (!toNode._deps.includes(fromNode)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": connect(${fromPath}, ${toPath}) — target must include source in its constructor deps (same node reference)`,\n\t\t\t);\n\t\t}\n\n\t\tif (fromGraph === toGraph) {\n\t\t\t// Same-owner: store on the child graph\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tfromGraph._edges.add(key);\n\t\t} else {\n\t\t\t// Cross-subgraph: store on this (parent) graph\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tthis._edges.add(key);\n\t\t}\n\t}\n\n\t/**\n\t * Remove a registered edge (§3.3). Accepts local names or `::` qualified paths.\n\t *\n\t * **Registry-only (§C resolved):** This drops the edge from the graph's edge\n\t * registry only. It does **not** mutate the target node's constructor-time\n\t * dependency list, bitmasks, or upstream subscriptions. Message flow follows\n\t * constructor-time deps, not the edge registry. For runtime dep rewiring, use\n\t * {@link dynamicNode}.\n\t *\n\t * @param fromPath - Registered edge tail.\n\t * @param toPath - Registered edge head.\n\t */\n\tdisconnect(fromPath: string, toPath: string): void {\n\t\tif (!fromPath || !toPath) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": disconnect paths must be non-empty`);\n\t\t}\n\t\tassertConnectPathNotMeta(fromPath, this.name);\n\t\tassertConnectPathNotMeta(toPath, this.name);\n\n\t\tconst [fromGraph, fromLocal] = this._resolveEndpoint(fromPath);\n\t\tconst [toGraph, toLocal] = this._resolveEndpoint(toPath);\n\n\t\tif (fromGraph === toGraph) {\n\t\t\tconst key = edgeKey(fromLocal, toLocal);\n\t\t\tif (!fromGraph._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = edgeKey(fromPath, toPath);\n\t\t\tif (!this._edges.delete(key)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": no registered edge ${fromPath} → ${toPath}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns registered `[from, to]` edge pairs (read-only snapshot).\n\t *\n\t * @returns Edge pairs recorded on this graph instance’s local `_edges` set.\n\t */\n\tedges(): ReadonlyArray<[string, string]> {\n\t\tconst result: [string, string][] = [];\n\t\tfor (const key of this._edges) {\n\t\t\tresult.push(parseEdgeKey(key));\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Composition\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Embed a child graph at a local mount name (§3.4). Child nodes are reachable via\n\t * {@link Graph.resolve} using `::` delimited paths (§3.5). Lifecycle\n\t * {@link Graph.signal} visits mounted subgraphs recursively.\n\t *\n\t * Rejects: same name as existing node or mount, self-mount, mount cycles,\n\t * and the same child graph instance mounted twice on one parent.\n\t *\n\t * @param name - Local mount point.\n\t * @param child - Nested `Graph` instance.\n\t */\n\tmount(name: string, child: Graph): void {\n\t\tassertLocalName(name, this.name, \"mount\");\n\t\tassertNoPathSep(name, this.name, \"mount\");\n\t\tassertNotReservedMetaSegment(name, this.name, \"mount\");\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": cannot mount at \"${name}\" — node with that name exists`,\n\t\t\t);\n\t\t}\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount \"${name}\" already exists`);\n\t\t}\n\t\tif (child === this) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot mount a graph into itself`);\n\t\t}\n\t\t// Reject same child instance mounted twice on this parent.\n\t\tfor (const existing of this._mounts.values()) {\n\t\t\tif (existing === child) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": this child graph is already mounted on this graph`);\n\t\t\t}\n\t\t}\n\t\tif (child._graphsReachableViaMounts().has(this)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount(\"${name}\", …) would create a mount cycle`);\n\t\t}\n\t\tthis._mounts.set(name, child);\n\t}\n\n\t/**\n\t * Look up a node by qualified path (§3.5). Segments are separated by `::`.\n\t *\n\t * If the first segment equals this graph's {@link Graph.name}, it is stripped\n\t * (so `root.resolve(\"app::a\")` works when `root.name === \"app\"`).\n\t *\n\t * @param path - Qualified `::` path or local name.\n\t * @returns The resolved `Node`.\n\t */\n\tresolve(path: string): Node {\n\t\tlet segments = splitPath(path, this.name);\n\t\tif (segments[0] === this.name) {\n\t\t\tsegments = segments.slice(1);\n\t\t\tif (segments.length === 0) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": resolve path ends at graph name only`);\n\t\t\t}\n\t\t}\n\t\treturn this._resolveFromSegments(segments);\n\t}\n\n\tprivate _resolveFromSegments(segments: readonly string[]): Node {\n\t\tconst head = segments[0] as string;\n\t\tconst rest = segments.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return n;\n\t\t\tif (this._mounts.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": path ends at subgraph \"${head}\" — not a node (GRAPHREFLY-SPEC §3.5)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown name \"${head}\"`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaChainFromNode(localN, rest, segments.join(PATH_SEP));\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\n\t\treturn child.resolve(rest.join(PATH_SEP));\n\t}\n\n\t/**\n\t * Resolve `::__meta__::key` segments from a registered primary node (possibly chained).\n\t */\n\tprivate _resolveMetaChainFromNode(n: Node, parts: readonly string[], fullPath: string): Node {\n\t\tlet current = n;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = p[i + 1] as string;\n\t\t\tconst next = current.meta[key];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown meta \"${key}\" in path \"${fullPath}\"`);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate _resolveMetaEndpointKeys(\n\t\tbaseNode: Node,\n\t\tbaseLocalKey: string,\n\t\tparts: readonly string[],\n\t\tfullPath: string,\n\t): [Graph, string, Node] {\n\t\tlet current = baseNode;\n\t\tlet localKey = baseLocalKey;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst metaKey = p[i + 1] as string;\n\t\t\tconst next = current.meta[metaKey];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": unknown meta \"${metaKey}\" on node (in \"${fullPath}\")`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlocalKey = `${localKey}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${metaKey}`;\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn [this, localKey, current];\n\t}\n\n\t/**\n\t * Deliver a message batch to every registered node in this graph and, recursively,\n\t * in mounted child graphs (§3.7). Recurses into mounts first, then delivers to\n\t * local nodes (sorted by name). Each {@link Node} receives at most one delivery\n\t * per call (deduped by reference).\n\t *\n\t * Companion `meta` nodes receive the same batch for control-plane types (e.g.\n\t * PAUSE) that the primary does not forward. **TEARDOWN-only** batches skip the\n\t * extra meta pass — the primary’s `down()` already cascades TEARDOWN to meta.\n\t *\n\t * @param messages - Batch to deliver to every registered node (and mounts, recursively).\n\t * @param options - Optional `actor` / `internal` for transport.\n\t */\n\tsignal(messages: Messages, options?: GraphActorOptions): void {\n\t\tthis._signalDeliver(messages, options ?? {}, new Set());\n\t}\n\n\tprivate _signalDeliver(messages: Messages, opts: GraphActorOptions, vis: Set<Node>): void {\n\t\tfor (const sub of this._mounts.values()) {\n\t\t\tsub._signalDeliver(messages, opts, vis);\n\t\t}\n\t\tconst internal = opts.internal === true;\n\t\tconst downOpts: NodeTransportOptions = internal\n\t\t\t? { internal: true }\n\t\t\t: { actor: opts.actor, delivery: \"signal\" };\n\t\tconst metaMessages = filterMetaMessages(messages);\n\t\tfor (const localName of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(localName)!;\n\t\t\tif (vis.has(n)) continue;\n\t\t\tvis.add(n);\n\t\t\tn.down(messages, downOpts);\n\t\t\tif (metaMessages.length === 0) continue;\n\t\t\tthis._signalMetaSubtree(n, metaMessages, vis, downOpts);\n\t\t}\n\t}\n\n\tprivate _signalMetaSubtree(\n\t\troot: Node,\n\t\tmessages: Messages,\n\t\tvis: Set<Node>,\n\t\tdownOpts: NodeTransportOptions,\n\t): void {\n\t\tfor (const mk of Object.keys(root.meta).sort()) {\n\t\t\tconst mnode = root.meta[mk];\n\t\t\tif (vis.has(mnode)) continue;\n\t\t\tvis.add(mnode);\n\t\t\tmnode.down(messages, downOpts);\n\t\t\tthis._signalMetaSubtree(mnode, messages, vis, downOpts);\n\t\t}\n\t}\n\n\t/**\n\t * Static structure snapshot: qualified node keys, edges, mount names (GRAPHREFLY-SPEC §3.6, Appendix B).\n\t *\n\t * @param options - Optional `actor` for guard-scoped visibility and/or `filter` for selective output.\n\t * @returns JSON-shaped describe payload for this graph tree.\n\t *\n\t * @example\n\t * ```ts\n\t * graph.describe() // full snapshot\n\t * graph.describe({ actor: llm }) // guard-scoped\n\t * graph.describe({ filter: { status: \"errored\" } }) // only errored nodes\n\t * graph.describe({ filter: (n) => n.type === \"state\" }) // predicate filter\n\t * ```\n\t */\n\tdescribe(options?: GraphDescribeOptions): GraphDescribeOutput {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst includeFields = resolveDescribeFields(options?.detail, options?.fields);\n\t\tconst isSpec = options?.format === \"spec\";\n\t\t// For spec format, force minimal fields (type + deps only, no status/value)\n\t\tconst effectiveFields = isSpec ? resolveDescribeFields(\"minimal\") : includeFields;\n\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\tconst nodeToPath = new Map<Node, string>();\n\t\tfor (const [p, n] of targets) {\n\t\t\tnodeToPath.set(n, p);\n\t\t}\n\t\tconst nodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const [p, n] of targets) {\n\t\t\tif (actor != null && !n.allowsObserve(actor)) continue;\n\t\t\tconst raw = describeNode(n, effectiveFields);\n\t\t\tconst deps =\n\t\t\t\tn instanceof NodeImpl ? n._deps.map((d) => nodeToPath.get(d) ?? d.name ?? \"\") : [];\n\t\t\tconst { name: _name, ...rest } = raw;\n\t\t\tconst entry: DescribeNodeOutput = { ...rest, deps };\n\t\t\tif (filter != null) {\n\t\t\t\tif (typeof filter === \"function\") {\n\t\t\t\t\tconst fn = filter as\n\t\t\t\t\t\t| ((nodePath: string, node: DescribeNodeOutput) => boolean)\n\t\t\t\t\t\t| ((node: DescribeNodeOutput) => boolean);\n\t\t\t\t\tconst pass =\n\t\t\t\t\t\tfn.length >= 2\n\t\t\t\t\t\t\t? (fn as (nodePath: string, node: DescribeNodeOutput) => boolean)(p, entry)\n\t\t\t\t\t\t\t: (fn as (node: DescribeNodeOutput) => boolean)(entry);\n\t\t\t\t\tif (!pass) continue;\n\t\t\t\t} else {\n\t\t\t\t\tlet match = true;\n\t\t\t\t\tfor (const [fk, fv] of Object.entries(filter)) {\n\t\t\t\t\t\tconst normalizedKey =\n\t\t\t\t\t\t\tfk === \"deps_includes\" ? \"depsIncludes\" : fk === \"meta_has\" ? \"metaHas\" : fk;\n\t\t\t\t\t\tif (normalizedKey === \"depsIncludes\") {\n\t\t\t\t\t\t\tif (!entry.deps.includes(String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (normalizedKey === \"metaHas\") {\n\t\t\t\t\t\t\tif (!Object.hasOwn(entry.meta ?? {}, String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((entry as Record<string, unknown>)[normalizedKey] !== fv) {\n\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) continue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodes[p] = entry;\n\t\t}\n\t\tconst nodeKeys = new Set(Object.keys(nodes));\n\t\tlet edges = this._collectAllEdges(\"\");\n\t\tif (actor != null || filter != null) {\n\t\t\tedges = edges.filter((e) => nodeKeys.has(e.from) && nodeKeys.has(e.to));\n\t\t}\n\t\tedges.sort((a, b) => {\n\t\t\tif (a.from < b.from) return -1;\n\t\t\tif (a.from > b.from) return 1;\n\t\t\tif (a.to < b.to) return -1;\n\t\t\tif (a.to > b.to) return 1;\n\t\t\treturn 0;\n\t\t});\n\t\tconst allSubgraphs = this._collectSubgraphs(\"\");\n\t\tconst subgraphs =\n\t\t\tactor != null || filter != null\n\t\t\t\t? allSubgraphs.filter((sg) => {\n\t\t\t\t\t\tconst prefix = `${sg}${PATH_SEP}`;\n\t\t\t\t\t\treturn [...nodeKeys].some((k) => k === sg || k.startsWith(prefix));\n\t\t\t\t\t})\n\t\t\t\t: allSubgraphs;\n\n\t\t// Capture graph ref and base options for expand()\n\t\tconst graph = this;\n\t\tconst baseOpts = options;\n\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t\texpand(detailOrFields: DescribeDetail | DescribeField[]): GraphDescribeOutput {\n\t\t\t\tconst merged: GraphDescribeOptions = { ...baseOpts, format: undefined };\n\t\t\t\tif (Array.isArray(detailOrFields)) {\n\t\t\t\t\tmerged.fields = detailOrFields;\n\t\t\t\t\tmerged.detail = undefined;\n\t\t\t\t} else {\n\t\t\t\t\tmerged.detail = detailOrFields;\n\t\t\t\t\tmerged.fields = undefined;\n\t\t\t\t}\n\t\t\t\treturn graph.describe(merged);\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _collectSubgraphs(prefix: string): string[] {\n\t\tconst out: string[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst q = prefix === \"\" ? m : `${prefix}${m}`;\n\t\t\tout.push(q);\n\t\t\tout.push(...this._mounts.get(m)!._collectSubgraphs(`${q}${PATH_SEP}`));\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _collectAllEdges(prefix: string): { from: string; to: string }[] {\n\t\tconst out: { from: string; to: string }[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tout.push(...this._mounts.get(m)!._collectAllEdges(p2));\n\t\t}\n\t\tfor (const [f, t] of this.edges()) {\n\t\t\tout.push({\n\t\t\t\tfrom: this._qualifyEdgeEndpoint(f, prefix),\n\t\t\t\tto: this._qualifyEdgeEndpoint(t, prefix),\n\t\t\t});\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Snapshot-based resource profile: per-node stats, orphan effect detection,\n\t * memory hotspots. Zero runtime overhead — walks nodes on demand.\n\t *\n\t * @param opts - Optional `topN` for hotspot limit (default 10).\n\t * @returns Aggregate profile with per-node details, hotspots, and orphan effects.\n\t */\n\tresourceProfile(opts?: GraphProfileOptions): GraphProfileResult {\n\t\treturn graphProfile(this, opts);\n\t}\n\n\tprivate _qualifyEdgeEndpoint(part: string, prefix: string): string {\n\t\tif (part.includes(PATH_SEP)) return part;\n\t\treturn prefix === \"\" ? part : `${prefix}${PATH_SEP}${part}`;\n\t}\n\n\tprivate _collectObserveTargets(prefix: string, out: [string, Node][]): void {\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tthis._mounts.get(m)!._collectObserveTargets(p2, out);\n\t\t}\n\t\tfor (const loc of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(loc)!;\n\t\t\tconst p = prefix === \"\" ? loc : `${prefix}${PATH_SEP}${loc}`;\n\t\t\tout.push([p, n]);\n\t\t\tthis._appendMetaObserveTargets(p, n, out);\n\t\t}\n\t}\n\n\tprivate _appendMetaObserveTargets(basePath: string, n: Node, out: [string, Node][]): void {\n\t\tfor (const mk of Object.keys(n.meta).sort()) {\n\t\t\tconst m = n.meta[mk];\n\t\t\tconst mp = `${basePath}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${mk}`;\n\t\t\tout.push([mp, m]);\n\t\t\tthis._appendMetaObserveTargets(mp, m, out);\n\t\t}\n\t}\n\n\t/**\n\t * Live message stream from one node (or meta path), or from the whole graph (§3.6).\n\t *\n\t * Overloads: `(path, options?)` for one node; `(options?)` for all nodes. Whole-graph mode\n\t * subscribes in **sorted path order** (code-point order). With structured options\n\t * (`structured`, `timeline`, `causal`, `derived`), returns an {@link ObserveResult}.\n\t * Inspector-gated extras (`causal` / `derived`) require {@link Graph.inspectorEnabled}.\n\t *\n\t * @param pathOrOpts - Qualified `path` string, or omit and pass only `options` for graph-wide observation.\n\t * @param options - Optional `actor`, `structured`, `causal`, `timeline` (inspector-gated).\n\t * @returns `GraphObserveOne`, `GraphObserveAll`, or `ObserveResult` depending on overload/options.\n\t */\n\tobserve(\n\t\tpath: string,\n\t\toptions?: ObserveOptions & {\n\t\t\tstructured?: true;\n\t\t\ttimeline?: true;\n\t\t\tcausal?: true;\n\t\t\tderived?: true;\n\t\t},\n\t): ObserveResult;\n\tobserve(path: string, options: ObserveOptions & { format: \"pretty\" | \"json\" }): ObserveResult;\n\tobserve(path: string, options?: ObserveOptions): GraphObserveOne;\n\tobserve(\n\t\toptions: ObserveOptions & { structured?: true; timeline?: true; causal?: true; derived?: true },\n\t): ObserveResult;\n\tobserve(options: ObserveOptions & { format: \"pretty\" | \"json\" }): ObserveResult;\n\tobserve(options?: ObserveOptions): GraphObserveAll;\n\tobserve(\n\t\tpathOrOpts?: string | ObserveOptions,\n\t\toptions?: ObserveOptions,\n\t): GraphObserveOne | GraphObserveAll | ObserveResult {\n\t\tif (typeof pathOrOpts === \"string\") {\n\t\t\tconst path = pathOrOpts;\n\t\t\tconst resolved = resolveObserveDetail(options);\n\t\t\tconst actor = resolved.actor;\n\t\t\tconst target = this.resolve(path);\n\t\t\tif (actor != null && !target.allowsObserve(actor)) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: path });\n\t\t\t}\n\t\t\tconst wantsStructured =\n\t\t\t\tresolved.structured === true ||\n\t\t\t\tresolved.timeline === true ||\n\t\t\t\tresolved.causal === true ||\n\t\t\t\tresolved.derived === true ||\n\t\t\t\tresolved.detail === \"minimal\" ||\n\t\t\t\tresolved.detail === \"full\" ||\n\t\t\t\tresolved.format != null;\n\t\t\tif (wantsStructured) {\n\t\t\t\tconst result = Graph.inspectorEnabled\n\t\t\t\t\t? this._createObserveResult(path, target, resolved)\n\t\t\t\t\t: this._createFallbackObserveResult(path, resolved);\n\t\t\t\tif (resolved.format != null) {\n\t\t\t\t\tthis._attachFormatLogger(result, resolved);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsubscribe(sink: NodeSink) {\n\t\t\t\t\treturn target.subscribe(sink);\n\t\t\t\t},\n\t\t\t\tup(messages: Messages) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttarget.up?.(messages);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst opts = resolveObserveDetail(pathOrOpts as ObserveOptions | undefined);\n\t\tconst actor = opts.actor;\n\t\tconst wantsStructured =\n\t\t\topts.structured === true ||\n\t\t\topts.timeline === true ||\n\t\t\topts.causal === true ||\n\t\t\topts.derived === true ||\n\t\t\topts.detail === \"minimal\" ||\n\t\t\topts.detail === \"full\" ||\n\t\t\topts.format != null;\n\t\tif (wantsStructured) {\n\t\t\tconst result = Graph.inspectorEnabled\n\t\t\t\t? this._createObserveResultForAll(opts)\n\t\t\t\t: this._createFallbackObserveResultForAll(opts);\n\t\t\tif (opts.format != null) {\n\t\t\t\tthis._attachFormatLogger(result, opts);\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\treturn {\n\t\t\tsubscribe: (sink: (nodePath: string, messages: Messages) => void) => {\n\t\t\t\tconst targets: [string, Node][] = [];\n\t\t\t\tthis._collectObserveTargets(\"\", targets);\n\t\t\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\t\t\tconst picked =\n\t\t\t\t\tactor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\t\t\tconst unsubs = picked.map(([p, nd]) =>\n\t\t\t\t\tnd.subscribe((msgs) => {\n\t\t\t\t\t\tsink(p, msgs);\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn () => {\n\t\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\t};\n\t\t\t},\n\t\t\tup: (upPath: string, messages: Messages) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst nd = this.resolve(upPath);\n\t\t\t\t\tnd.up?.(messages);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (err instanceof GuardDenied) return; // silently drop — guard denied flow control\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResult<T>(\n\t\tpath: string,\n\t\ttarget: Node<T>,\n\t\toptions: ObserveOptions,\n\t): ObserveResult<T> {\n\t\tconst timeline = options.timeline === true;\n\t\tconst causal = options.causal === true;\n\t\tconst derived = options.derived === true;\n\t\tconst minimal = options.detail === \"minimal\";\n\t\tconst result: {\n\t\t\tvalues: Record<string, T>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tanyCompletedCleanly: boolean;\n\t\t\tanyErrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tanyCompletedCleanly: false,\n\t\t\tanyErrored: false,\n\t\t};\n\n\t\tlet lastTriggerDepIndex: number | undefined;\n\t\tlet lastRunDepValues: unknown[] | undefined;\n\t\tlet detachInspectorHook: (() => void) | undefined;\n\t\tlet batchSeq = 0;\n\t\tif ((causal || derived) && target instanceof NodeImpl) {\n\t\t\tdetachInspectorHook = target._setInspectorHook((event: NodeInspectorHookEvent) => {\n\t\t\t\tif (event.kind === \"dep_message\") {\n\t\t\t\t\tlastTriggerDepIndex = event.depIndex;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlastRunDepValues = [...event.depValues];\n\t\t\t\tif (derived) {\n\t\t\t\t\tresult.events.push({\n\t\t\t\t\t\ttype: \"derived\",\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tdep_values: [...event.depValues],\n\t\t\t\t\t\t...(timeline\n\t\t\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst unsub = target.subscribe((msgs) => {\n\t\t\tbatchSeq++;\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst t = m[0];\n\t\t\t\tconst base = timeline\n\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t: {};\n\t\t\t\tconst withCausal =\n\t\t\t\t\tcausal && lastRunDepValues != null\n\t\t\t\t\t\t? (() => {\n\t\t\t\t\t\t\t\tconst triggerDep =\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex != null &&\n\t\t\t\t\t\t\t\t\tlastTriggerDepIndex >= 0 &&\n\t\t\t\t\t\t\t\t\ttarget instanceof NodeImpl\n\t\t\t\t\t\t\t\t\t\t? target._deps[lastTriggerDepIndex]\n\t\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\t\tconst tv = triggerDep?.v;\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\ttrigger_dep_index: lastTriggerDepIndex,\n\t\t\t\t\t\t\t\t\ttrigger_dep_name: triggerDep?.name,\n\t\t\t\t\t\t\t\t\t...(tv != null ? { trigger_version: { id: tv.id, version: tv.version } } : {}),\n\t\t\t\t\t\t\t\t\tdep_values: [...lastRunDepValues],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t})()\n\t\t\t\t\t\t: {};\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tresult.values[path] = m[1] as T;\n\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base, ...withCausal });\n\t\t\t\t} else if (minimal) {\n\t\t\t\t\t// minimal: track state but don't push non-DATA events\n\t\t\t\t\tif (t === DIRTY) result.dirtyCount++;\n\t\t\t\t\telse if (t === RESOLVED) result.resolvedCount++;\n\t\t\t\t\telse if (t === COMPLETE && !result.anyErrored) result.anyCompletedCleanly = true;\n\t\t\t\t\telse if (t === ERROR) result.anyErrored = true;\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base, ...withCausal });\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!result.anyErrored) result.anyCompletedCleanly = true;\n\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tresult.anyErrored = true;\n\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tconst graph = this;\n\t\tconst basePath = path;\n\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn result.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn result.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn result.anyCompletedCleanly && !result.anyErrored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tunsub();\n\t\t\t\tdetachInspectorHook?.();\n\t\t\t},\n\t\t\texpand(\n\t\t\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t\t\t): ObserveResult<T> {\n\t\t\t\tunsub();\n\t\t\t\tdetachInspectorHook?.();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\tconst resolvedTarget = graph.resolve(basePath);\n\t\t\t\tconst expanded = graph._createObserveResult<T>(\n\t\t\t\t\tbasePath,\n\t\t\t\t\tresolvedTarget as Node<T>,\n\t\t\t\t\tresolveObserveDetail(merged),\n\t\t\t\t);\n\t\t\t\tif (merged.format != null) {\n\t\t\t\t\tgraph._attachFormatLogger(expanded, merged);\n\t\t\t\t}\n\t\t\t\treturn expanded;\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _createObserveResultForAll(options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline === true;\n\t\tconst minimal = options.detail === \"minimal\";\n\t\tconst result: {\n\t\t\tvalues: Record<string, unknown>;\n\t\t\tdirtyCount: number;\n\t\t\tresolvedCount: number;\n\t\t\tevents: ObserveEvent[];\n\t\t\tanyCompletedCleanly: boolean;\n\t\t\tanyErrored: boolean;\n\t\t} = {\n\t\t\tvalues: {},\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [],\n\t\t\tanyCompletedCleanly: false,\n\t\t\tanyErrored: false,\n\t\t};\n\t\t/** Per-node terminal state for allCompletedCleanly computation. */\n\t\tconst nodeErrored = new Set<string>();\n\t\tconst actor = options.actor;\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst picked = actor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\tlet batchSeq = 0;\n\t\tconst unsubs = picked.map(([path, nd]) =>\n\t\t\tnd.subscribe((msgs) => {\n\t\t\t\tbatchSeq++;\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tconst t = m[0];\n\t\t\t\t\tconst base = timeline\n\t\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t\t: {};\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tresult.values[path] = m[1];\n\t\t\t\t\t\tresult.events.push({ type: \"data\", path, data: m[1], ...base });\n\t\t\t\t\t} else if (minimal) {\n\t\t\t\t\t\tif (t === DIRTY) result.dirtyCount++;\n\t\t\t\t\t\telse if (t === RESOLVED) result.resolvedCount++;\n\t\t\t\t\t\telse if (t === COMPLETE && !nodeErrored.has(path)) result.anyCompletedCleanly = true;\n\t\t\t\t\t\telse if (t === ERROR) {\n\t\t\t\t\t\t\tresult.anyErrored = true;\n\t\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\t\tresult.dirtyCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\tresult.resolvedCount++;\n\t\t\t\t\t\tresult.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\tif (!nodeErrored.has(path)) result.anyCompletedCleanly = true;\n\t\t\t\t\t\tresult.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tresult.anyErrored = true;\n\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\tresult.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\n\t\tconst graph = this;\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn result.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn result.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn result.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn result.events;\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn result.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn result.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn result.anyCompletedCleanly && !result.anyErrored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t},\n\t\t\texpand(\n\t\t\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t\t\t): ObserveResult {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\tconst expanded = graph._createObserveResultForAll(resolveObserveDetail(merged));\n\t\t\t\tif (merged.format != null) {\n\t\t\t\t\tgraph._attachFormatLogger(expanded, merged);\n\t\t\t\t}\n\t\t\t\treturn expanded;\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Fallback ObserveResult for single-node when inspector is disabled but `format` is requested.\n\t * Subscribes to raw messages and accumulates events with timeline info.\n\t */\n\tprivate _createFallbackObserveResult(path: string, options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline !== false;\n\t\tconst acc = {\n\t\t\tvalues: {} as Record<string, unknown>,\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [] as ObserveEvent[],\n\t\t\tanyCompletedCleanly: false,\n\t\t\tanyErrored: false,\n\t\t};\n\t\tconst target = this.resolve(path);\n\t\tlet batchSeq = 0;\n\t\tconst unsub = target.subscribe((msgs) => {\n\t\t\tbatchSeq++;\n\t\t\tfor (const m of msgs) {\n\t\t\t\tconst t = m[0];\n\t\t\t\tconst base = timeline\n\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t: {};\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tacc.values[path] = m[1];\n\t\t\t\t\tacc.events.push({ type: \"data\", path, data: m[1], ...base });\n\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\tacc.dirtyCount++;\n\t\t\t\t\tacc.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tacc.resolvedCount++;\n\t\t\t\t\tacc.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tif (!acc.anyErrored) acc.anyCompletedCleanly = true;\n\t\t\t\t\tacc.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tacc.anyErrored = true;\n\t\t\t\t\tacc.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn acc.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn acc.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn acc.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn acc.events;\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn acc.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn acc.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn acc.anyCompletedCleanly && !acc.anyErrored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tunsub();\n\t\t\t},\n\t\t\texpand() {\n\t\t\t\tthrow new Error(\"expand() requires inspector mode (Graph.inspectorEnabled = true)\");\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Fallback ObserveResult for graph-wide when inspector is disabled but `format` is requested.\n\t */\n\tprivate _createFallbackObserveResultForAll(options: ObserveOptions): ObserveResult {\n\t\tconst timeline = options.timeline !== false;\n\t\tconst actor = options.actor;\n\t\tconst acc = {\n\t\t\tvalues: {} as Record<string, unknown>,\n\t\t\tdirtyCount: 0,\n\t\t\tresolvedCount: 0,\n\t\t\tevents: [] as ObserveEvent[],\n\t\t\tanyCompletedCleanly: false,\n\t\t\tanyErrored: false,\n\t\t};\n\t\tconst nodeErrored = new Set<string>();\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\ttargets.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst picked = actor == null ? targets : targets.filter(([, nd]) => nd.allowsObserve(actor));\n\t\tlet batchSeq = 0;\n\t\tconst unsubs = picked.map(([path, nd]) =>\n\t\t\tnd.subscribe((msgs) => {\n\t\t\t\tbatchSeq++;\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tconst t = m[0];\n\t\t\t\t\tconst base = timeline\n\t\t\t\t\t\t? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq }\n\t\t\t\t\t\t: {};\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tacc.values[path] = m[1];\n\t\t\t\t\t\tacc.events.push({ type: \"data\", path, data: m[1], ...base });\n\t\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\t\tacc.dirtyCount++;\n\t\t\t\t\t\tacc.events.push({ type: \"dirty\", path, ...base });\n\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\tacc.resolvedCount++;\n\t\t\t\t\t\tacc.events.push({ type: \"resolved\", path, ...base });\n\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\tif (!nodeErrored.has(path)) acc.anyCompletedCleanly = true;\n\t\t\t\t\t\tacc.events.push({ type: \"complete\", path, ...base });\n\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\tacc.anyErrored = true;\n\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\tacc.events.push({ type: \"error\", path, data: m[1], ...base });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\tget values() {\n\t\t\t\treturn acc.values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn acc.dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn acc.resolvedCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn acc.events;\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn acc.anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn acc.anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn acc.anyCompletedCleanly && !acc.anyErrored;\n\t\t\t},\n\t\t\tdispose() {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t},\n\t\t\texpand() {\n\t\t\t\tthrow new Error(\"expand() requires inspector mode (Graph.inspectorEnabled = true)\");\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Attaches a format logger to an ObserveResult, rendering events as they arrive.\n\t * Wraps the result's dispose to flush pending events.\n\t */\n\tprivate _attachFormatLogger(result: ObserveResult, options: ObserveOptions): void {\n\t\tconst format = options.format!;\n\t\tconst logger = options.logger ?? ((line: string) => console.log(line));\n\t\tconst include = options.includeTypes ? new Set(options.includeTypes) : null;\n\t\tconst exclude = options.excludeTypes ? new Set(options.excludeTypes) : null;\n\t\tconst theme = resolveObserveTheme(options.theme);\n\n\t\tconst shouldLog = (type: ObserveEvent[\"type\"]): boolean => {\n\t\t\tif (include?.has(type) === false) return false;\n\t\t\tif (exclude?.has(type) === true) return false;\n\t\t\treturn true;\n\t\t};\n\n\t\tconst renderEvent = (event: ObserveEvent): string => {\n\t\t\tif (format === \"json\") {\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.stringify(event);\n\t\t\t\t} catch {\n\t\t\t\t\treturn JSON.stringify({\n\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\tpath: event.path,\n\t\t\t\t\t\tdata: \"[unserializable]\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst color = theme[event.type] ?? \"\";\n\t\t\tconst pathPart = event.path ? `${theme.path}${event.path}${theme.reset} ` : \"\";\n\t\t\tconst dataPart = event.data !== undefined ? ` ${describeData(event.data)}` : \"\";\n\t\t\tconst triggerPart =\n\t\t\t\tevent.trigger_dep_name != null\n\t\t\t\t\t? ` <- ${event.trigger_dep_name}`\n\t\t\t\t\t: event.trigger_dep_index != null\n\t\t\t\t\t\t? ` <- #${event.trigger_dep_index}`\n\t\t\t\t\t\t: \"\";\n\t\t\tconst batchPart = event.in_batch ? \" [batch]\" : \"\";\n\t\t\treturn `${pathPart}${color}${event.type.toUpperCase()}${theme.reset}${dataPart}${triggerPart}${batchPart}`;\n\t\t};\n\n\t\t// Poll-free event flushing: watch the events array length via a cursor.\n\t\t// The fallback ObserveResult pushes events synchronously during subscribe callbacks,\n\t\t// so we use Object.defineProperty to intercept event pushes.\n\t\tlet cursor = 0;\n\t\tconst flush = () => {\n\t\t\tconst events = result.events;\n\t\t\twhile (cursor < events.length) {\n\t\t\t\tconst event = events[cursor++];\n\t\t\t\tif (shouldLog(event.type)) {\n\t\t\t\t\tlogger(renderEvent(event), event);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Wrap the events array's push to flush on each new event.\n\t\tconst origPush = (result.events as ObserveEvent[]).push;\n\t\t(result.events as ObserveEvent[]).push = function (...items: ObserveEvent[]) {\n\t\t\tconst ret = origPush.apply(this, items);\n\t\t\tflush();\n\t\t\treturn ret;\n\t\t};\n\n\t\t// Wrap dispose to flush any remaining events.\n\t\tconst origDispose = result.dispose.bind(result);\n\t\t(result as { dispose(): void }).dispose = () => {\n\t\t\torigDispose();\n\t\t\tflush();\n\t\t};\n\t}\n\n\t/**\n\t * CLI/debug-friendly graph dump built on {@link Graph.describe}.\n\t *\n\t * @param options - Optional actor/filter/format toggles.\n\t * @returns Rendered graph text.\n\t */\n\tdumpGraph(options: GraphDumpOptions = {}): string {\n\t\tconst { expand: _, ...described } = this.describe({\n\t\t\tactor: options.actor,\n\t\t\tfilter: options.filter,\n\t\t\tdetail: \"standard\",\n\t\t});\n\t\tconst includeEdges = options.includeEdges ?? true;\n\t\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\t\tif (options.format === \"json\") {\n\t\t\tconst payload: GraphDescribeOutput = {\n\t\t\t\t...described,\n\t\t\t\tedges: includeEdges ? described.edges : [],\n\t\t\t\tsubgraphs: includeSubgraphs ? described.subgraphs : [],\n\t\t\t};\n\t\t\tconst text = JSON.stringify(sortJsonValue(payload), null, options.indent ?? 2);\n\t\t\toptions.logger?.(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tconst lines: string[] = [];\n\t\tlines.push(`Graph ${described.name}`);\n\t\tlines.push(\"Nodes:\");\n\t\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\t\tconst n = described.nodes[path]!;\n\t\t\tlines.push(`- ${path} (${n.type}/${n.status}): ${describeData(n.value)}`);\n\t\t}\n\t\tif (includeEdges) {\n\t\t\tlines.push(\"Edges:\");\n\t\t\tfor (const edge of described.edges) {\n\t\t\t\tlines.push(`- ${edge.from} -> ${edge.to}`);\n\t\t\t}\n\t\t}\n\t\tif (includeSubgraphs) {\n\t\t\tlines.push(\"Subgraphs:\");\n\t\t\tfor (const sg of described.subgraphs) {\n\t\t\t\tlines.push(`- ${sg}`);\n\t\t\t}\n\t\t}\n\t\tconst text = lines.join(\"\\n\");\n\t\toptions.logger?.(text);\n\t\treturn text;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Lifecycle & persistence (§3.7–§3.8)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Register a cleanup function to be called on {@link Graph.destroy}.\n\t *\n\t * Factories use this to attach teardown logic for internal nodes, keepalive\n\t * subscriptions, or other resources that are not registered on the graph and\n\t * would otherwise leak on repeated create/destroy cycles.\n\t *\n\t * Returns a removal function — call it to unregister the disposer early.\n\t */\n\taddDisposer(fn: () => void): () => void {\n\t\tthis._disposers.add(fn);\n\t\treturn () => {\n\t\t\tthis._disposers.delete(fn);\n\t\t};\n\t}\n\n\t/**\n\t * Drains disposers (registered via {@link addDisposer}), then sends `[[TEARDOWN]]` to all\n\t * nodes and clears registries on this graph and every mounted subgraph (§3.7).\n\t * The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\t// Drain disposers (keepalive unsubs etc.) BEFORE TEARDOWN so that\n\t\t// internal effect nodes are disconnected before the cascade fires.\n\t\tfor (const dispose of [...this._disposers]) {\n\t\t\ttry {\n\t\t\t\tdispose();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t\tthis._disposers.clear();\n\t\tthis.signal([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tfor (const dispose of [...this._autoCheckpointDisposers]) {\n\t\t\ttry {\n\t\t\t\tdispose();\n\t\t\t} catch {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t\tthis._autoCheckpointDisposers.clear();\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/** Clear structure after parent already signaled TEARDOWN through this subtree. */\n\tprivate _destroyClearOnly(): void {\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._edges.clear();\n\t}\n\n\t/**\n\t * Serializes structure and current values to JSON-shaped data (§3.8). Same information\n\t * as {@link Graph.describe} plus a `version` field for format evolution.\n\t *\n\t * @returns Persistable snapshot with sorted keys.\n\t */\n\tsnapshot(): GraphPersistSnapshot {\n\t\tconst { expand: _, ...d } = this.describe({ detail: \"full\" });\n\t\t// Explicit key sorting for deterministic output — don't rely on\n\t\t// describe() iteration order (audit batch-3, §3.8).\n\t\t// Strip non-restorable fields (runtime attribution) so snapshot → restore → snapshot\n\t\t// is idempotent. Use describe({ detail: \"full\" }) for audit snapshots instead.\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = d.nodes[key]!;\n\t\t\tsortedNodes[key] = node;\n\t\t}\n\t\tconst sortedSubgraphs = [...d.subgraphs].sort();\n\t\treturn { ...d, version: 1, nodes: sortedNodes, subgraphs: sortedSubgraphs };\n\t}\n\n\t/**\n\t * Apply persisted values onto an existing graph whose topology matches the snapshot\n\t * (§3.8). Only {@link DescribeNodeOutput.type} `state` and `producer` entries with a\n\t * `value` field are written; `derived` / `operator` / `effect` are skipped so deps\n\t * drive recomputation. Unknown paths are ignored.\n\t *\n\t * @param data - Snapshot envelope with matching `name` and node slices.\n\t * @throws If `data.name` does not equal {@link Graph.name}.\n\t */\n\trestore(data: GraphPersistSnapshot, options?: { only?: string | readonly string[] }): void {\n\t\tparseSnapshotEnvelope(data);\n\t\tif (data.name !== this.name) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": restore snapshot name \"${data.name}\" does not match this graph`,\n\t\t\t);\n\t\t}\n\t\tconst onlyPatterns =\n\t\t\toptions?.only == null\n\t\t\t\t? null\n\t\t\t\t: (Array.isArray(options.only) ? options.only : [options.only]).map((p) => globToRegex(p));\n\t\tfor (const path of Object.keys(data.nodes).sort()) {\n\t\t\tif (onlyPatterns !== null && !onlyPatterns.some((re) => re.test(path))) continue;\n\t\t\tconst slice = data.nodes[path];\n\t\t\tif (slice === undefined || slice.value === undefined) continue;\n\t\t\tif (slice.type === \"derived\" || slice.type === \"operator\" || slice.type === \"effect\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.set(path, slice.value);\n\t\t\t} catch {\n\t\t\t\t/* missing path or set not applicable */\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a graph named from the snapshot, optionally runs `build` to register nodes\n\t * and mounts, then {@link Graph.restore} values (§3.8).\n\t *\n\t * @param data - Snapshot envelope (`version` checked).\n\t * @param build - Optional callback to construct topology before values are applied.\n\t * @returns Hydrated `Graph` instance.\n\t */\n\tstatic fromSnapshot(data: GraphPersistSnapshot, build?: (g: Graph) => void): Graph {\n\t\tparseSnapshotEnvelope(data);\n\t\tconst g = new Graph(data.name);\n\t\tif (build) {\n\t\t\tbuild(g);\n\t\t\tg.restore(data);\n\t\t\treturn g;\n\t\t}\n\t\t// Auto-create mount hierarchy from subgraphs.\n\t\tfor (const mount of [...data.subgraphs].sort((a, b) => {\n\t\t\tconst da = a.split(PATH_SEP).length;\n\t\t\tconst db = b.split(PATH_SEP).length;\n\t\t\tif (da !== db) return da - db;\n\t\t\tif (a < b) return -1;\n\t\t\tif (a > b) return 1;\n\t\t\treturn 0;\n\t\t})) {\n\t\t\tconst parts = mount.split(PATH_SEP);\n\t\t\tlet target: Graph = g;\n\t\t\tfor (const seg of parts) {\n\t\t\t\tif (!target._mounts.has(seg)) {\n\t\t\t\t\ttarget.mount(seg, new Graph(seg));\n\t\t\t\t}\n\t\t\t\ttarget = target._mounts.get(seg)!;\n\t\t\t}\n\t\t}\n\n\t\tconst primaryEntries = Object.entries(data.nodes)\n\t\t\t.filter(([path]) => !path.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`))\n\t\t\t.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst pending = new Map(primaryEntries);\n\t\tconst created = new Map<string, Node>();\n\n\t\tlet progressed = true;\n\t\twhile (pending.size > 0 && progressed) {\n\t\t\tprogressed = false;\n\t\t\tfor (const [path, slice] of [...pending.entries()]) {\n\t\t\t\tconst deps = slice?.deps ?? [];\n\t\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\t\t\t\tconst [owner, localName] = Graph._ownerForPath(g, path);\n\t\t\t\tconst meta: Record<string, unknown> = { ...(slice?.meta ?? {}) };\n\t\t\t\tconst factory = Graph._factoryForPath(path);\n\t\t\t\tlet node: Node;\n\t\t\t\tif (slice?.type === \"state\") {\n\t\t\t\t\tnode = stateNode(slice.value, { meta });\n\t\t\t\t} else {\n\t\t\t\t\tif (factory == null) continue;\n\t\t\t\t\tnode = factory(localName, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\ttype: slice.type,\n\t\t\t\t\t\tvalue: slice.value,\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tresolvedDeps: deps.map((dep) => created.get(dep)!),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\towner.add(localName, node);\n\t\t\t\tcreated.set(path, node);\n\t\t\t\tpending.delete(path);\n\t\t\t\tprogressed = true;\n\t\t\t}\n\t\t}\n\t\tif (pending.size > 0) {\n\t\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`Graph.fromSnapshot could not reconstruct nodes without build callback: ${unresolved}. ` +\n\t\t\t\t\t`Register matching factories with Graph.registerFactory(pattern, factory).`,\n\t\t\t);\n\t\t}\n\t\tfor (const edge of data.edges) {\n\t\t\ttry {\n\t\t\t\tg.connect(edge.from, edge.to);\n\t\t\t} catch {\n\t\t\t\t/* ignore malformed or non-reconstructable edge */\n\t\t\t}\n\t\t}\n\t\tg.restore(data);\n\t\treturn g;\n\t}\n\n\t/**\n\t * Plain snapshot object with **recursively sorted object keys** for deterministic serialization (§3.8).\n\t *\n\t * @remarks\n\t * For a single UTF-8 string with a trailing newline (convenient for git), use {@link Graph.toJSONString}.\n\t *\n\t * @returns Same object as {@link Graph.snapshot}.\n\t */\n\ttoObject(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * ECMAScript `JSON.stringify` hook — delegates to {@link Graph.toObject}.\n\t *\n\t * @remarks\n\t * Must return a plain object (not a string) so `JSON.stringify(graph)` works correctly\n\t * without double-encoding.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.toObject();\n\t}\n\n\t/**\n\t * Deterministic JSON **text**: `JSON.stringify` of {@link Graph.toObject} plus a trailing newline (§3.8).\n\t *\n\t * @returns Stable string suitable for diffs.\n\t */\n\ttoJSONString(): string {\n\t\treturn stableJsonStringify(this.snapshot());\n\t}\n\n\t/**\n\t * Debounced persistence wired to graph-wide observe stream (spec §3.8 auto-checkpoint).\n\t *\n\t * Checkpoint trigger uses {@link messageTier}: only batches containing tier >= 3 messages\n\t * schedule a save (`DATA`/`RESOLVED`/terminal/destruction), never pure tier-0/1/2 control\n\t * waves (`START`/`DIRTY`/`INVALIDATE`/`PAUSE`/`RESUME`).\n\t */\n\tautoCheckpoint(\n\t\tadapter: AutoCheckpointAdapter,\n\t\toptions: GraphAutoCheckpointOptions = {},\n\t): GraphAutoCheckpointHandle {\n\t\tconst debounceMs = Math.max(0, options.debounceMs ?? 500);\n\t\tconst compactEvery = Math.max(1, options.compactEvery ?? 10);\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet seq = 0;\n\t\tlet pending = false;\n\t\tlet lastDescribe: GraphDescribeOutput | undefined;\n\n\t\tconst flush = () => {\n\t\t\ttimer = undefined;\n\t\t\tif (!pending) return;\n\t\t\tpending = false;\n\t\t\ttry {\n\t\t\t\tconst { expand: _expand, ...raw } = this.describe({ detail: \"full\" });\n\t\t\t\t// Strip non-restorable fields for persistence idempotency\n\t\t\t\tconst cleanNodes: Record<string, DescribeNodeOutput> = {};\n\t\t\t\tfor (const [p, n] of Object.entries(raw.nodes)) {\n\t\t\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = n!;\n\t\t\t\t\tcleanNodes[p] = node;\n\t\t\t\t}\n\t\t\t\tconst described = { ...raw, nodes: cleanNodes };\n\t\t\t\tconst snapshot = { ...described, version: SNAPSHOT_VERSION };\n\t\t\t\tseq += 1;\n\t\t\t\tconst shouldCompact = lastDescribe == null || seq % compactEvery === 0;\n\t\t\t\tif (shouldCompact) {\n\t\t\t\t\tadapter.save(this.name, { mode: \"full\", snapshot, seq } satisfies GraphCheckpointRecord);\n\t\t\t\t} else {\n\t\t\t\t\tconst previous = lastDescribe;\n\t\t\t\t\tif (previous == null) return;\n\t\t\t\t\tadapter.save(this.name, {\n\t\t\t\t\t\tmode: \"diff\",\n\t\t\t\t\t\tdiff: Graph.diff(previous, described),\n\t\t\t\t\t\tsnapshot,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t} satisfies GraphCheckpointRecord);\n\t\t\t\t}\n\t\t\t\tlastDescribe = described;\n\t\t\t} catch (error) {\n\t\t\t\toptions.onError?.(error);\n\t\t\t}\n\t\t};\n\n\t\tconst schedule = () => {\n\t\t\tpending = true;\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\ttimer = setTimeout(flush, debounceMs);\n\t\t};\n\n\t\tconst off = this.observe().subscribe((path, messages) => {\n\t\t\tconst triggeredByTier = messages.some((m) => messageTier(m[0]) >= 3);\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst nd = this.resolve(path);\n\t\t\t\tif (nd == null) return;\n\t\t\t\tconst described = describeNode(nd, resolveDescribeFields(\"standard\"));\n\t\t\t\tif (!options.filter(path, described)) return;\n\t\t\t}\n\t\t\tschedule();\n\t\t});\n\n\t\tconst dispose = () => {\n\t\t\toff();\n\t\t\tif (timer !== undefined) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = undefined;\n\t\t\t}\n\t\t\tthis._autoCheckpointDisposers.delete(dispose);\n\t\t};\n\t\tthis._autoCheckpointDisposers.add(dispose);\n\t\treturn { dispose };\n\t}\n\n\t/**\n\t * Export the current graph topology as Mermaid flowchart text.\n\t *\n\t * Renders qualified node paths and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns Mermaid flowchart source.\n\t */\n\ttoMermaid(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`flowchart ${direction}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(` ${id}[\"${escapeMermaidLabel(path)}\"]`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(` ${fromId} --> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t/**\n\t * Export the current graph topology as D2 diagram text.\n\t *\n\t * Renders qualified node paths, constructor deps, and registered edges from {@link Graph.describe}.\n\t *\n\t * @param options - Optional diagram direction (`LR` by default).\n\t * @returns D2 source text.\n\t */\n\ttoD2(options?: GraphDiagramOptions): string {\n\t\tconst direction = normalizeDiagramDirection(options?.direction);\n\t\tconst described = this.describe();\n\t\tconst paths = Object.keys(described.nodes).sort();\n\t\tconst ids = new Map<string, string>();\n\t\tfor (let i = 0; i < paths.length; i += 1) {\n\t\t\tids.set(paths[i]!, `n${i}`);\n\t\t}\n\t\tconst lines: string[] = [`direction: ${d2DirectionFromGraphDirection(direction)}`];\n\t\tfor (const path of paths) {\n\t\t\tconst id = ids.get(path)!;\n\t\t\tlines.push(`${id}: \"${escapeD2Label(path)}\"`);\n\t\t}\n\t\tfor (const [from, to] of collectDiagramArrows(described)) {\n\t\t\tconst fromId = ids.get(from);\n\t\t\tconst toId = ids.get(to);\n\t\t\tif (!fromId || !toId) continue;\n\t\t\tlines.push(`${fromId} -> ${toId}`);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Inspector (roadmap 3.3) — reasoning trace, overhead gating\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * When `false`, structured observation options (`causal`, `timeline`),\n\t * and `trace()` writes are no-ops. Raw `observe()` always works.\n\t *\n\t * Default: `true` outside production (`process.env.NODE_ENV !== \"production\"`).\n\t */\n\tstatic inspectorEnabled = !(\n\t\ttypeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n\t);\n\n\tprivate _annotations = new Map<string, string>();\n\tprivate _traceRing = new RingBuffer<TraceEntry>(1000);\n\n\t/**\n\t * Unified reasoning trace: write annotations or read the ring buffer.\n\t *\n\t * Write: `graph.trace(\"path\", \"reason\")` — attaches a reasoning annotation\n\t * to a node, capturing *why* an AI agent set a value.\n\t * No-op when {@link Graph.inspectorEnabled} is `false`.\n\t *\n\t * Read: `graph.trace()` — returns a chronological log of all annotations.\n\t * Returns `[]` when {@link Graph.inspectorEnabled} is `false`.\n\t */\n\ttrace(path: string, reason: string): void;\n\ttrace(): readonly TraceEntry[];\n\ttrace(path?: string, reason?: string): undefined | readonly TraceEntry[] {\n\t\tif (path != null && reason != null) {\n\t\t\tif (!Graph.inspectorEnabled) return;\n\t\t\tthis.resolve(path); // validate path exists\n\t\t\tthis._annotations.set(path, reason);\n\t\t\tthis._traceRing.push({ path, reason, timestamp_ns: monotonicNs() });\n\t\t\treturn;\n\t\t}\n\t\tif (!Graph.inspectorEnabled) return [];\n\t\treturn this._traceRing.toArray();\n\t}\n\n\t/**\n\t * Computes structural + value diff between two {@link Graph.describe} snapshots.\n\t *\n\t * @param a - Earlier describe output.\n\t * @param b - Later describe output.\n\t * @returns Added/removed nodes, changed fields, and edge deltas.\n\t */\n\tstatic diff(a: GraphDescribeOutput, b: GraphDescribeOutput): GraphDiffResult {\n\t\tconst aKeys = new Set(Object.keys(a.nodes));\n\t\tconst bKeys = new Set(Object.keys(b.nodes));\n\n\t\tconst nodesAdded = [...bKeys].filter((k) => !aKeys.has(k)).sort();\n\t\tconst nodesRemoved = [...aKeys].filter((k) => !bKeys.has(k)).sort();\n\t\tconst nodesChanged: GraphDiffChange[] = [];\n\n\t\tfor (const key of aKeys) {\n\t\t\tif (!bKeys.has(key)) continue;\n\t\t\tconst na = a.nodes[key];\n\t\t\tconst nb = b.nodes[key];\n\t\t\t// V0 optimization: skip value comparison when both nodes have matching versions.\n\t\t\tconst av = na.v;\n\t\t\tconst bv = nb.v;\n\t\t\tif (av != null && bv != null && av.id === bv.id && av.version === bv.version) {\n\t\t\t\t// Version unchanged — only check type/status (cheap string compare).\n\t\t\t\tfor (const field of [\"type\", \"status\"] as const) {\n\t\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\t\tif (va !== vb) {\n\t\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const field of [\"type\", \"status\", \"value\"] as const) {\n\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\tif (!Object.is(va, vb) && JSON.stringify(va) !== JSON.stringify(vb)) {\n\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst edgeKey = (e: { from: string; to: string }) => `${e.from}\\t${e.to}`;\n\t\tconst aEdges = new Set(a.edges.map(edgeKey));\n\t\tconst bEdges = new Set(b.edges.map(edgeKey));\n\n\t\tconst edgesAdded = b.edges.filter((e) => !aEdges.has(edgeKey(e)));\n\t\tconst edgesRemoved = a.edges.filter((e) => !bEdges.has(edgeKey(e)));\n\t\tconst aSubgraphs = new Set(a.subgraphs);\n\t\tconst bSubgraphs = new Set(b.subgraphs);\n\t\tconst subgraphsAdded = [...bSubgraphs].filter((s) => !aSubgraphs.has(s)).sort();\n\t\tconst subgraphsRemoved = [...aSubgraphs].filter((s) => !bSubgraphs.has(s)).sort();\n\n\t\treturn {\n\t\t\tnodesAdded,\n\t\t\tnodesRemoved,\n\t\t\tnodesChanged,\n\t\t\tedgesAdded,\n\t\t\tedgesRemoved,\n\t\t\tsubgraphsAdded,\n\t\t\tsubgraphsRemoved,\n\t\t};\n\t}\n}\n\n/** Entry in the reasoning trace ring buffer (roadmap 3.3). */\nexport type TraceEntry = {\n\tpath: string;\n\treason: string;\n\ttimestamp_ns: number;\n};\n\n/** Result of {@link Graph.diff}. */\nexport type GraphDiffResult = {\n\tnodesAdded: string[];\n\tnodesRemoved: string[];\n\tnodesChanged: GraphDiffChange[];\n\tedgesAdded: Array<{ from: string; to: string }>;\n\tedgesRemoved: Array<{ from: string; to: string }>;\n\tsubgraphsAdded: string[];\n\tsubgraphsRemoved: string[];\n};\n\n/** A single field change within a diff. */\nexport type GraphDiffChange = {\n\tpath: string;\n\tfield: string;\n\tfrom: unknown;\n\tto: unknown;\n};\n\n/** Direction for {@link reachable} graph traversal. */\nexport type ReachableDirection = \"upstream\" | \"downstream\";\n\n/** Options for {@link reachable}. */\nexport type ReachableOptions = {\n\t/** Maximum hop depth from `from` (0 returns `[]`). Omit for unbounded traversal. */\n\tmaxDepth?: number;\n};\n\n/**\n * Reachability query over a {@link Graph.describe} snapshot.\n *\n * Traversal combines dependency links (`deps`) and explicit graph edges (`edges`):\n * - `upstream`: follows `deps` plus incoming edges.\n * - `downstream`: follows reverse-`deps` plus outgoing edges.\n *\n * @param described - `graph.describe()` output to traverse.\n * @param from - Start path (qualified node path).\n * @param direction - Traversal direction.\n * @param options - Optional max depth bound.\n * @returns Sorted list of reachable paths (excluding `from`).\n *\n * @example\n * ```ts\n * import { Graph, reachable } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * const a = g.register(\"a\");\n * const b = g.register(\"b\", [a]);\n * const described = g.describe();\n *\n * reachable(described, \"app.a\", \"downstream\"); // [\"app.b\"]\n * reachable(described, \"app.b\", \"upstream\"); // [\"app.a\"]\n * ```\n */\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions: ReachableOptions = {},\n): string[] {\n\tif (!from) return [];\n\tif (direction !== \"upstream\" && direction !== \"downstream\") {\n\t\tthrow new Error(`reachable: direction must be \"upstream\" or \"downstream\"`);\n\t}\n\tconst maxDepth = options.maxDepth;\n\tif (maxDepth != null && (!Number.isInteger(maxDepth) || maxDepth < 0)) {\n\t\tthrow new Error(`reachable: maxDepth must be an integer >= 0`);\n\t}\n\tif (maxDepth === 0) return [];\n\n\tconst depsByPath = new Map<string, string[]>();\n\tconst reverseDeps = new Map<string, Set<string>>();\n\tconst incomingEdges = new Map<string, Set<string>>();\n\tconst outgoingEdges = new Map<string, Set<string>>();\n\tconst universe = new Set<string>();\n\n\tconst nodesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"nodes\" in described &&\n\t\ttypeof (described as Record<string, unknown>).nodes === \"object\" &&\n\t\t(described as Record<string, unknown>).nodes !== null &&\n\t\t!Array.isArray((described as Record<string, unknown>).nodes)\n\t\t\t? ((described as Record<string, unknown>).nodes as Record<string, unknown>)\n\t\t\t: {};\n\tconst edgesRaw =\n\t\tdescribed != null &&\n\t\ttypeof described === \"object\" &&\n\t\t\"edges\" in described &&\n\t\tArray.isArray((described as Record<string, unknown>).edges)\n\t\t\t? ((described as Record<string, unknown>).edges as unknown[])\n\t\t\t: [];\n\n\tfor (const [path, node] of Object.entries(nodesRaw)) {\n\t\tif (!path) continue;\n\t\tuniverse.add(path);\n\t\tconst deps =\n\t\t\tnode != null && typeof node === \"object\" && Array.isArray((node as { deps?: unknown[] }).deps)\n\t\t\t\t? (node as { deps: unknown[] }).deps\n\t\t\t\t: [];\n\t\tconst cleanDeps = deps.filter((d): d is string => typeof d === \"string\" && d.length > 0);\n\t\tdepsByPath.set(path, cleanDeps);\n\t\tfor (const dep of cleanDeps) {\n\t\t\tuniverse.add(dep);\n\t\t\tif (!reverseDeps.has(dep)) reverseDeps.set(dep, new Set());\n\t\t\treverseDeps.get(dep)!.add(path);\n\t\t}\n\t}\n\tfor (const edge of edgesRaw) {\n\t\tif (edge == null || typeof edge !== \"object\") continue;\n\t\tconst edgeFrom =\n\t\t\t\"from\" in edge && typeof (edge as { from?: unknown }).from === \"string\"\n\t\t\t\t? ((edge as { from: string }).from as string)\n\t\t\t\t: \"\";\n\t\tconst edgeTo =\n\t\t\t\"to\" in edge && typeof (edge as { to?: unknown }).to === \"string\"\n\t\t\t\t? ((edge as { to: string }).to as string)\n\t\t\t\t: \"\";\n\t\tif (!edgeFrom || !edgeTo) continue;\n\t\tuniverse.add(edgeFrom);\n\t\tuniverse.add(edgeTo);\n\t\tif (!outgoingEdges.has(edgeFrom)) outgoingEdges.set(edgeFrom, new Set());\n\t\toutgoingEdges.get(edgeFrom)!.add(edgeTo);\n\t\tif (!incomingEdges.has(edgeTo)) incomingEdges.set(edgeTo, new Set());\n\t\tincomingEdges.get(edgeTo)!.add(edgeFrom);\n\t}\n\n\tif (!universe.has(from)) return [];\n\n\tconst neighbors = (path: string): string[] => {\n\t\tif (direction === \"upstream\") {\n\t\t\tconst depNeighbors = depsByPath.get(path) ?? [];\n\t\t\tconst edgeNeighbors = [...(incomingEdges.get(path) ?? [])];\n\t\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t\t}\n\t\tconst depNeighbors = [...(reverseDeps.get(path) ?? [])];\n\t\tconst edgeNeighbors = [...(outgoingEdges.get(path) ?? [])];\n\t\treturn [...depNeighbors, ...edgeNeighbors];\n\t};\n\n\tconst visited = new Set<string>([from]);\n\tconst out = new Set<string>();\n\tconst queue: Array<{ path: string; depth: number }> = [{ path: from, depth: 0 }];\n\twhile (queue.length > 0) {\n\t\tconst next = queue.shift()!;\n\t\tif (maxDepth != null && next.depth >= maxDepth) continue;\n\t\tfor (const nb of neighbors(next.path)) {\n\t\t\tif (!nb || visited.has(nb)) continue;\n\t\t\tvisited.add(nb);\n\t\t\tout.add(nb);\n\t\t\tqueue.push({ path: nb, depth: next.depth + 1 });\n\t\t}\n\t}\n\n\treturn [...out].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n","/**\n * Reactive append-only log (roadmap §3.2) — emits `readonly T[]` snapshots directly.\n *\n * Internal version counter drives efficient equality without leaking `Versioned`\n * into the public API (spec §5.12).\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\";\n\nexport type ReactiveLogOptions = {\n\tname?: string;\n\tmaxSize?: number;\n};\n\nexport type ReactiveLogBundle<T> = {\n\t/** Emits `readonly T[]` on each append/clear (two-phase). */\n\treadonly entries: Node<readonly 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\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 immutable array 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\n\tconst entries = state<readonly T[]>(buf.length > 0 ? [...buf] : [], {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: (a, b) => a === b,\n\t});\n\n\tfunction pushSnapshot(): void {\n\t\tconst snapshot: readonly T[] = [...buf];\n\t\tbatch(() => {\n\t\t\tentries.down([[DIRTY]]);\n\t\t\tentries.down([[DATA, snapshot]]);\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 e = entries.get() as readonly T[];\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 readonly T[];\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 e = log.entries.get() as readonly T[];\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 readonly T[];\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 * 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 { 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<readonly 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<readonly 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<readonly CqrsEvent[]>(\n\t\t\t[entries],\n\t\t\t([snapshot]) => snapshot as readonly 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 readonly 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 entries = snapshot as readonly CqrsEvent[];\n\t\t\t\t\tallEvents.push(...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 entries = snapshots[i] as readonly CqrsEvent<T>[];\n\t\t\t\t\tconst eName = eventNames[i];\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?: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