@graphrefly/graphrefly 0.22.0 → 0.23.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-RHI3GHZW.js → chunk-263BEJJO.js} +3 -3
- package/dist/{chunk-44HD4BTA.js → chunk-2GQLMQVJ.js} +3 -3
- package/dist/chunk-32N5A454.js +36 -0
- package/dist/chunk-32N5A454.js.map +1 -0
- package/dist/{chunk-IR3KMOLX.js → chunk-CWYPA63G.js} +3 -383
- package/dist/chunk-CWYPA63G.js.map +1 -0
- package/dist/{chunk-TH6COGOP.js → chunk-HVBX5KIW.js} +2 -2
- package/dist/chunk-JFONSPNF.js +391 -0
- package/dist/chunk-JFONSPNF.js.map +1 -0
- package/dist/{chunk-QA3RP5NH.js → chunk-NZMBRXQV.js} +101 -5
- package/dist/chunk-NZMBRXQV.js.map +1 -0
- package/dist/{chunk-MQBQOFDS.js → chunk-PNUZM7PC.js} +12 -31
- package/dist/chunk-PNUZM7PC.js.map +1 -0
- package/dist/{chunk-EQUZ5NLD.js → chunk-PX6PDUJ5.js} +11 -16
- package/dist/chunk-PX6PDUJ5.js.map +1 -0
- package/dist/{chunk-NXC35KC5.js → chunk-XRFJJ2IU.js} +3 -3
- package/dist/{chunk-BLD3IFYF.js → chunk-XTLYW4FR.js} +9 -7
- package/dist/{chunk-BLD3IFYF.js.map → chunk-XTLYW4FR.js.map} +1 -1
- package/dist/compat/nestjs/index.cjs +100 -4
- package/dist/compat/nestjs/index.cjs.map +1 -1
- package/dist/compat/nestjs/index.d.cts +6 -6
- package/dist/compat/nestjs/index.d.ts +6 -6
- package/dist/compat/nestjs/index.js +9 -7
- package/dist/core/index.cjs +100 -4
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/core/index.js +3 -3
- package/dist/extra/index.cjs +100 -4
- 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 +9 -7
- package/dist/graph/index.cjs +100 -4
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +5 -5
- package/dist/graph/index.d.ts +5 -5
- package/dist/graph/index.js +4 -4
- package/dist/{graph-ab1yPwIB.d.cts → graph-BtdSRHUc.d.cts} +3 -3
- package/dist/{graph-DFr0diXB.d.ts → graph-CEO2FkLY.d.ts} +3 -3
- package/dist/{index-BvWfZCTt.d.cts → index-B0tfuXwV.d.cts} +3 -3
- package/dist/{index-Dy04P4W3.d.cts → index-BFGjXbiP.d.cts} +2 -2
- package/dist/{index-DrJq9B1T.d.cts → index-BPlWVAKY.d.cts} +3 -3
- package/dist/{index-C9z6rU9P.d.cts → index-BUj3ASVe.d.cts} +25 -7
- package/dist/{index-DLE1Sp-L.d.cts → index-C59uSJAH.d.cts} +2 -2
- package/dist/{index-DsGxLfwL.d.ts → index-CkElcUY6.d.ts} +2 -2
- package/dist/{index-HdJx_BjO.d.ts → index-DSPc5rkv.d.ts} +25 -7
- package/dist/{index-D36MAQ3f.d.ts → index-DgscL7v0.d.ts} +3 -3
- package/dist/{index-BbYZma8G.d.ts → index-RXN94sHK.d.ts} +3 -3
- package/dist/{index-BHm3Ba5q.d.ts → index-jEtF4N7L.d.ts} +2 -2
- package/dist/index.cjs +109 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -15
- package/dist/index.d.ts +15 -15
- package/dist/index.js +26 -22
- package/dist/index.js.map +1 -1
- package/dist/{meta-n3FoVWML.d.ts → meta-3QjzotRv.d.ts} +1 -1
- package/dist/{meta--fr9sxRM.d.cts → meta-B-Lbs4-O.d.cts} +1 -1
- package/dist/{node-C5UD5MGq.d.cts → node-C7PD3sn9.d.cts} +42 -0
- package/dist/{node-C5UD5MGq.d.ts → node-C7PD3sn9.d.ts} +42 -0
- package/dist/{observable-CQRBtEbq.d.ts → observable-EyO-moQY.d.ts} +1 -1
- package/dist/{observable-DWydVy5b.d.cts → observable-axpzv1K2.d.cts} +1 -1
- package/dist/patterns/reactive-layout/index.cjs +214 -117
- package/dist/patterns/reactive-layout/index.cjs.map +1 -1
- package/dist/patterns/reactive-layout/index.d.cts +5 -5
- package/dist/patterns/reactive-layout/index.d.ts +5 -5
- package/dist/patterns/reactive-layout/index.js +6 -4
- package/dist/{storage-C9fZfMfM.d.ts → storage-CHT5WE9m.d.ts} +1 -1
- package/dist/{storage-Bew05Xy6.d.cts → storage-DIgAr7M_.d.cts} +1 -1
- package/package.json +2 -1
- package/dist/chunk-EQUZ5NLD.js.map +0 -1
- package/dist/chunk-IR3KMOLX.js.map +0 -1
- package/dist/chunk-MQBQOFDS.js.map +0 -1
- package/dist/chunk-QA3RP5NH.js.map +0 -1
- /package/dist/{chunk-RHI3GHZW.js.map → chunk-263BEJJO.js.map} +0 -0
- /package/dist/{chunk-44HD4BTA.js.map → chunk-2GQLMQVJ.js.map} +0 -0
- /package/dist/{chunk-TH6COGOP.js.map → chunk-HVBX5KIW.js.map} +0 -0
- /package/dist/{chunk-NXC35KC5.js.map → chunk-XRFJJ2IU.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/compat/index.ts","../src/compat/jotai/index.ts","../src/compat/nanostores/index.ts","../src/compat/react/index.ts","../src/compat/signals/index.ts","../src/compat/solid/index.ts","../src/compat/svelte/index.ts","../src/compat/vue/index.ts","../src/compat/zustand/index.ts","../src/patterns/index.ts","../src/patterns/ai.ts","../src/patterns/memory.ts","../src/patterns/messaging.ts","../src/patterns/orchestration.ts","../src/patterns/demo-shell.ts","../src/patterns/domain-templates.ts","../src/patterns/reduction.ts","../src/patterns/graphspec.ts","../src/patterns/harness/index.ts","../src/patterns/harness/bridge.ts","../src/patterns/harness/types.ts","../src/patterns/harness/strategy.ts","../src/patterns/harness/loop.ts","../src/patterns/harness/profile.ts","../src/patterns/harness/trace.ts","../src/index.ts"],"sourcesContent":["/**\n * Compat layer: compatibility wrappers for other state management libraries (Phase 5.1b).\n *\n * Framework adapters are optional peers. Install only what you use:\n * - `@graphrefly/graphrefly-ts/compat/react` -> `react`, `react-dom`\n * - `@graphrefly/graphrefly-ts/compat/vue` -> `vue`\n * - `@graphrefly/graphrefly-ts/compat/svelte` -> `svelte`\n * - `@graphrefly/graphrefly-ts/compat/solid` -> `solid-js`\n */\nexport * as jotai from \"./jotai/index.js\";\nexport * as nanostores from \"./nanostores/index.js\";\nexport * as nestjs from \"./nestjs/index.js\";\nexport * as react from \"./react/index.js\";\nexport * as signals from \"./signals/index.js\";\nexport * as solid from \"./solid/index.js\";\nexport * as svelte from \"./svelte/index.js\";\nexport * as vue from \"./vue/index.js\";\nexport * as zustand from \"./zustand/index.js\";\n","import { DATA, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { autoTrackNode, state } from \"../../core/sugar.js\";\n\n/**\n * Options for creating an atom.\n *\n * @category compat\n */\nexport interface AtomOptions {\n\t/** Optional identifier for the underlying node. */\n\tname?: string;\n\t/** Optional companion meta nodes. */\n\tmeta?: Record<string, unknown>;\n}\n\n/**\n * A read-only Jotai-compatible atom.\n *\n * @category compat\n */\nexport interface ReadableAtom<T> {\n\t/** Returns the current cached value. */\n\tget(): T;\n\t/** Subscribes to value changes. Returns an unsubscribe function. */\n\tsubscribe(callback: (value: T) => void): () => void;\n\t/** Access to companion meta nodes. */\n\treadonly meta: Record<string, Node>;\n\t/** @internal The underlying GraphReFly node. */\n\t_node: Node<T>;\n}\n\n/**\n * A writable Jotai-compatible atom.\n *\n * @category compat\n */\nexport interface WritableAtom<T> extends ReadableAtom<T> {\n\t/** Sets a new value. */\n\tset(value: T): void;\n\t/** Updates the value using a transformation function. */\n\tupdate(fn: (current: T) => T): void;\n}\n\n/** Function type for reading other atoms inside a derived atom. */\nexport type GetFn = <V>(a: ReadableAtom<V>) => V;\n/** Function type for writing to other atoms inside a writable derived atom. */\nexport type SetFn = <V>(a: WritableAtom<V>, value: V) => void;\n\n/** Function that computes the atom's value. */\nexport type ReadFn<T> = (get: GetFn) => T;\n/** Function that handles writes to the atom. */\nexport type WriteFn<T> = (get: GetFn, set: SetFn, value: T) => void;\n\n/**\n * Creates a Jotai-compatible atom built on GraphReFly primitives.\n *\n * Supports three overloads:\n * 1. `atom(initial)` — Writable primitive atom (wraps `state()`).\n * 2. `atom(read)` — Read-only derived atom (wraps `dynamicNode()`).\n * 3. `atom(read, write)` — Writable derived atom.\n *\n * @param initialOrRead - Initial value or a read function.\n * @param writeOrOptions - Write function or options object.\n * @param options - Optional configuration.\n * @returns WritableAtom or ReadableAtom.\n *\n * @example\n * ```ts\n * const count = atom(0);\n * count.set(1);\n * const doubled = atom((get) => get(count)! * 2);\n * ```\n *\n * @category compat\n */\nexport function atom<T>(initial: T, options?: AtomOptions): WritableAtom<T>;\nexport function atom<T>(read: ReadFn<T>, options?: AtomOptions): ReadableAtom<T>;\nexport function atom<T>(read: ReadFn<T>, write: WriteFn<T>, options?: AtomOptions): WritableAtom<T>;\nexport function atom<T>(\n\tinitialOrRead: T | ReadFn<T>,\n\twriteOrOptions?: WriteFn<T> | AtomOptions,\n\toptions?: AtomOptions,\n): ReadableAtom<T> | WritableAtom<T> {\n\tif (typeof initialOrRead === \"function\") {\n\t\tconst read = initialOrRead as ReadFn<T>;\n\t\tif (typeof writeOrOptions === \"function\") {\n\t\t\treturn createDerivedAtom(read, writeOrOptions as WriteFn<T>, options);\n\t\t}\n\t\treturn createDerivedAtom(read, undefined, writeOrOptions as AtomOptions);\n\t}\n\n\treturn createPrimitiveAtom(initialOrRead as T, writeOrOptions as AtomOptions);\n}\n\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined | null = n.cache;\n\tlet err: any;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t\tif (t === ERROR) err = v;\n\t\t}\n\t});\n\tunsub();\n\tif (err) throw err;\n\treturn val as T;\n}\n\nfunction createPrimitiveAtom<T>(initial: T, options?: AtomOptions): WritableAtom<T> {\n\tconst n = state(initial, {\n\t\t...options,\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t});\n\treturn {\n\t\tget: () => {\n\t\t\tif (n.status === \"sentinel\") {\n\t\t\t\treturn pull(n);\n\t\t\t}\n\t\t\treturn n.cache as T;\n\t\t},\n\t\t// Use `n.emit` (not raw `n.down`) so writes go through the framed\n\t\t// emit pipeline: bundle() auto-prefixes DIRTY (diamond-safe wave\n\t\t// coordination) and the equals check folds same-value writes to\n\t\t// RESOLVED (no spurious subscriber fires).\n\t\tset: (value: T) => n.emit(value),\n\t\tupdate: (fn: (current: T) => T) => {\n\t\t\tconst current = n.status === \"sentinel\" ? pull(n) : (n.cache as T);\n\t\t\tn.emit(fn(current));\n\t\t},\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\t// Skip the initial push-on-subscribe DATA — jotai subscribe fires on changes only.\n\t\t\tlet initial = true;\n\t\t\treturn n.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcb(v as T);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tmeta: n.meta,\n\t\t_node: n,\n\t};\n}\n\nfunction createDerivedAtom<T>(\n\tread: ReadFn<T>,\n\twrite?: WriteFn<T>,\n\toptions?: AtomOptions,\n): ReadableAtom<T> | WritableAtom<T> {\n\tconst n = autoTrackNode(\n\t\t(track) =>\n\t\t\tread(<V>(a: ReadableAtom<V>) => {\n\t\t\t\tconst dn = a._node;\n\t\t\t\tif (dn.status === \"sentinel\") {\n\t\t\t\t\tpull(dn);\n\t\t\t\t}\n\t\t\t\treturn track(dn) as V;\n\t\t\t}),\n\t\t{\n\t\t\t...options,\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t},\n\t);\n\n\tconst result: ReadableAtom<T> = {\n\t\tget: () => {\n\t\t\tif (n.status === \"sentinel\") {\n\t\t\t\treturn pull(n);\n\t\t\t}\n\t\t\treturn n.cache as T;\n\t\t},\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\t// Skip the initial push-on-subscribe DATA — jotai subscribe fires on changes only.\n\t\t\tlet initial = true;\n\t\t\treturn n.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcb(v as T);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tmeta: n.meta,\n\t\t_node: n,\n\t};\n\n\tif (write) {\n\t\tconst getFn: GetFn = <V>(a: ReadableAtom<V>) => a.get();\n\t\tconst setFn: SetFn = <V>(a: WritableAtom<V>, value: V) => a.set(value);\n\n\t\tconst writable = result as WritableAtom<T>;\n\t\twritable.set = (value: T) => write(getFn, setFn, value);\n\t\twritable.update = (fn: (current: T) => T) => {\n\t\t\tconst current = n.status === \"sentinel\" ? pull(n) : (n.cache as T);\n\t\t\treturn write(getFn, setFn, fn(current));\n\t\t};\n\t\treturn writable;\n\t}\n\n\treturn result;\n}\n","import { batch } from \"../../core/batch.js\";\nimport { DATA, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { dynamicNode, state, type TrackFn } from \"../../core/sugar.js\";\n\n/**\n * A Nanostores-compatible atom.\n *\n * @category compat\n */\nexport interface NanoAtom<T> {\n\t/** Get current value. */\n\tget(): T;\n\t/** Set a new value (writable atoms only). */\n\tset(value: T): void;\n\t/** Subscribe to value changes. Callback receives the new value.\n\t * Returns unsubscribe function. Called immediately with current value. */\n\tsubscribe(cb: (value: T) => void): () => void;\n\t/** Listen to value changes (no immediate call). Returns unsubscribe. */\n\tlisten(cb: (value: T) => void): () => void;\n\t/** The underlying GraphReFly node. */\n\treadonly _node: Node<T>;\n}\n\n/**\n * A Nanostores-compatible computed store.\n *\n * @category compat\n */\nexport interface NanoComputed<T> {\n\t/** Get current value. */\n\tget(): T;\n\t/** Subscribe to value changes. Called immediately with current value.\n\t * Returns unsubscribe function. */\n\tsubscribe(cb: (value: T) => void): () => void;\n\t/** Listen to value changes (no immediate call). Returns unsubscribe. */\n\tlisten(cb: (value: T) => void): () => void;\n\t/** The underlying GraphReFly node. */\n\treadonly _node: Node<T>;\n}\n\n/**\n * A Nanostores-compatible map.\n *\n * @category compat\n */\nexport interface NanoMap<T extends Record<string, unknown>> extends NanoAtom<T> {\n\t/** Set a single key. */\n\tsetKey<K extends keyof T>(key: K, value: T[K]): void;\n}\n\nconst START_LISTENERS = new WeakMap<Node<any>, Set<() => void>>();\nconst STOP_LISTENERS = new WeakMap<Node<any>, Set<() => void>>();\n\nfunction trigger(node: Node<any>, map: WeakMap<Node<any>, Set<() => void>>) {\n\tconst callbacks = map.get(node);\n\tif (callbacks) {\n\t\tfor (const cb of callbacks) cb();\n\t}\n}\n\nfunction createStore<T>(node: Node<T>, extra: any = {}): any {\n\tlet listeners = 0;\n\tconst store = {\n\t\t...extra,\n\t\tget: () => getVal(node),\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\tif (listeners === 0) trigger(node, START_LISTENERS);\n\t\t\tlisteners++;\n\t\t\t// Push-on-subscribe delivers the initial value via DATA — no explicit cb() needed.\n\t\t\tconst sub = node.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) cb(v as T);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsub();\n\t\t\t\tlisteners--;\n\t\t\t\tif (listeners === 0) trigger(node, STOP_LISTENERS);\n\t\t\t};\n\t\t},\n\t\tlisten: (cb: (value: T) => void) => {\n\t\t\tif (listeners === 0) trigger(node, START_LISTENERS);\n\t\t\tlisteners++;\n\t\t\t// Skip the initial push-on-subscribe DATA — listen() fires on changes only.\n\t\t\tlet initial = true;\n\t\t\tconst sub = node.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcb(v as T);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsub();\n\t\t\t\tlisteners--;\n\t\t\t\tif (listeners === 0) trigger(node, STOP_LISTENERS);\n\t\t\t};\n\t\t},\n\t\t_node: node,\n\t};\n\treturn store;\n}\n\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined | null = n.cache;\n\tlet err: any;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t\tif (t === ERROR) err = v;\n\t\t}\n\t});\n\tunsub();\n\tif (err) throw err;\n\treturn val as T;\n}\n\nfunction getVal<T>(n: Node<T>): T {\n\tif (n.status === \"sentinel\") {\n\t\treturn pull(n);\n\t}\n\treturn n.cache as T;\n}\n\n/**\n * Creates a nanostores-compatible atom.\n *\n * @param initial - Initial value.\n * @returns `NanoAtom<T>`\n *\n * @category compat\n */\nexport function atom<T>(initial: T): NanoAtom<T> {\n\tconst n = state<T>(initial, {\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t});\n\n\treturn createStore(n, {\n\t\t// `n.emit` routes through the framed pipeline: `bundle()` auto-\n\t\t// prefixes `[DIRTY]` (diamond-safe wave coordination) and the\n\t\t// node's `equals` (default `Object.is`) folds same-value writes\n\t\t// into `RESOLVED`. Matches nanostores' documented Object.is\n\t\t// dedup semantics without any custom check.\n\t\tset: (value: T) => n.emit(value),\n\t});\n}\n\n/**\n * Creates a nanostores-compatible computed store.\n *\n * @param stores - One or more atoms/computed stores.\n * @param fn - Compute function.\n * @returns `NanoComputed<T>`\n *\n * @category compat\n */\nexport function computed<T, A>(\n\tstoreA: NanoAtom<A> | NanoComputed<A>,\n\tfn: (a: A) => T,\n): NanoComputed<T>;\nexport function computed<T, A, B>(\n\tstores: [NanoAtom<A> | NanoComputed<A>, NanoAtom<B> | NanoComputed<B>],\n\tfn: (a: A, b: B) => T,\n): NanoComputed<T>;\nexport function computed<T, A, B, C>(\n\tstores: [\n\t\tNanoAtom<A> | NanoComputed<A>,\n\t\tNanoAtom<B> | NanoComputed<B>,\n\t\tNanoAtom<C> | NanoComputed<C>,\n\t],\n\tfn: (a: A, b: B, c: C) => T,\n): NanoComputed<T>;\nexport function computed<T>(stores: any, fn: (...args: any[]) => T): NanoComputed<T> {\n\tconst storeArray: Array<NanoAtom<any> | NanoComputed<any>> = Array.isArray(stores)\n\t\t? stores\n\t\t: [stores];\n\n\tconst depNodes = storeArray.map((s) => s._node);\n\tconst n = dynamicNode(\n\t\tdepNodes,\n\t\t(track: TrackFn) => {\n\t\t\tconst vals = storeArray.map((s) => {\n\t\t\t\tconst node = s._node;\n\t\t\t\tif (node.status === \"sentinel\") {\n\t\t\t\t\tpull(node);\n\t\t\t\t}\n\t\t\t\treturn track(node);\n\t\t\t});\n\t\t\treturn fn(...vals);\n\t\t},\n\t\t{\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t\tequals: Object.is as any,\n\t\t},\n\t);\n\n\treturn createStore(n);\n}\n\n/**\n * Creates a nanostores-compatible map.\n *\n * @param initial - Initial object value.\n * @returns `NanoMap<T>`\n *\n * @category compat\n */\nexport function map<T extends Record<string, unknown>>(initial: T): NanoMap<T> {\n\tconst n = state<T>(initial, {\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t\tequals: () => false,\n\t});\n\n\treturn createStore(n, {\n\t\t// `map`'s state node is configured with `equals: () => false`\n\t\t// above, so every `emit` produces DATA (even for same-key same-\n\t\t// value sets). The `emit` path is still required for diamond\n\t\t// coordination (`[DIRTY]` auto-prefix via `bundle()`).\n\t\tset: (value: T) => n.emit(value),\n\t\tsetKey: <K extends keyof T>(key: K, value: T[K]) => {\n\t\t\tconst current = getVal(n);\n\t\t\tn.emit({ ...current, [key]: value });\n\t\t},\n\t});\n}\n\n/**\n * Returns the current value of the store.\n *\n * @category compat\n */\nexport function getValue<T>(store: NanoAtom<T> | NanoComputed<T>): T {\n\treturn store.get();\n}\n\n/**\n * Adds a listener for the store start (first listener connected).\n *\n * @category compat\n */\nexport function onStart(store: NanoAtom<any> | NanoComputed<any>, cb: () => void): void {\n\tconst node = store._node;\n\tlet callbacks = START_LISTENERS.get(node);\n\tif (!callbacks) {\n\t\tcallbacks = new Set();\n\t\tSTART_LISTENERS.set(node, callbacks);\n\t}\n\tcallbacks.add(cb);\n}\n\n/**\n * Adds a listener for the store stop (last listener disconnected).\n *\n * @category compat\n */\nexport function onStop(store: NanoAtom<any> | NanoComputed<any>, cb: () => void): void {\n\tconst node = store._node;\n\tlet callbacks = STOP_LISTENERS.get(node);\n\tif (!callbacks) {\n\t\tcallbacks = new Set();\n\t\tSTOP_LISTENERS.set(node, callbacks);\n\t}\n\tcallbacks.add(cb);\n}\n\n/**\n * Adds a listener for the store mount (first listener connected).\n *\n * @returns A cleanup function called when the last listener is removed.\n * @category compat\n */\nexport function onMount(\n\tstore: NanoAtom<any> | NanoComputed<any>,\n\tcb: () => (() => void) | undefined,\n): void {\n\tonStart(store, () => {\n\t\tconst stop = cb();\n\t\tif (typeof stop === \"function\") onStop(store, stop);\n\t});\n}\n\n/**\n * Batches multiple store updates.\n *\n * @category compat\n */\nexport function action<Args extends any[], Return>(\n\t_store: NanoAtom<any> | NanoComputed<any>,\n\t_name: string,\n\tfn: (...args: Args) => Return,\n): (...args: Args) => Return {\n\treturn (...args: Args) => {\n\t\tlet result: any;\n\t\tbatch(() => {\n\t\t\tresult = fn(...args);\n\t\t});\n\t\treturn result as Return;\n\t};\n}\n","// ---------------------------------------------------------------------------\n// React bindings — useStore / useSubscribe\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into React via useSyncExternalStore.\n// Works with any Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useStore, useSubscribe } from '@graphrefly/graphrefly-ts/compat/react';\n// // Optional peer install (only for this adapter): pnpm add react react-dom\n// const value = useSubscribe(myNode); // T | undefined (read-only)\n// const [count, setCount] = useStore(counter); // [T | undefined, setter]\n// ---------------------------------------------------------------------------\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { DATA, DIRTY, type Messages, RESOLVED } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/**\n * Subscribe to a read-only `Node<T>` as a React value. Re-renders on node value settlement.\n * Subscription lifecycle is tied to React mount/unmount (not node terminal messages).\n *\n * @param node - Any `Node<T>`.\n * @returns `T | undefined` — the current node value, kept in sync via `useSyncExternalStore`.\n */\nexport function useSubscribe<T>(node: Node<T>): T | undefined | null {\n\treturn useSyncExternalStore(\n\t\t(onStoreChange) => {\n\t\t\tlet disposed = false;\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tdisposed = true;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t},\n\t\t() => node.cache,\n\t\t() => node.cache, // Server snapshot\n\t);\n}\n\n/**\n * Bind a writable `Node<T>` as a React `[value, setter]` tuple.\n * Setting the value always pushes `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to React mount/unmount (not node terminal messages).\n *\n * @param node - A `Node<T>` (e.g. state node).\n * @returns `[T | undefined, (value: T) => void]` — current value and setter function.\n */\nexport function useStore<T>(node: Node<T>): [T | undefined | null, (value: T) => void] {\n\tconst value = useSubscribe(node);\n\tconst setter = useCallback(\n\t\t(v: T) => {\n\t\t\tnode.down([[DIRTY], [DATA, v]]);\n\t\t},\n\t\t[node],\n\t);\n\treturn [value, setter];\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records.\n * Re-subscribes all per-key fields whenever `keysNode` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 3`) to avoid DIRTY-phase churn.\n * Guaranteed to clean up strictly with React hook lifecycle, utilizing no global mappings.\n *\n * @param keysNode - Node of current keys (e.g. node IDs)\n * @param factory - Function returning `{ [field]: Node<V> }` for each key.\n * @returns `Record<K, R>` — snapshot of resolved values for all keys.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): Record<K, R> {\n\tconst factoryRef = useRef(factory);\n\tfactoryRef.current = factory;\n\n\tconst store = useMemo(() => {\n\t\tconst computeSnap = () => {\n\t\t\tconst snap = {} as Record<K, R>;\n\t\t\tconst keys = keysNode.cache ?? [];\n\t\t\tfor (const key of keys) {\n\t\t\t\tconst nodes = factoryRef.current(key);\n\t\t\t\tconst values = {} as R;\n\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t\t}\n\t\t\t\tsnap[key] = values;\n\t\t\t}\n\t\t\treturn snap;\n\t\t};\n\n\t\tlet currentSnapshot = computeSnap();\n\n\t\treturn {\n\t\t\tsubscribe: (onStoreChange: () => void) => {\n\t\t\t\tlet disposed = false;\n\t\t\t\tlet entrySubs: Array<() => void> = [];\n\n\t\t\t\tconst cleanupEntries = () => {\n\t\t\t\t\tfor (const unsub of entrySubs) unsub();\n\t\t\t\t\tentrySubs = [];\n\t\t\t\t};\n\n\t\t\t\tconst sync = (nextKeys: K[]) => {\n\t\t\t\t\tcleanupEntries();\n\t\t\t\t\tfor (const key of nextKeys) {\n\t\t\t\t\t\tconst nodes = factoryRef.current(key);\n\t\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\t\t\t\tcurrentSnapshot = computeSnap();\n\t\t\t\t\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tentrySubs.push(unsub);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcurrentSnapshot = computeSnap();\n\t\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t\t};\n\n\t\t\t\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\t\t\t\tconst hasSettled = msgs.some((m) => m[0] === DATA || m[0] === RESOLVED);\n\t\t\t\t\tif (!disposed && hasSettled) sync(keysNode.cache ?? []);\n\t\t\t\t});\n\t\t\t\tsync(keysNode.cache ?? []);\n\n\t\t\t\treturn () => {\n\t\t\t\t\tdisposed = true;\n\t\t\t\t\tkeysUnsub();\n\t\t\t\t\tcleanupEntries();\n\t\t\t\t};\n\t\t\t},\n\t\t\tgetSnapshot: () => currentSnapshot,\n\t\t};\n\t}, [keysNode]);\n\n\treturn useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n","import { batch } from \"../../core/batch.js\";\nimport { COMPLETE, DATA, DIRTY, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { autoTrackNode, state, type TrackFn } from \"../../core/sugar.js\";\n\n/**\n * Options for creating signals.\n *\n * @category compat\n */\nexport interface SignalOptions {\n\t/** Optional identifier for the underlying node. */\n\tname?: string;\n\t/** Custom equality function for change detection. */\n\tequals?: (a: any, b: any) => boolean;\n}\n\n/**\n * Common interface for all reactive signals.\n *\n * @category compat\n */\nexport interface AnySignal<T> {\n\t/** Returns the current value of the signal. */\n\tget(): T;\n\t/** @internal The underlying GraphReFly node. */\n\t_node: Node<T>;\n}\n\n/**\n * Global stack of active tracking contexts.\n * Since computation evaluation is fully synchronous, we push the tracking `get`\n * function before execution and pop it after. This prevents memory leaks without\n * needing WeakRefs, as the stack is always empty when idle.\n */\nconst trackingStack: TrackFn[] = [];\n\n/**\n * Helper to pull a disconnected node, forcing a synchronous resolution\n * cycle so that `get()` returns a fresh value even if the signal is unmounted.\n */\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined | null = n.cache;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t}\n\t});\n\tunsub();\n\treturn val as T;\n}\n\n/**\n * TC39 `Signal.State` — a writable signal backed by a GraphReFly `state` node.\n * Automatically registers itself as a dependency if read inside a `Computed`.\n *\n * @example\n * ```ts\n * const count = new Signal.State(0);\n * count.get(); // 0\n * count.set(1);\n * count.get(); // 1\n * ```\n */\nclass SignalState<T> implements AnySignal<T> {\n\t/** @internal */\n\t_node: Node<T>;\n\tprivate readonly _equals: (a: T, b: T) => boolean;\n\n\tconstructor(initial: T, opts?: SignalOptions) {\n\t\tthis._equals = (opts?.equals ?? Object.is) as (a: T, b: T) => boolean;\n\t\tthis._node = state<T>(initial, {\n\t\t\t...opts,\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t});\n\t}\n\n\tget(): T {\n\t\t// If we are evaluating inside a computed node, track this read!\n\t\tconst tracker = trackingStack[trackingStack.length - 1];\n\t\tif (tracker) {\n\t\t\tif (this._node.status === \"sentinel\") {\n\t\t\t\tpull(this._node);\n\t\t\t}\n\t\t\treturn tracker(this._node) as T;\n\t\t}\n\n\t\tif (this._node.status === \"sentinel\") {\n\t\t\treturn pull(this._node);\n\t\t}\n\t\treturn this._node.cache as T;\n\t}\n\n\tset(value: T): void {\n\t\tif (this._equals(this.get(), value)) return;\n\t\tbatch(() => {\n\t\t\tthis._node.down([[DIRTY], [DATA, value]]);\n\t\t});\n\t}\n}\n\n/**\n * TC39 `Signal.Computed` — a read-only signal backed by `dynamicNode`.\n * Automatically tracks dependencies when `get()` is called on other signals\n * during its computation.\n *\n * @example\n * ```ts\n * const count = new Signal.State(0);\n * const doubled = new Signal.Computed(() => count.get() * 2);\n * ```\n */\nclass SignalComputed<T> implements AnySignal<T> {\n\t/** @internal */\n\t_node: Node<T>;\n\n\tconstructor(computation: () => T, opts?: SignalOptions) {\n\t\tthis._node = autoTrackNode<T>(\n\t\t\t(track) => {\n\t\t\t\ttrackingStack.push(track);\n\t\t\t\ttry {\n\t\t\t\t\treturn computation();\n\t\t\t\t} finally {\n\t\t\t\t\ttrackingStack.pop();\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\t...opts,\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tresubscribable: true,\n\t\t\t\tresetOnTeardown: true,\n\t\t\t},\n\t\t);\n\t}\n\n\tget(): T {\n\t\t// Computed nodes can themselves be dependencies of other Computed nodes.\n\t\tconst tracker = trackingStack[trackingStack.length - 1];\n\t\tif (tracker) {\n\t\t\tif (this._node.status === \"sentinel\") {\n\t\t\t\tpull(this._node);\n\t\t\t}\n\t\t\treturn tracker(this._node) as T;\n\t\t}\n\n\t\tif (this._node.status === \"sentinel\") {\n\t\t\treturn pull(this._node);\n\t\t}\n\t\treturn this._node.cache as T;\n\t}\n}\n\n/**\n * TC39 Signals-compatible namespace. Wraps GraphReFly primitives.\n * Provides auto-tracking conforming to the TS39 signals proposal.\n *\n * @category compat\n */\nexport const Signal = {\n\tState: SignalState,\n\tComputed: SignalComputed,\n\n\t/**\n\t * Subscribes to changes on a signal.\n\t * Returns an unsubscribe callback.\n\t *\n\t * @example\n\t * ```ts\n\t * const count = new Signal.State(0);\n\t * const unsub = Signal.sub(count, v => console.log(v));\n\t * ```\n\t */\n\tsub: <T>(\n\t\tsignal: AnySignal<T>,\n\t\tcallback:\n\t\t\t| ((value: T) => void)\n\t\t\t| {\n\t\t\t\t\tdata?: (value: T) => void;\n\t\t\t\t\terror?: (err: unknown) => void;\n\t\t\t\t\tcomplete?: () => void;\n\t\t\t },\n\t): (() => void) => {\n\t\tconst handlers =\n\t\t\ttypeof callback === \"function\"\n\t\t\t\t? { data: callback as (value: T) => void, error: undefined, complete: undefined }\n\t\t\t\t: callback;\n\t\t// Skip the initial push-on-subscribe DATA — Signal.sub fires on changes only.\n\t\tlet initial = true;\n\t\treturn signal._node.subscribe((msgs) => {\n\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tif (initial) {\n\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\thandlers.data?.(v as T);\n\t\t\t\t}\n\t\t\t\tif (t === ERROR) handlers.error?.(v);\n\t\t\t\tif (t === COMPLETE) handlers.complete?.();\n\t\t\t}\n\t\t});\n\t},\n} as const;\n\nexport type { SignalComputed, SignalState };\n","// ---------------------------------------------------------------------------\n// Solid bindings — useSubscribe / useStore\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Solid reactivity via createSignal.\n// Works with any Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useSubscribe, useStore } from '@graphrefly/graphrefly-ts/compat/solid';\n// // Optional peer install (only for this adapter): pnpm add solid-js\n// const status = useSubscribe(wsStatusNode); // Accessor<string | undefined>\n// const [count, setCount] = useStore(countNode); // [Accessor<number | undefined>, Setter]\n// ---------------------------------------------------------------------------\n\nimport { createSignal, getOwner, onCleanup } from \"solid-js\";\nimport { DATA, DIRTY, type Messages, RESOLVED } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/** Solid accessor function — returns current value when called. */\nexport type Accessor<T> = () => T;\n\n/**\n * Subscribe to a `Node<T>` as a Solid signal. Auto-cleans up with the owning scope.\n * Subscription lifecycle is tied to Solid scope cleanup (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): Accessor<T | undefined | null> {\n\tconst [value, setValue] = createSignal(node.cache, { equals: false });\n\n\tconst unsub = node.subscribe(() => {\n\t\tsetValue(() => node.cache);\n\t});\n\n\tif (getOwner()) {\n\t\tonCleanup(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribe called outside a Solid reactive owner — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn value;\n}\n\n/**\n * Bind a writable `Node<T>` as a Solid resource tuple `[accessor, setter]`.\n * Setter always forwards `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Solid scope cleanup (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): [Accessor<T | undefined | null>, (v: T) => void] {\n\tconst value = useSubscribe(node);\n\tconst setter = (v: T) => {\n\t\tnode.down([[DIRTY], [DATA, v]]);\n\t};\n\treturn [value, setter];\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records as a Solid accessor.\n * Re-subscribes all per-key fields whenever `keys` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 3`) to avoid DIRTY-phase churn.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): Accessor<Record<K, R>> {\n\tconst [value, setValue] = createSignal({} as Record<K, R>, { equals: false });\n\tlet entrySubs: Array<() => void> = [];\n\n\tconst cleanupEntries = () => {\n\t\tfor (const unsub of entrySubs) unsub();\n\t\tentrySubs = [];\n\t};\n\n\tconst buildSnapshot = (): Record<K, R> => {\n\t\tconst snap = {} as Record<K, R>;\n\t\tfor (const key of keysNode.cache ?? []) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst values = {} as R;\n\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t}\n\t\t\tsnap[key] = values;\n\t\t}\n\t\treturn snap;\n\t};\n\n\tconst sync = (nextKeys: K[]) => {\n\t\tcleanupEntries();\n\t\tfor (const key of nextKeys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\tsetValue(() => buildSnapshot());\n\t\t\t\t});\n\t\t\t\tentrySubs.push(unsub);\n\t\t\t}\n\t\t}\n\t\tsetValue(() => buildSnapshot());\n\t};\n\n\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\tif (msgs.some((m) => m[0] === DATA || m[0] === RESOLVED)) {\n\t\t\tsync(keysNode.cache ?? []);\n\t\t}\n\t});\n\tsync(keysNode.cache ?? []);\n\n\tif (getOwner()) {\n\t\tonCleanup(() => {\n\t\t\tkeysUnsub();\n\t\t\tcleanupEntries();\n\t\t});\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn value;\n}\n","// ---------------------------------------------------------------------------\n// Svelte bindings — useSubscribe / useStore\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Svelte's store contract. Works with any\n// Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useSubscribe, useStore } from '@graphrefly/graphrefly-ts/compat/svelte';\n// // Optional peer install (only for this adapter): pnpm add svelte\n// const status = useSubscribe(wsStatusNode); // Svelte readable store\n// const count = useStore(countNode); // Svelte writable store\n// // In template: $status, $count\n// // $count = 42\n// ---------------------------------------------------------------------------\n\nimport { DATA, DIRTY, type Messages, RESOLVED } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/** Svelte store contract — implements the minimal `subscribe` method. */\nexport interface SvelteReadable<T> {\n\tsubscribe(run: (value: T) => void): () => void;\n}\n\n/** Svelte writable store contract. */\nexport interface SvelteWritable<T> extends SvelteReadable<T> {\n\tset(value: T): void;\n\tupdate(updater: (value: T) => T): void;\n}\n\n/**\n * Subscribe to a `Node<T>` as a Svelte readable store (implements Svelte store contract).\n * Subscription lifecycle is tied to Svelte store unsubscription (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): SvelteReadable<T | undefined | null> {\n\treturn {\n\t\tsubscribe(run: (value: T | undefined | null) => void): () => void {\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\trun(node.cache);\n\t\t\t});\n\t\t\trun(node.cache);\n\t\t\treturn unsub;\n\t\t},\n\t};\n}\n\n/**\n * Bind a writable `Node<T>` as a Svelte writable store.\n * Reads and writes adapt seamlessly.\n * Setter/update always forward `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Svelte store unsubscription (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): SvelteWritable<T | undefined | null> {\n\treturn {\n\t\tsubscribe(run: (value: T | undefined | null) => void): () => void {\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\trun(node.cache);\n\t\t\t});\n\t\t\trun(node.cache);\n\t\t\treturn unsub;\n\t\t},\n\t\tset(value: T | undefined | null) {\n\t\t\tnode.down([[DIRTY], [DATA, value]]);\n\t\t},\n\t\tupdate(updater: (value: T | undefined | null) => T | undefined | null) {\n\t\t\tconst next = updater(node.cache);\n\t\t\tnode.down([[DIRTY], [DATA, next]]);\n\t\t},\n\t};\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic keyed record of nodes as a Svelte readable store.\n * Re-subscribes all per-key fields whenever `keysNode` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 3`) to avoid DIRTY-phase churn.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): SvelteReadable<Record<K, R>> {\n\treturn {\n\t\tsubscribe(run: (value: Record<K, R>) => void): () => void {\n\t\t\tlet entrySubs: Array<() => void> = [];\n\n\t\t\tconst cleanupEntries = () => {\n\t\t\t\tfor (const unsub of entrySubs) unsub();\n\t\t\t\tentrySubs = [];\n\t\t\t};\n\n\t\t\tconst buildSnapshot = (): Record<K, R> => {\n\t\t\t\tconst snap = {} as Record<K, R>;\n\t\t\t\tfor (const key of keysNode.cache ?? []) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tconst values = {} as R;\n\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t\t\t}\n\t\t\t\t\tsnap[key] = values;\n\t\t\t\t}\n\t\t\t\treturn snap;\n\t\t\t};\n\n\t\t\tconst sync = (nextKeys: K[]) => {\n\t\t\t\tcleanupEntries();\n\t\t\t\tfor (const key of nextKeys) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\t\t\trun(buildSnapshot());\n\t\t\t\t\t\t});\n\t\t\t\t\t\tentrySubs.push(unsub);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trun(buildSnapshot());\n\t\t\t};\n\n\t\t\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\t\t\tif (msgs.some((m) => m[0] === DATA || m[0] === RESOLVED)) {\n\t\t\t\t\tsync(keysNode.cache ?? []);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsync(keysNode.cache ?? []);\n\n\t\t\treturn () => {\n\t\t\t\tkeysUnsub();\n\t\t\t\tcleanupEntries();\n\t\t\t};\n\t\t},\n\t};\n}\n","// ---------------------------------------------------------------------------\n// Vue bindings — useStore / useSubscribe\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Vue reactivity. Works with any\n// Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useStore, useSubscribe } from '@graphrefly/graphrefly-ts/compat/vue';\n// // Optional peer install (only for this adapter): pnpm add vue\n// const count = useStore(counterNode); // Ref<number | undefined> (read + write)\n// const status = useSubscribe(wsStatusNode); // Readonly<Ref<string | undefined>>\n// ---------------------------------------------------------------------------\n\nimport {\n\tcomputed,\n\tgetCurrentScope,\n\tisRef,\n\tonScopeDispose,\n\ttype Ref,\n\treadonly,\n\tshallowRef,\n\ttype WatchSource,\n\twatch,\n} from \"vue\";\nimport { DATA, DIRTY } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/**\n * Subscribe to a read-only `Node<T>` as a Vue `Ref<T>`. Auto-unsubscribes on scope disposal.\n * Subscription lifecycle is tied to Vue scope disposal (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): Readonly<Ref<T | undefined | null>> {\n\tconst ref = shallowRef(node.cache) as Ref<T | undefined | null>;\n\n\tconst unsub = node.subscribe(() => {\n\t\tref.value = node.cache;\n\t});\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribe called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn readonly(ref) as Readonly<Ref<T | undefined | null>>;\n}\n\n/**\n * Bind a writable `Node<T>` as a Vue `Ref<T>`. Reads and writes are bidirectional.\n * Value sets always dispatch `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Vue scope disposal (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): Ref<T | undefined | null> {\n\tconst inner = shallowRef(node.cache) as Ref<T | undefined | null>;\n\n\tconst unsub = node.subscribe(() => {\n\t\tinner.value = node.cache;\n\t});\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useStore called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn computed({\n\t\tget: () => inner.value,\n\t\tset: (v: T | undefined | null) => {\n\t\t\tnode.down([[DIRTY], [DATA, v]]);\n\t\t},\n\t});\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord` factory. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records. When keys change,\n * old subscriptions are torn down and new ones created automatically.\n * Must be called during Vue `setup()`.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeys: WatchSource<K[] | undefined>,\n\tfactory: NodeFactory<K, R>,\n): Readonly<Ref<Record<K, R>>> {\n\tconst result = shallowRef<Record<K, R>>({} as Record<K, R>);\n\n\t// Track active subscriptions per key (strictly enclosed memory mapping)\n\tconst activeSubs = new Map<K, { subs: Array<() => void>; values: R }>();\n\tlet disposed = false;\n\n\tlet batchPending = false;\n\tfunction scheduleBatch() {\n\t\tif (batchPending) return;\n\t\tbatchPending = true;\n\t\tqueueMicrotask(() => {\n\t\t\tif (disposed) return;\n\t\t\tbatchPending = false;\n\t\t\tconst snap = {} as Record<K, R>;\n\t\t\tfor (const [key, entry] of activeSubs) {\n\t\t\t\tsnap[key] = { ...entry.values };\n\t\t\t}\n\t\t\tresult.value = snap;\n\t\t});\n\t}\n\n\tfunction sync(newKeys: K[]) {\n\t\tfor (const entry of activeSubs.values()) {\n\t\t\tfor (const unsub of entry.subs) unsub();\n\t\t}\n\t\tactiveSubs.clear();\n\n\t\tfor (const key of newKeys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst fields = Object.keys(nodes) as (keyof R)[];\n\t\t\tconst values = {} as R;\n\t\t\tconst subs: Array<() => void> = [];\n\n\t\t\tfor (const field of fields) {\n\t\t\t\tconst node = nodes[field];\n\t\t\t\tvalues[field] = node.cache as R[keyof R];\n\t\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\t\tvalues[field] = node.cache as R[keyof R];\n\t\t\t\t\tscheduleBatch();\n\t\t\t\t});\n\t\t\t\tsubs.push(unsub);\n\t\t\t}\n\n\t\t\tactiveSubs.set(key, { subs, values });\n\t\t}\n\n\t\tconst snap = {} as Record<K, R>;\n\t\tfor (const [key, entry] of activeSubs) {\n\t\t\tsnap[key] = { ...entry.values };\n\t\t}\n\t\tresult.value = snap;\n\t}\n\n\tconst readKeys = (): K[] => {\n\t\tconst current = typeof keys === \"function\" ? keys() : isRef(keys) ? keys.value : keys;\n\t\treturn [...(current ?? [])];\n\t};\n\n\twatch(readKeys, (newKeys) => sync(newKeys ?? []), { immediate: true });\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => {\n\t\t\tdisposed = true;\n\t\t\tfor (const entry of activeSubs.values()) {\n\t\t\t\tfor (const unsub of entry.subs) unsub();\n\t\t\t}\n\t\t\tactiveSubs.clear();\n\t\t});\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribeRecord called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn readonly(result) as Readonly<Ref<Record<K, R>>>;\n}\n","import { DATA } from \"../../core/messages.js\";\nimport { state as stateNode } from \"../../core/sugar.js\";\nimport { Graph } from \"../../graph/graph.js\";\n\n// Zustand fires listeners on every setState, regardless of reference\n// equality. Configure the state node with a permissive equals so every\n// emit produces DATA (not RESOLVED). Diamond coordination still works\n// because `n.emit` routes through the framed pipeline which auto-\n// prefixes `[DIRTY]`.\nconst alwaysDiffer = () => false;\n\n/** Zustand-compatible Store API. */\nexport interface StoreApi<T> {\n\tgetState: () => T;\n\tsetState: (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean) => void;\n\tgetInitialState: () => T;\n\tsubscribe: (listener: (state: T, prevState: T) => void) => () => void;\n\tdestroy: () => void;\n}\n\n/** Function type for initializing the store. */\nexport type StateCreator<T> = (\n\tset: StoreApi<T>[\"setState\"],\n\tget: StoreApi<T>[\"getState\"],\n\tapi: StoreApi<T>,\n) => T;\n\n/**\n * Creates a Zustand-compatible store backed by a GraphReFly state node.\n * returns an object that is both a Graph and a StoreApi.\n *\n * @example\n * ```ts\n * const store = create((set) => ({\n * count: 0,\n * inc: () => set((s) => ({ count: s.count + 1 }))\n * }));\n * store.getState().inc();\n * ```\n *\n * @category compat\n */\nexport function create<T extends object>(initializer: StateCreator<T>): Graph & StoreApi<T> {\n\tconst g = new Graph(\"zustand\");\n\tconst s = stateNode<T>(undefined as unknown as T, {\n\t\tname: \"state\",\n\t\tequals: alwaysDiffer,\n\t});\n\tg.add(\"state\", s);\n\n\tconst getState = () => s.cache as T;\n\tconst setState = (partial: any, replace?: boolean): void => {\n\t\tconst prev = getState();\n\t\tconst next = typeof partial === \"function\" ? partial(prev) : partial;\n\t\tconst nextState = replace ? next : { ...prev, ...next };\n\t\t// `n.emit` goes through `_actionEmit` → `bundle()`, which auto-\n\t\t// prefixes `[DIRTY]` so diamond legs coordinate under downstream\n\t\t// composition. The `alwaysDiffer` equals keeps zustand's \"fire\n\t\t// on every setState\" semantics — the framing is what matters\n\t\t// here, not the equality folding.\n\t\ts.emit(nextState);\n\t};\n\n\tconst api: StoreApi<T> = {\n\t\tgetState,\n\t\tsetState,\n\t\tgetInitialState: () => initialValue,\n\t\tsubscribe: (listener) => {\n\t\t\tlet prev = getState();\n\t\t\t// Skip the initial push-on-subscribe DATA — zustand subscribe fires on changes only.\n\t\t\tlet initial = true;\n\t\t\treturn s.subscribe((msgs) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlistener(v as T, prev);\n\t\t\t\t\t\tprev = v as T;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tdestroy: g.destroy.bind(g),\n\t};\n\n\tconst initialValue = initializer(setState, getState, api);\n\ts.emit(initialValue);\n\n\treturn Object.assign(g, api);\n}\n","/**\n * Patterns layer: domain/solution helpers (Phase 4+).\n */\n\nexport * as ai from \"./ai.js\";\nexport * as cqrs from \"./cqrs.js\";\nexport * as demoShell from \"./demo-shell.js\";\nexport * as domainTemplates from \"./domain-templates.js\";\nexport * as graphspec from \"./graphspec.js\";\nexport * as harness from \"./harness/index.js\";\nexport * as memory from \"./memory.js\";\nexport * as messaging from \"./messaging.js\";\nexport * as orchestration from \"./orchestration.js\";\nexport * as layout from \"./reactive-layout/index.js\";\nexport * as reduction from \"./reduction.js\";\n","/**\n * AI surface patterns (roadmap §4.4).\n *\n * Domain-layer factories for LLM-backed agents, chat, tool registries, and\n * agentic memory. Composed from core + extra + Phase 3–4.3 primitives.\n */\n\nimport type { Actor } from \"../core/actor.js\";\nimport { batch } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, ERROR } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, producer, state } from \"../core/sugar.js\";\nimport {\n\ttype DistillBundle,\n\ttype DistillOptions,\n\tdistill,\n\ttype Extraction,\n} from \"../extra/composite.js\";\nimport { switchMap } from \"../extra/operators.js\";\nimport { type ReactiveLogBundle, reactiveLog } from \"../extra/reactive-log.js\";\nimport { fromAny, fromTimer, type NodeInput } from \"../extra/sources.js\";\nimport type { StorageHandle, StorageTier } from \"../extra/storage.js\";\nimport { ResettableTimer } from \"../extra/timer.js\";\nimport {\n\tGraph,\n\ttype GraphAttachStorageOptions,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n} from \"../graph/graph.js\";\nimport {\n\tdecay,\n\ttype KnowledgeGraphGraph,\n\tknowledgeGraph,\n\ttype LightCollectionBundle,\n\tlightCollection,\n\ttype VectorIndexBundle,\n\ttype VectorSearchResult,\n\tvectorIndex,\n} from \"./memory.js\";\nimport { type TopicGraph, topic } from \"./messaging.js\";\nimport { type GateController, type GateOptions, gate } from \"./orchestration.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A single chat message in a conversation. */\nexport type ChatMessage = {\n\treadonly role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n\treadonly content: string;\n\treadonly name?: string;\n\treadonly toolCallId?: string;\n\treadonly toolCalls?: readonly ToolCall[];\n\treadonly metadata?: Record<string, unknown>;\n};\n\n/** A tool invocation request from an LLM. */\nexport type ToolCall = {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly arguments: Record<string, unknown>;\n};\n\n/** The response from an LLM invocation. */\nexport type LLMResponse = {\n\treadonly content: string;\n\treadonly toolCalls?: readonly ToolCall[];\n\treadonly usage?: { readonly inputTokens: number; readonly outputTokens: number };\n\treadonly finishReason?: string;\n\treadonly metadata?: Record<string, unknown>;\n};\n\n/** Provider-agnostic LLM client adapter protocol. */\nexport type LLMAdapter = {\n\tinvoke(messages: readonly ChatMessage[], opts?: LLMInvokeOptions): NodeInput<LLMResponse>;\n\tstream(messages: readonly ChatMessage[], opts?: LLMInvokeOptions): AsyncIterable<string>;\n};\n\nexport type LLMInvokeOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n\tsignal?: AbortSignal;\n};\n\n/** A tool definition for LLM consumption. */\nexport type ToolDefinition = {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly parameters: Record<string, unknown>; // JSON Schema\n\treadonly handler: (args: Record<string, unknown>) => NodeInput<unknown>;\n\t/**\n\t * V0 version of the backing node at `knobsAsTools()` call time (§6.0b).\n\t * Snapshot — re-call `knobsAsTools()` to refresh.\n\t */\n\treadonly version?: { id: string; version: number };\n};\n\nexport type AgentLoopStatus = \"idle\" | \"thinking\" | \"acting\" | \"done\" | \"error\";\n\n/**\n * A single chunk from any streaming source (LLM tokens, WebSocket, SSE, file tail).\n * Generic enough for any streaming source, not just LLM.\n */\nexport type StreamChunk = {\n\t/** Identifier for the stream source (adapter name, URL, etc.). */\n\treadonly source: string;\n\t/** This chunk's content. */\n\treadonly token: string;\n\t/** Full accumulated text so far. */\n\treadonly accumulated: string;\n\t/** 0-based chunk counter. */\n\treadonly index: number;\n};\n\n// ---------------------------------------------------------------------------\n// Meta helpers\n// ---------------------------------------------------------------------------\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction aiMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"ai\", kind, extra);\n}\n\nfunction isPromiseLike(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isNodeLike(x: unknown): x is Node<unknown> {\n\treturn (\n\t\ttypeof x === \"object\" &&\n\t\tx !== null &&\n\t\t\"subscribe\" in x &&\n\t\ttypeof (x as Node<unknown>).subscribe === \"function\" &&\n\t\t\"cache\" in x\n\t);\n}\n\nfunction isAsyncIterableLike(x: unknown): x is AsyncIterable<unknown> {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === \"object\" &&\n\t\tSymbol.asyncIterator in x &&\n\t\ttypeof (x as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** First settled `DATA` from a `Node` (do not pass plain strings — `fromAny` would iterate chars). */\nfunction firstDataFromNode(\n\tresolved: Node<unknown>,\n\topts?: { timeoutMs?: number },\n): Promise<unknown> {\n\t// Only trust get() when node is in settled state\n\tif ((resolved as { status?: string }).status === \"settled\") {\n\t\tconst immediate = resolved.cache;\n\t\tif (immediate !== undefined) {\n\t\t\treturn Promise.resolve(immediate);\n\t\t}\n\t}\n\tconst timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = new ResettableTimer();\n\t\tconst unsub = resolved.subscribe((messages) => {\n\t\t\tfor (const msg of messages) {\n\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\ttimer.cancel();\n\t\t\t\t\tunsub();\n\t\t\t\t\tresolve(msg[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === ERROR) {\n\t\t\t\t\ttimer.cancel();\n\t\t\t\t\tunsub();\n\t\t\t\t\treject(msg[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\ttimer.cancel();\n\t\t\t\t\tunsub();\n\t\t\t\t\treject(new Error(\"firstDataFromNode: completed without producing a value\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\ttimer.start(timeoutMs, () => {\n\t\t\tunsub();\n\t\t\treject(new Error(`firstDataFromNode: timed out after ${timeoutMs}ms`));\n\t\t});\n\t});\n}\n\n/** Await Promise-likes, then resolve `Node` / async-iterable inputs via `fromAny` + first `DATA`. */\nasync function resolveToolHandlerResult(value: unknown): Promise<unknown> {\n\tif (isPromiseLike(value)) {\n\t\treturn resolveToolHandlerResult(await value);\n\t}\n\tif (isNodeLike(value)) {\n\t\treturn firstDataFromNode(value);\n\t}\n\tif (isAsyncIterableLike(value)) {\n\t\treturn firstDataFromNode(fromAny(value as NodeInput<unknown>));\n\t}\n\treturn value;\n}\n\n// ---------------------------------------------------------------------------\n// fromLLM\n// ---------------------------------------------------------------------------\n\nexport type FromLLMOptions = {\n\tname?: string;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n};\n\n/**\n * Reactive LLM invocation adapter. Returns a derived node that re-invokes\n * the LLM whenever the messages dep changes.\n *\n * Uses `switchMap` internally — new invocations cancel stale in-flight ones.\n */\nexport function fromLLM(\n\tadapter: LLMAdapter,\n\tmessages: NodeInput<readonly ChatMessage[]>,\n\topts?: FromLLMOptions,\n): Node<LLMResponse | null> {\n\tconst msgsNode = fromAny(messages);\n\tconst result = switchMap(msgsNode, (msgs) => {\n\t\tif (!msgs || (msgs as readonly ChatMessage[]).length === 0) {\n\t\t\treturn state<LLMResponse | null>(null) as NodeInput<LLMResponse | null>;\n\t\t}\n\t\tconst tools = opts?.tools;\n\t\treturn adapter.invoke(msgs as readonly ChatMessage[], {\n\t\t\tmodel: opts?.model,\n\t\t\ttemperature: opts?.temperature,\n\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\ttools,\n\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t}) as NodeInput<LLMResponse | null>;\n\t});\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// streamingPromptNode\n// ---------------------------------------------------------------------------\n\nexport type StreamingPromptNodeOptions = {\n\tname?: string;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Output format — `\"json\"` attempts JSON.parse on the final accumulated text. Default: `\"text\"`. */\n\tformat?: \"text\" | \"json\";\n\tsystemPrompt?: string;\n};\n\n/**\n * Bundle returned by {@link streamingPromptNode}.\n */\nexport type StreamingPromptNodeHandle<T> = {\n\t/** Final parsed result (emits once per invocation, after stream completes). */\n\toutput: Node<T | null>;\n\t/** Live stream topic — subscribe to `stream.latest` or `stream.events` for chunks. */\n\tstream: TopicGraph<StreamChunk>;\n\t/** Tear down the keepalive subscription and release resources. */\n\tdispose: () => void;\n};\n\n/**\n * Streaming LLM transform: wraps a prompt template + adapter into a reactive\n * streaming pipeline. Re-invokes the LLM whenever any dep changes; the\n * previous in-flight stream is canceled automatically via `switchMap`.\n *\n * Each token chunk is published to a {@link TopicGraph} as a {@link StreamChunk}.\n * Extractors can mount on the topic independently (see {@link streamExtractor}).\n * Zero overhead if nobody subscribes to the stream topic.\n *\n * The `output` node emits the final parsed result (like {@link promptNode}).\n * The async boundary is handled by `fromAny` (spec §5.10 compliant).\n */\nexport function streamingPromptNode<T = string>(\n\tadapter: LLMAdapter,\n\tdeps: readonly Node<unknown>[],\n\tprompt: string | ((...depValues: unknown[]) => string),\n\topts?: StreamingPromptNodeOptions,\n): StreamingPromptNodeHandle<T> {\n\tconst sourceName = opts?.name ?? \"llm\";\n\tconst format = opts?.format ?? \"text\";\n\tconst streamTopic = topic<StreamChunk>(`${sourceName}/stream`);\n\n\tconst messagesNode = derived<readonly ChatMessage[]>(deps as Node<unknown>[], (values) => {\n\t\tif (values.some((v) => v == null)) return [];\n\t\tconst text = typeof prompt === \"string\" ? prompt : prompt(...values);\n\t\tif (!text) return [];\n\t\tconst msgs: ChatMessage[] = [];\n\t\tif (opts?.systemPrompt) msgs.push({ role: \"system\", content: opts.systemPrompt });\n\t\tmsgs.push({ role: \"user\", content: text });\n\t\treturn msgs;\n\t});\n\n\tconst output = switchMap(messagesNode, (msgs) => {\n\t\tconst chatMsgs = msgs as readonly ChatMessage[];\n\t\tif (!chatMsgs || chatMsgs.length === 0) {\n\t\t\treturn state<T | null>(null) as NodeInput<T | null>;\n\t\t}\n\n\t\tconst ac = new AbortController();\n\n\t\tasync function* pumpAndCollect(): AsyncGenerator<T | null> {\n\t\t\tlet accumulated = \"\";\n\t\t\tlet index = 0;\n\t\t\ttry {\n\t\t\t\tfor await (const token of adapter.stream(chatMsgs, {\n\t\t\t\t\tmodel: opts?.model,\n\t\t\t\t\ttemperature: opts?.temperature,\n\t\t\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t\t\t\tsignal: ac.signal,\n\t\t\t\t})) {\n\t\t\t\t\taccumulated += token;\n\t\t\t\t\tstreamTopic.publish({\n\t\t\t\t\t\tsource: sourceName,\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\taccumulated,\n\t\t\t\t\t\tindex: index++,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tlet result: T | null;\n\t\t\t\tif (format === \"json\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = JSON.parse(stripFences(accumulated)) as T;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tresult = accumulated as unknown as T;\n\t\t\t\t}\n\t\t\t\tyield result;\n\t\t\t} finally {\n\t\t\t\tac.abort();\n\t\t\t}\n\t\t}\n\n\t\treturn fromAny(pumpAndCollect());\n\t});\n\n\tconst unsub = keepalive(output);\n\n\treturn {\n\t\toutput,\n\t\tstream: streamTopic,\n\t\tdispose: () => {\n\t\t\tunsub();\n\t\t\tstreamTopic.destroy();\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// streamExtractor\n// ---------------------------------------------------------------------------\n\n/**\n * Mounts an extractor function on a streaming topic. Returns a derived node\n * that emits extracted values as chunks arrive.\n *\n * `extractFn` receives the accumulated text from the latest chunk and returns\n * the extracted value, or `null` if nothing detected yet. This is the building\n * block for keyword flags, tool call detection, cost metering, etc.\n *\n * @param streamTopic - The stream topic to extract from.\n * @param extractFn - `(accumulated: string) => T | null`.\n * @param opts - Optional name.\n * @returns Derived node emitting extracted values.\n */\nexport function streamExtractor<T>(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\textractFn: (accumulated: string) => T | null,\n\topts?: {\n\t\tname?: string;\n\t\t/**\n\t\t * Optional structural equals for the extractor output. When two\n\t\t * consecutive chunks produce structurally-equal outputs, the framework\n\t\t * emits `RESOLVED` instead of `DATA`, saving downstream work. Default:\n\t\t * reference equality (`Object.is`). The library cannot know your\n\t\t * output shape — supply this when your `extractFn` returns structured\n\t\t * objects or arrays.\n\t\t */\n\t\tequals?: (a: T | null, b: T | null) => boolean;\n\t},\n): Node<T | null> {\n\treturn derived<T | null>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk]) => {\n\t\t\tif (chunk == null) return null;\n\t\t\treturn extractFn((chunk as StreamChunk).accumulated);\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ?? \"extractor\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: null,\n\t\t\tmeta: aiMeta(\"stream_extractor\"),\n\t\t\t...(opts?.equals ? { equals: opts.equals } : {}),\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// keywordFlagExtractor\n// ---------------------------------------------------------------------------\n\n/** A keyword match detected in the stream. */\nexport type KeywordFlag = {\n\treadonly label: string;\n\treadonly pattern: RegExp;\n\treadonly match: string;\n\treadonly position: number;\n};\n\nexport type KeywordFlagExtractorOptions = {\n\tpatterns: readonly { pattern: RegExp; label: string }[];\n\tname?: string;\n\t/**\n\t * Maximum length of any pattern's literal text. Used as an overlap window\n\t * when cursoring through the accumulated stream so matches that span\n\t * chunk boundaries aren't missed. Default: 128.\n\t */\n\tmaxPatternLength?: number;\n};\n\nconst keywordFlagsEqual = (\n\ta: readonly KeywordFlag[] | null,\n\tb: readonly KeywordFlag[] | null,\n): boolean => {\n\tif (a === b) return true;\n\tif (a == null || b == null) return a === b;\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tconst x = a[i];\n\t\tconst y = b[i];\n\t\tif (\n\t\t\tx.label !== y.label ||\n\t\t\tx.pattern !== y.pattern ||\n\t\t\tx.match !== y.match ||\n\t\t\tx.position !== y.position\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n};\n\n/**\n * Mounts a keyword-flag extractor on a streaming topic. Scans accumulated text\n * for all configured patterns and emits an array of matches.\n *\n * Use cases: design invariant violations (`setTimeout`, `EventEmitter`), PII\n * detection (SSN, email, phone), toxicity keywords, off-track reasoning.\n *\n * **Streaming optimization.** Maintains a cursor across chunks in `ctx.store`\n * so each chunk scans only the delta region `accumulated.slice(scannedTo -\n * maxPatternLength)` — not the full string. Default structural equals\n * suppresses DATA emission when no new flags were found this chunk.\n */\nexport function keywordFlagExtractor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\topts: KeywordFlagExtractorOptions,\n): Node<readonly KeywordFlag[]> {\n\tconst maxPatternLength = opts.maxPatternLength ?? 128;\n\treturn derived<readonly KeywordFlag[]>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk], ctx) => {\n\t\t\tif (chunk == null) return [];\n\t\t\tconst accumulated = (chunk as StreamChunk).accumulated;\n\n\t\t\tif (!(\"flags\" in ctx.store)) {\n\t\t\t\tctx.store.flags = [] as KeywordFlag[];\n\t\t\t\tctx.store.scannedTo = 0;\n\t\t\t}\n\t\t\tconst flags = ctx.store.flags as KeywordFlag[];\n\t\t\tconst scannedTo = ctx.store.scannedTo as number;\n\n\t\t\t// Scan the delta plus an overlap window so matches that span\n\t\t\t// chunk boundaries (e.g. \"EventE\" + \"mitter\") are still found.\n\t\t\tconst startOffset = Math.max(0, scannedTo - maxPatternLength);\n\t\t\tconst region = accumulated.slice(startOffset);\n\t\t\tlet added = false;\n\t\t\tfor (const { pattern, label } of opts.patterns) {\n\t\t\t\tconst re = new RegExp(pattern.source, `${pattern.flags.replace(\"g\", \"\")}g`);\n\t\t\t\tfor (const m of region.matchAll(re)) {\n\t\t\t\t\tconst pos = startOffset + m.index!;\n\t\t\t\t\t// Skip matches that end inside the already-scanned prefix.\n\t\t\t\t\tif (pos + m[0].length <= scannedTo) continue;\n\t\t\t\t\tflags.push({ label, pattern, match: m[0], position: pos });\n\t\t\t\t\tadded = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.store.scannedTo = accumulated.length;\n\n\t\t\t// Always return a fresh copy so downstream never holds a live\n\t\t\t// reference to ctx.store.flags. Structural equals suppresses the\n\t\t\t// emission when no new flag was added this chunk.\n\t\t\treturn added ? [...flags] : flags.slice();\n\t\t},\n\t\t{\n\t\t\tname: opts.name ?? \"keyword-flag-extractor\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: [],\n\t\t\tmeta: aiMeta(\"keyword_flag_extractor\"),\n\t\t\tequals: keywordFlagsEqual,\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// toolCallExtractor\n// ---------------------------------------------------------------------------\n\n/** A tool call detected in the stream. */\nexport type ExtractedToolCall = {\n\treadonly name: string;\n\treadonly arguments: Record<string, unknown>;\n\treadonly raw: string;\n\treadonly startIndex: number;\n};\n\nconst toolCallsEqual = (\n\ta: readonly ExtractedToolCall[] | null,\n\tb: readonly ExtractedToolCall[] | null,\n): boolean => {\n\tif (a === b) return true;\n\tif (a == null || b == null) return a === b;\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tconst x = a[i];\n\t\tconst y = b[i];\n\t\tif (x.startIndex !== y.startIndex || x.name !== y.name || x.raw !== y.raw) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n};\n\n/**\n * Mounts a tool-call extractor on a streaming topic. Scans accumulated text\n * for complete JSON objects containing `\"name\"` and `\"arguments\"` keys (the\n * standard tool_call shape). Partial JSON is ignored until the closing brace.\n *\n * Feeds into the tool interception chain for reactive tool gating mid-stream.\n *\n * **Streaming optimization.** Maintains a cursor (`scanFrom`) in `ctx.store`\n * so each chunk resumes brace-scanning from the position after the last\n * complete parse (or the last incomplete open brace). Already-parsed objects\n * are not re-parsed. Default structural equals suppresses DATA emission when\n * no new tool call completed this chunk.\n */\nexport function toolCallExtractor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\topts?: { name?: string },\n): Node<readonly ExtractedToolCall[]> {\n\treturn derived<readonly ExtractedToolCall[]>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk], ctx) => {\n\t\t\tif (chunk == null) return [];\n\t\t\tconst accumulated = (chunk as StreamChunk).accumulated;\n\n\t\t\tif (!(\"calls\" in ctx.store)) {\n\t\t\t\tctx.store.calls = [] as ExtractedToolCall[];\n\t\t\t\tctx.store.scanFrom = 0;\n\t\t\t}\n\t\t\tconst calls = ctx.store.calls as ExtractedToolCall[];\n\t\t\tlet i = ctx.store.scanFrom as number;\n\t\t\tlet added = false;\n\n\t\t\twhile (i < accumulated.length) {\n\t\t\t\tconst start = accumulated.indexOf(\"{\", i);\n\t\t\t\tif (start === -1) {\n\t\t\t\t\tctx.store.scanFrom = accumulated.length;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlet depth = 0;\n\t\t\t\tlet end = -1;\n\t\t\t\tlet inString = false;\n\t\t\t\tfor (let j = start; j < accumulated.length; j++) {\n\t\t\t\t\tconst ch = accumulated[j];\n\t\t\t\t\tif (inString) {\n\t\t\t\t\t\tif (ch === \"\\\\\" && j + 1 < accumulated.length) {\n\t\t\t\t\t\t\tj++; // skip escaped character\n\t\t\t\t\t\t} else if (ch === '\"') {\n\t\t\t\t\t\t\tinString = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (ch === '\"') {\n\t\t\t\t\t\tinString = true;\n\t\t\t\t\t} else if (ch === \"{\") {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t} else if (ch === \"}\") {\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\tend = j;\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\tif (end === -1) {\n\t\t\t\t\t// Incomplete — resume brace-scanning from this open brace\n\t\t\t\t\t// next chunk. Do NOT advance past it.\n\t\t\t\t\tctx.store.scanFrom = start;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst raw = accumulated.slice(start, end + 1);\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(raw) as Record<string, unknown>;\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof parsed.name === \"string\" &&\n\t\t\t\t\t\tparsed.arguments != null &&\n\t\t\t\t\t\ttypeof parsed.arguments === \"object\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcalls.push({\n\t\t\t\t\t\t\tname: parsed.name,\n\t\t\t\t\t\t\targuments: parsed.arguments as Record<string, unknown>,\n\t\t\t\t\t\t\traw,\n\t\t\t\t\t\t\tstartIndex: start,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tadded = true;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Not valid JSON — skip\n\t\t\t\t}\n\t\t\t\ti = end + 1;\n\t\t\t\tctx.store.scanFrom = i;\n\t\t\t}\n\n\t\t\t// Always return a fresh copy so downstream never holds a live\n\t\t\t// reference to ctx.store.calls.\n\t\t\treturn added ? [...calls] : calls.slice();\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ?? \"tool-call-extractor\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: [],\n\t\t\tmeta: aiMeta(\"tool_call_extractor\"),\n\t\t\tequals: toolCallsEqual,\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// costMeterExtractor\n// ---------------------------------------------------------------------------\n\n/** A cost meter reading from the stream. */\nexport type CostMeterReading = {\n\treadonly chunkCount: number;\n\treadonly charCount: number;\n\treadonly estimatedTokens: number;\n};\n\nexport type CostMeterOptions = {\n\t/** Characters per token approximation. Default: 4 (GPT-family). */\n\tcharsPerToken?: number;\n\tname?: string;\n};\n\nconst costMeterEqual = (a: CostMeterReading, b: CostMeterReading): boolean => {\n\tif (a === b) return true;\n\treturn (\n\t\ta.chunkCount === b.chunkCount &&\n\t\ta.charCount === b.charCount &&\n\t\ta.estimatedTokens === b.estimatedTokens\n\t);\n};\n\n/**\n * Mounts a cost meter on a streaming topic. Counts chunks, characters, and\n * estimates token count. Compose with `budgetGate` for hard-stop when LLM\n * output exceeds budget mid-generation.\n *\n * Default structural equals suppresses DATA emission when two consecutive\n * readings are identical (same chunk count + char count + token estimate).\n */\nexport function costMeterExtractor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\topts?: CostMeterOptions,\n): Node<CostMeterReading> {\n\tconst charsPerToken = opts?.charsPerToken ?? 4;\n\treturn derived<CostMeterReading>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk]) => {\n\t\t\tif (chunk == null) return { chunkCount: 0, charCount: 0, estimatedTokens: 0 };\n\t\t\tconst c = chunk as StreamChunk;\n\t\t\tconst charCount = c.accumulated.length;\n\t\t\treturn {\n\t\t\t\tchunkCount: c.index + 1,\n\t\t\t\tcharCount,\n\t\t\t\testimatedTokens: Math.ceil(charCount / charsPerToken),\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ?? \"cost-meter\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: { chunkCount: 0, charCount: 0, estimatedTokens: 0 },\n\t\t\tmeta: aiMeta(\"cost_meter_extractor\"),\n\t\t\tequals: costMeterEqual,\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition B: Content safety pipeline\n// ---------------------------------------------------------------------------\n\n/** Options for {@link redactor}. */\nexport type RedactorOptions = {\n\tname?: string;\n};\n\n/**\n * Stream extractor that replaces matched patterns in the accumulated text.\n *\n * Returns a derived node emitting a sanitized `StreamChunk` on every chunk:\n * `accumulated` and `token` have matched substrings replaced by `replaceFn`.\n * The default `replaceFn` replaces with `\"[REDACTED]\"`.\n *\n * Compose with `contentGate` for in-flight safety pipelines.\n *\n * @param streamTopic - Streaming topic to monitor.\n * @param patterns - Array of RegExps to match against accumulated text.\n * @param replaceFn - Replacement producer (default: always `\"[REDACTED]\"`).\n */\nexport function redactor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\tpatterns: RegExp[],\n\treplaceFn?: (match: string, pattern: RegExp) => string,\n\topts?: RedactorOptions,\n): Node<StreamChunk> {\n\tconst replace = replaceFn ?? (() => \"[REDACTED]\");\n\n\tfunction sanitize(text: string): string {\n\t\tlet result = text;\n\t\tfor (const pat of patterns) {\n\t\t\tconst global = pat.global ? pat : new RegExp(pat.source, `${pat.flags}g`);\n\t\t\tresult = result.replace(global, (m) => replace(m, pat));\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn derived<StreamChunk>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk]) => {\n\t\t\tif (chunk == null) {\n\t\t\t\treturn { source: \"\", token: \"\", accumulated: \"\", index: -1 };\n\t\t\t}\n\t\t\tconst c = chunk as StreamChunk;\n\t\t\tconst sanitizedAccumulated = sanitize(c.accumulated);\n\t\t\tconst sanitizedToken = sanitize(c.token);\n\t\t\treturn {\n\t\t\t\tsource: c.source,\n\t\t\t\ttoken: sanitizedToken,\n\t\t\t\taccumulated: sanitizedAccumulated,\n\t\t\t\tindex: c.index,\n\t\t\t};\n\t\t},\n\t\t{ name: opts?.name ?? \"redactor\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Content safety decision. */\nexport type ContentDecision = \"allow\" | \"block\" | \"review\";\n\n/** Options for {@link contentGate}. */\nexport type ContentGateOptions = {\n\t/**\n\t * Hard-block threshold multiplier (default 1.5).\n\t * Scores above `threshold * hardMultiplier` emit `\"block\"`.\n\t * Scores between `threshold` and that emit `\"review\"`.\n\t */\n\thardMultiplier?: number;\n\tname?: string;\n};\n\n/**\n * Derived node that classifies accumulated stream text as `\"allow\"`,\n * `\"review\"`, or `\"block\"` based on a classifier score.\n *\n * Emits a three-way decision on every new chunk:\n * - `\"allow\"` — score below `threshold`\n * - `\"review\"` — score in `[threshold, threshold × hardMultiplier)`\n * - `\"block\"` — score at or above `threshold × hardMultiplier`\n *\n * Wire the output into a `valve` (automatic) or `gate` (human approval).\n * This node does not itself control flow — it just classifies.\n *\n * @param streamTopic - Streaming topic to classify.\n * @param classifier - `(accumulated: string) => number` scoring function, or\n * a `Node<number>` for live scores.\n * @param threshold - Score at which output becomes \"review\" or \"block\".\n */\nexport function contentGate(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\tclassifier: ((accumulated: string) => number) | Node<number>,\n\tthreshold: number,\n\topts?: ContentGateOptions,\n): Node<ContentDecision> {\n\tconst hardThreshold = threshold * (opts?.hardMultiplier ?? 1.5);\n\tconst isNodeClassifier = typeof classifier !== \"function\";\n\n\tconst deps: Node<unknown>[] = [streamTopic.latest as Node<StreamChunk | null>];\n\tif (isNodeClassifier) deps.push(classifier as Node<unknown>);\n\n\treturn derived<ContentDecision>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst chunk = values[0] as StreamChunk | undefined;\n\t\t\tif (chunk == null) return \"allow\";\n\n\t\t\tconst score = isNodeClassifier\n\t\t\t\t? ((values[1] as number | undefined) ?? 0)\n\t\t\t\t: (classifier as (text: string) => number)(chunk.accumulated);\n\n\t\t\tif (score >= hardThreshold) return \"block\";\n\t\t\tif (score >= threshold) return \"review\";\n\t\t\treturn \"allow\";\n\t\t},\n\t\t{ name: opts?.name ?? \"content-gate\", initial: \"allow\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// gatedStream\n// ---------------------------------------------------------------------------\n\nexport type GatedStreamOptions = StreamingPromptNodeOptions & {\n\t/** Gate options (maxPending, startOpen). */\n\tgate?: Omit<GateOptions, \"meta\">;\n};\n\n/**\n * Bundle returned by {@link gatedStream}.\n */\nexport type GatedStreamHandle<T> = {\n\t/** Final parsed result (after gate approval). */\n\toutput: Node<T | null>;\n\t/** Live stream topic — subscribe to `stream.latest` for chunks. */\n\tstream: TopicGraph<StreamChunk>;\n\t/** Gate controller — approve, reject (aborts in-flight stream), modify. */\n\tgate: GateController<T | null>;\n\t/** Tear down everything. */\n\tdispose: () => void;\n};\n\n/**\n * Streaming LLM transform with human-in-the-loop gate integration.\n *\n * Composes {@link streamingPromptNode} with {@link gate} so that:\n * - `gate.reject()` discards the pending value **and** aborts the in-flight\n * stream (cancels the `AbortController`).\n * - `gate.modify()` transforms the pending value before forwarding downstream.\n * - `gate.approve()` forwards the final result as normal.\n *\n * The abort-on-reject works by toggling an internal cancel signal that causes\n * the `switchMap` inside `streamingPromptNode` to restart with an empty message\n * list, which triggers the `AbortController.abort()` in the async generator's\n * `finally` block.\n */\nexport function gatedStream<T = string>(\n\tgraph: Graph,\n\tname: string,\n\tadapter: LLMAdapter,\n\tdeps: readonly Node<unknown>[],\n\tprompt: string | ((...depValues: unknown[]) => string),\n\topts?: GatedStreamOptions,\n): GatedStreamHandle<T> {\n\t// Cancel signal: toggling this forces switchMap to restart (aborting stream).\n\tconst cancelSignal = state<number>(0, { name: `${name}/cancel` });\n\tlet cancelCounter = 0;\n\n\t// Build the streaming prompt node with cancelSignal as an extra dep.\n\t// The cancel dep is excluded from prompt template arguments.\n\tconst allDeps = [...deps, cancelSignal] as readonly Node<unknown>[];\n\n\tconst sourceName = opts?.name ?? name;\n\tconst format = opts?.format ?? \"text\";\n\tconst streamTopic = topic<StreamChunk>(`${sourceName}/stream`);\n\n\tconst messagesNode = derived<readonly ChatMessage[]>(allDeps as Node<unknown>[], (values) => {\n\t\t// Last dep is the cancel signal — exclude from prompt args\n\t\tconst depValues = values.slice(0, -1);\n\t\tif (depValues.some((v) => v == null)) return [];\n\t\tconst text = typeof prompt === \"string\" ? prompt : prompt(...depValues);\n\t\tif (!text) return [];\n\t\tconst msgs: ChatMessage[] = [];\n\t\tif (opts?.systemPrompt) msgs.push({ role: \"system\", content: opts.systemPrompt });\n\t\tmsgs.push({ role: \"user\", content: text });\n\t\treturn msgs;\n\t});\n\n\tconst output = switchMap(messagesNode, (msgs) => {\n\t\tconst chatMsgs = msgs as readonly ChatMessage[];\n\t\tif (!chatMsgs || chatMsgs.length === 0) {\n\t\t\treturn state<T | null>(null) as NodeInput<T | null>;\n\t\t}\n\n\t\tconst ac = new AbortController();\n\n\t\tasync function* pumpAndCollect(): AsyncGenerator<T | null> {\n\t\t\tlet accumulated = \"\";\n\t\t\tlet index = 0;\n\t\t\ttry {\n\t\t\t\tfor await (const token of adapter.stream(chatMsgs, {\n\t\t\t\t\tmodel: opts?.model,\n\t\t\t\t\ttemperature: opts?.temperature,\n\t\t\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t\t\t\tsignal: ac.signal,\n\t\t\t\t})) {\n\t\t\t\t\taccumulated += token;\n\t\t\t\t\tstreamTopic.publish({\n\t\t\t\t\t\tsource: sourceName,\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\taccumulated,\n\t\t\t\t\t\tindex: index++,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tlet result: T | null;\n\t\t\t\tif (format === \"json\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = JSON.parse(stripFences(accumulated)) as T;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tresult = accumulated as unknown as T;\n\t\t\t\t}\n\t\t\t\tyield result;\n\t\t\t} finally {\n\t\t\t\tac.abort();\n\t\t\t}\n\t\t}\n\n\t\treturn fromAny(pumpAndCollect());\n\t});\n\n\tconst unsub = keepalive(output);\n\n\t// Filter: only forward non-null results to the gate. Null is the switchMap\n\t// initial/cancel state — not a real LLM result worth gating. Returning\n\t// undefined from a derived fn means \"no auto-emit\" (spec §2.4), so null\n\t// values are silently suppressed.\n\tconst nonNullOutput = derived<T>(\n\t\t[output],\n\t\t([v]) => {\n\t\t\tif (v == null) return undefined;\n\t\t\treturn v as T;\n\t\t},\n\t\t{\n\t\t\tname: `${name}/filter`,\n\t\t},\n\t);\n\n\t// Register the filtered output so gate() can find it as a dep\n\tgraph.add(`${name}/raw`, nonNullOutput);\n\n\t// Wire gate on the output\n\tconst gateCtrl = gate<T | null>(graph, `${name}/gate`, `${name}/raw`, opts?.gate);\n\n\t// Wrap reject to also abort the in-flight stream\n\tconst originalReject = gateCtrl.reject.bind(gateCtrl);\n\tconst gateWithAbort: GateController<T | null> = {\n\t\t...gateCtrl,\n\t\treject(count = 1) {\n\t\t\toriginalReject(count);\n\t\t\t// Toggle cancel signal to force switchMap restart → abort\n\t\t\tcancelSignal.down([[DATA, ++cancelCounter]]);\n\t\t},\n\t};\n\n\treturn {\n\t\toutput: gateCtrl.node,\n\t\tstream: streamTopic,\n\t\tgate: gateWithAbort,\n\t\tdispose: () => {\n\t\t\tunsub();\n\t\t\tstreamTopic.destroy();\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// promptNode\n// ---------------------------------------------------------------------------\n\nexport type PromptNodeOptions = {\n\tname?: string;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Output format — `\"json\"` attempts JSON.parse on the response. Default: `\"text\"`. */\n\tformat?: \"text\" | \"json\";\n\t/** Number of retries on transient errors. Default: 0. */\n\tretries?: number;\n\t/** Cache LLM responses for identical inputs. Default: false. */\n\tcache?: boolean;\n\tsystemPrompt?: string;\n\tmeta?: Record<string, unknown>;\n};\n\n/** Extract text content from an LLM response, handling various response shapes. */\nfunction extractContent(resp: unknown): string {\n\tif (resp != null && typeof resp === \"object\" && \"content\" in resp) {\n\t\treturn String((resp as LLMResponse).content);\n\t}\n\tif (typeof resp === \"string\") return resp;\n\treturn String(resp);\n}\n\n/**\n * Universal LLM transform: wraps a prompt template + model adapter into a reactive derived node.\n * Re-invokes the LLM whenever any dep changes. Suitable for triage, QA, hypothesis, parity, etc.\n *\n * @param adapter - LLM adapter (provider-agnostic).\n * @param deps - Input nodes whose values feed the prompt.\n * @param prompt - Static string or template function receiving dep values.\n * @param opts - Optional configuration.\n * @returns `Node` emitting LLM responses (string or parsed JSON).\n */\nexport function promptNode<T = string>(\n\tadapter: LLMAdapter,\n\tdeps: readonly Node<unknown>[],\n\tprompt: string | ((...depValues: unknown[]) => string),\n\topts?: PromptNodeOptions,\n): Node<T | null> {\n\tconst format = opts?.format ?? \"text\";\n\tconst retries = opts?.retries ?? 0;\n\tconst useCache = opts?.cache ?? false;\n\tconst cache = useCache ? new Map<string, T>() : null;\n\n\t// Seed with `initial: []` so `switchMap` below fires with `[]` during the\n\t// initial activation pass and emits null (composition guide §8 — promptNode\n\t// gates on nullish deps). Dep-level null guarding is done inside the fn.\n\tconst messagesNode = derived<readonly ChatMessage[]>(\n\t\tdeps as Node<unknown>[],\n\t\t(values) => {\n\t\t\t// Dep-level null guard (composition guide §8): if any dep is\n\t\t\t// nullish, return empty messages → switchMap emits null.\n\t\t\tif (values.some((v) => v == null)) return [];\n\t\t\tconst text = typeof prompt === \"string\" ? prompt : prompt(...values);\n\t\t\tif (!text) return [];\n\t\t\tconst msgs: ChatMessage[] = [];\n\t\t\tif (opts?.systemPrompt) msgs.push({ role: \"system\", content: opts.systemPrompt });\n\t\t\tmsgs.push({ role: \"user\", content: text });\n\t\t\treturn msgs;\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ? `${opts.name}::messages` : \"prompt_node::messages\",\n\t\t\tmeta: aiMeta(\"prompt_node\"),\n\t\t\tinitial: [] as readonly ChatMessage[],\n\t\t},\n\t);\n\n\tconst result = switchMap<readonly ChatMessage[], T | null>(messagesNode, (msgs) => {\n\t\tif (!msgs || msgs.length === 0) {\n\t\t\treturn state<T | null>(null) as NodeInput<T | null>;\n\t\t}\n\n\t\tconst cacheKey = useCache ? JSON.stringify(msgs.map((m) => [m.role, m.content])) : \"\";\n\t\tif (cache?.has(cacheKey)) {\n\t\t\treturn state<T | null>(cache.get(cacheKey)!) as NodeInput<T | null>;\n\t\t}\n\n\t\tasync function attempt(remaining: number): Promise<T | null> {\n\t\t\ttry {\n\t\t\t\tconst resp = await new Promise<LLMResponse>((resolve, reject) => {\n\t\t\t\t\tconst input = adapter.invoke(msgs, {\n\t\t\t\t\t\tmodel: opts?.model,\n\t\t\t\t\t\ttemperature: opts?.temperature,\n\t\t\t\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\t\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t\t\t\t});\n\t\t\t\t\t// NodeInput may be a Node, Promise, or raw value\n\t\t\t\t\tif (input && typeof (input as PromiseLike<LLMResponse>).then === \"function\") {\n\t\t\t\t\t\t(input as PromiseLike<LLMResponse>).then(resolve, reject);\n\t\t\t\t\t} else if (input && typeof (input as Node<LLMResponse>).subscribe === \"function\") {\n\t\t\t\t\t\tresolve((input as Node<LLMResponse>).cache as LLMResponse);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(input as LLMResponse);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tconst content = extractContent(resp);\n\t\t\t\tlet parsed: T;\n\t\t\t\tif (format === \"json\") {\n\t\t\t\t\tparsed = JSON.parse(stripFences(content)) as T;\n\t\t\t\t} else {\n\t\t\t\t\tparsed = content as unknown as T;\n\t\t\t\t}\n\t\t\t\tcache?.set(cacheKey, parsed);\n\t\t\t\treturn parsed;\n\t\t\t} catch (err) {\n\t\t\t\tif (remaining > 0) return attempt(remaining - 1);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\treturn attempt(retries) as NodeInput<T | null>;\n\t});\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// chatStream\n// ---------------------------------------------------------------------------\n\nexport type ChatStreamOptions = {\n\tgraph?: GraphOptions;\n\tmaxMessages?: number;\n};\n\nexport class ChatStreamGraph extends Graph {\n\tprivate readonly _log: ReactiveLogBundle<ChatMessage>;\n\treadonly messages: Node<readonly ChatMessage[]>;\n\treadonly latest: Node<ChatMessage | null>;\n\treadonly messageCount: Node<number>;\n\n\tconstructor(name: string, opts: ChatStreamOptions = {}) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis._log = reactiveLog<ChatMessage>([], {\n\t\t\tname: \"messages\",\n\t\t\tmaxSize: opts.maxMessages,\n\t\t});\n\t\tthis.messages = this._log.entries;\n\t\tthis.add(\"messages\", this.messages);\n\n\t\tthis.latest = derived<ChatMessage | null>(\n\t\t\t[this.messages],\n\t\t\t([snapshot]) => {\n\t\t\t\tconst entries = snapshot as readonly ChatMessage[];\n\t\t\t\treturn entries.length === 0 ? null : (entries[entries.length - 1] as ChatMessage);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"latest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"chat_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"latest\", this.latest);\n\t\tthis.addDisposer(keepalive(this.latest));\n\n\t\tthis.messageCount = derived<number>(\n\t\t\t[this.messages],\n\t\t\t([snapshot]) => (snapshot as readonly ChatMessage[]).length,\n\t\t\t{\n\t\t\t\tname: \"messageCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"chat_message_count\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"messageCount\", this.messageCount);\n\t\tthis.addDisposer(keepalive(this.messageCount));\n\t}\n\n\tappend(role: ChatMessage[\"role\"], content: string, extra?: Partial<ChatMessage>): void {\n\t\tthis._log.append({ role, content, ...extra });\n\t}\n\n\tappendToolResult(callId: string, content: string): void {\n\t\tthis._log.append({ role: \"tool\", content, toolCallId: callId });\n\t}\n\n\tclear(): void {\n\t\tthis._log.clear();\n\t}\n\n\tallMessages(): readonly ChatMessage[] {\n\t\treturn this.messages.cache as readonly ChatMessage[];\n\t}\n}\n\nexport function chatStream(name: string, opts?: ChatStreamOptions): ChatStreamGraph {\n\treturn new ChatStreamGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// toolRegistry\n// ---------------------------------------------------------------------------\n\nexport type ToolRegistryOptions = {\n\tgraph?: GraphOptions;\n};\n\nexport class ToolRegistryGraph extends Graph {\n\treadonly definitions: Node<ReadonlyMap<string, ToolDefinition>>;\n\treadonly schemas: Node<readonly ToolDefinition[]>;\n\n\tconstructor(name: string, opts: ToolRegistryOptions = {}) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis.definitions = state<ReadonlyMap<string, ToolDefinition>>(new Map(), {\n\t\t\tname: \"definitions\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"tool_definitions\"),\n\t\t});\n\t\tthis.add(\"definitions\", this.definitions);\n\n\t\tthis.schemas = derived<readonly ToolDefinition[]>(\n\t\t\t[this.definitions],\n\t\t\t([defs]) => [...((defs ?? new Map()) as ReadonlyMap<string, ToolDefinition>).values()],\n\t\t\t{\n\t\t\t\tname: \"schemas\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"tool_schemas\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tthis.add(\"schemas\", this.schemas);\n\t\tthis.addDisposer(keepalive(this.schemas));\n\t}\n\n\tregister(tool: ToolDefinition): void {\n\t\tconst current = this.definitions.cache as ReadonlyMap<string, ToolDefinition>;\n\t\tconst next = new Map(current);\n\t\tnext.set(tool.name, tool);\n\t\tthis.definitions.down([[DATA, next]]);\n\t}\n\n\tunregister(name: string): void {\n\t\tconst current = this.definitions.cache as ReadonlyMap<string, ToolDefinition>;\n\t\tif (!current.has(name)) return;\n\t\tconst next = new Map(current);\n\t\tnext.delete(name);\n\t\tthis.definitions.down([[DATA, next]]);\n\t}\n\n\tasync execute(name: string, args: Record<string, unknown>): Promise<unknown> {\n\t\tconst defs = this.definitions.cache as ReadonlyMap<string, ToolDefinition>;\n\t\tconst tool = defs.get(name);\n\t\tif (!tool) throw new Error(`toolRegistry: unknown tool \"${name}\"`);\n\t\tconst raw = tool.handler(args);\n\t\treturn resolveToolHandlerResult(raw);\n\t}\n\n\tgetDefinition(name: string): ToolDefinition | undefined {\n\t\treturn (this.definitions.cache as ReadonlyMap<string, ToolDefinition>)?.get(name);\n\t}\n}\n\nexport function toolRegistry(name: string, opts?: ToolRegistryOptions): ToolRegistryGraph {\n\treturn new ToolRegistryGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// systemPromptBuilder\n// ---------------------------------------------------------------------------\n\n/**\n * Assembles a system prompt from reactive sections. Each section is a\n * `NodeInput<string>` — the prompt updates when any section changes.\n */\nexport type SystemPromptHandle = Node<string> & { dispose: () => void };\n\nexport function systemPromptBuilder(\n\tsections: readonly NodeInput<string>[],\n\topts?: { separator?: string; name?: string },\n): SystemPromptHandle {\n\tconst separator = opts?.separator ?? \"\\n\\n\";\n\tconst sectionNodes = sections.map((s) => (typeof s === \"string\" ? state(s) : fromAny(s)));\n\tconst prompt = derived(\n\t\tsectionNodes,\n\t\t(values) => (values as string[]).filter((v) => v != null && v !== \"\").join(separator),\n\t\t{\n\t\t\tname: opts?.name ?? \"systemPrompt\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: aiMeta(\"system_prompt\"),\n\t\t\tinitial: \"\",\n\t\t},\n\t);\n\tconst unsub = keepalive(prompt);\n\treturn Object.assign(prompt, { dispose: unsub });\n}\n\n// ---------------------------------------------------------------------------\n// llmExtractor / llmConsolidator\n// ---------------------------------------------------------------------------\n\nexport type LLMExtractorOptions = {\n\tadapter: LLMAdapter;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n};\n\n/**\n * Returns an `extractFn` callback for `distill()` that invokes an LLM to\n * extract structured memories from raw input.\n *\n * The system prompt should instruct the LLM to return JSON matching\n * `Extraction<TMem>` shape: `{ upsert: [{ key, value }], remove?: [key] }`.\n */\nexport function llmExtractor<TRaw, TMem>(\n\tsystemPrompt: string,\n\topts: LLMExtractorOptions,\n): (raw: TRaw, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>> {\n\treturn (raw: TRaw, existing: ReadonlyMap<string, TMem>) => {\n\t\tconst existingKeys = [...existing.keys()].slice(0, 100); // sample for dedup\n\t\tconst messages: ChatMessage[] = [\n\t\t\t{ role: \"system\", content: systemPrompt },\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: JSON.stringify({\n\t\t\t\t\tinput: raw,\n\t\t\t\t\texistingKeys,\n\t\t\t\t}),\n\t\t\t},\n\t\t];\n\t\t// Wrap the adapter call in a producer that parses the JSON response\n\t\treturn producer<Extraction<TMem>>((actions) => {\n\t\t\tlet active = true;\n\t\t\tconst result = opts.adapter.invoke(messages, {\n\t\t\t\tmodel: opts.model,\n\t\t\t\ttemperature: opts.temperature ?? 0,\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t});\n\t\t\t// result is NodeInput — could be a Promise, Node, etc.\n\t\t\tconst resolved = fromAny(result);\n\t\t\tconst unsub = resolved.subscribe((msgs) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tlet done = false;\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst response = msg[1] as LLMResponse;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst parsed = JSON.parse(response.content) as Extraction<TMem>;\n\t\t\t\t\t\t\tactions.emit(parsed);\n\t\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tactions.down([\n\t\t\t\t\t\t\t\t[ERROR, new Error(\"llmExtractor: failed to parse LLM response as JSON\")],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tactions.down([[ERROR, msg[1]]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Forward unknown message types (spec §1.3.6)\n\t\t\t\t\t\tactions.down([[msg[0], msg[1]]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tactive = false;\n\t\t\t};\n\t\t});\n\t};\n}\n\nexport type LLMConsolidatorOptions = LLMExtractorOptions;\n\n/**\n * Returns a `consolidateFn` callback for `distill()` that invokes an LLM to\n * cluster and merge related memories.\n */\nexport function llmConsolidator<TMem>(\n\tsystemPrompt: string,\n\topts: LLMConsolidatorOptions,\n): (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>> {\n\treturn (entries: ReadonlyMap<string, TMem>) => {\n\t\tconst entriesArray = [...entries.entries()].map(([key, value]) => ({ key, value }));\n\t\tconst messages: ChatMessage[] = [\n\t\t\t{ role: \"system\", content: systemPrompt },\n\t\t\t{ role: \"user\", content: JSON.stringify({ memories: entriesArray }) },\n\t\t];\n\t\treturn producer<Extraction<TMem>>((actions) => {\n\t\t\tlet active = true;\n\t\t\tconst result = opts.adapter.invoke(messages, {\n\t\t\t\tmodel: opts.model,\n\t\t\t\ttemperature: opts.temperature ?? 0,\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t});\n\t\t\tconst resolved = fromAny(result);\n\t\t\tconst unsub = resolved.subscribe((msgs) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tlet done = false;\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst response = msg[1] as LLMResponse;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst parsed = JSON.parse(response.content) as Extraction<TMem>;\n\t\t\t\t\t\t\tactions.emit(parsed);\n\t\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tactions.down([\n\t\t\t\t\t\t\t\t[ERROR, new Error(\"llmConsolidator: failed to parse LLM response as JSON\")],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tactions.down([[ERROR, msg[1]]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Forward unknown message types (spec §1.3.6)\n\t\t\t\t\t\tactions.down([[msg[0], msg[1]]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tactive = false;\n\t\t\t};\n\t\t});\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// 3D Admission Scoring\n// ---------------------------------------------------------------------------\n\n/** Scores for the three admission dimensions. Each 0–1. */\nexport type AdmissionScores = {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n};\n\nexport type AdmissionScore3DOptions = {\n\t/** Custom scoring function. Default: rule-based (all dimensions 0.5). */\n\tscoreFn?: (raw: unknown) => AdmissionScores;\n\t/** Minimum persistence score to admit (default 0.3). */\n\tpersistenceThreshold?: number;\n\t/** Minimum personalValue score to admit (default 0.3). */\n\tpersonalValueThreshold?: number;\n\t/** Require structure score > 0 to admit (default false). */\n\trequireStructured?: boolean;\n};\n\n/**\n * Default 3D admission scorer. Returns middle scores for all dimensions.\n * Override with `scoreFn` for LLM-backed or domain-specific scoring.\n */\nfunction defaultAdmissionScorer(_raw: unknown): AdmissionScores {\n\treturn { persistence: 0.5, structure: 0.5, personalValue: 0.5 };\n}\n\n/**\n * Creates a 3D admission filter function compatible with `agentMemory`'s\n * `admissionFilter` option. Scores each candidate on persistence, structure,\n * and personalValue, then applies thresholds.\n */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions = {}): (raw: unknown) => boolean {\n\tconst scoreFn = opts.scoreFn ?? defaultAdmissionScorer;\n\tconst pThresh = opts.persistenceThreshold ?? 0.3;\n\tconst pvThresh = opts.personalValueThreshold ?? 0.3;\n\tconst reqStructured = opts.requireStructured ?? false;\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = scoreFn(raw);\n\t\tif (scores.persistence < pThresh) return false;\n\t\tif (scores.personalValue < pvThresh) return false;\n\t\tif (reqStructured && scores.structure <= 0) return false;\n\t\treturn true;\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Memory Tiers\n// ---------------------------------------------------------------------------\n\nexport type MemoryTier = \"permanent\" | \"active\" | \"archived\";\n\nexport type MemoryTiersOptions<TMem> = {\n\t/** Exponential decay rate per second for active tier.\n\t * Default: 7-day half-life ≈ ln(2)/(7×86400) ≈ 0.00000114. */\n\tdecayRate?: number;\n\t/** Max entries in the active tier before archiving lowest-scored (default 1000). */\n\tmaxActive?: number;\n\t/** Score threshold below which active entries get archived (default 0.1). */\n\tarchiveThreshold?: number;\n\t/** Predicate: true → entry belongs in permanent tier (default: never). */\n\tpermanentFilter?: (key: string, mem: TMem) => boolean;\n\t/** Storage tier for the archive. Omit to disable archiving. */\n\tarchiveTier?: StorageTier;\n\t/** Options forwarded to `graph.attachStorage` for the archive tier. */\n\tarchiveStorageOptions?: GraphAttachStorageOptions;\n};\n\nconst DEFAULT_DECAY_RATE = Math.LN2 / (7 * 86_400); // 7-day half-life\n\nexport type MemoryTiersBundle<TMem> = {\n\t/** Permanent tier: never evicted. */\n\treadonly permanent: LightCollectionBundle<TMem>;\n\t/** Active entries node (reactive, holds ReadonlyMap). */\n\treadonly activeEntries: Node<unknown>;\n\t/** Archive storage handle (null if no tier configured). */\n\treadonly archiveHandle: StorageHandle | null;\n\t/** Classify a key into its current tier. */\n\ttierOf: (key: string) => MemoryTier;\n\t/** Move a key to the permanent tier. */\n\tmarkPermanent: (key: string, value: TMem) => void;\n};\n\n// ---------------------------------------------------------------------------\n// Retrieval Pipeline\n// ---------------------------------------------------------------------------\n\nexport type RetrievalQuery = {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n};\n\nexport type RetrievalPipelineOptions<TMem> = {\n\t/** Max candidates from vector search (default 20). */\n\ttopK?: number;\n\t/** KG expansion depth in hops (default 1). */\n\tgraphDepth?: number;\n\t/** Token budget for final packing (default 2000). */\n\tbudget?: number;\n\t/** Cost function for budget packing. */\n\tcost: (mem: TMem) => number;\n\t/** Score function for ranking. */\n\tscore: (mem: TMem, context: unknown) => number;\n};\n\n/** A single entry in the retrieval result, with causal trace metadata. */\nexport type RetrievalEntry<TMem> = {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n};\n\n/** Causal trace for a retrieval run. */\nexport type RetrievalTrace<TMem> = {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n};\n\n// ---------------------------------------------------------------------------\n// agentMemory\n// ---------------------------------------------------------------------------\n\nexport type AgentMemoryOptions<TMem = unknown> = {\n\tgraph?: GraphOptions;\n\t/** LLM adapter for extraction and consolidation. */\n\tadapter?: LLMAdapter;\n\t/** System prompt for the extractor LLM. */\n\textractPrompt?: string;\n\t/** Custom extractFn (overrides adapter + extractPrompt). */\n\textractFn?: (raw: unknown, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;\n\t/** System prompt for the consolidation LLM. */\n\tconsolidatePrompt?: string;\n\t/** Custom consolidateFn (overrides adapter + consolidatePrompt). */\n\tconsolidateFn?: (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;\n\t/** Reactive trigger for consolidation (caller supplies e.g. `fromTimer`). */\n\tconsolidateTrigger?: NodeInput<unknown>;\n\t/** Score function for budget packing (required). */\n\tscore: (mem: TMem, context: unknown) => number;\n\t/** Cost function for budget packing (required). */\n\tcost: (mem: TMem) => number;\n\t/** Token budget for compact view (default 2000). */\n\tbudget?: number;\n\t/** Context node for scoring. */\n\tcontext?: NodeInput<unknown>;\n\t/** Admission filter (default: admit all). */\n\tadmissionFilter?: (candidate: unknown) => boolean;\n\t/** Vector index dimensions (> 0 enables vector index for retrieval). */\n\tvectorDimensions?: number;\n\n\t// --- In-factory composition (new) ---\n\n\t/** Extract embedding vector from a memory entry (enables vector index). */\n\tembedFn?: (mem: TMem) => readonly number[] | undefined;\n\t/** Enable knowledge graph for entity/relation tracking. */\n\tenableKnowledgeGraph?: boolean;\n\t/** Extract entities and relations from a memory entry. */\n\tentityFn?: (\n\t\tkey: string,\n\t\tmem: TMem,\n\t) =>\n\t\t| {\n\t\t\t\tentities?: Array<{ id: string; value: unknown }>;\n\t\t\t\trelations?: Array<{ from: string; to: string; relation: string; weight?: number }>;\n\t\t }\n\t\t| undefined;\n\n\t/** 3-tier storage configuration. Omit to use single-tier (existing behavior). */\n\ttiers?: MemoryTiersOptions<TMem>;\n\n\t/** Retrieval pipeline configuration. Requires vector index or knowledge graph. */\n\tretrieval?: {\n\t\t/** Max candidates from vector search (default 20). */\n\t\ttopK?: number;\n\t\t/** KG expansion depth in hops (default 1). */\n\t\tgraphDepth?: number;\n\t};\n\n\t/** Periodic reflection/consolidation configuration. */\n\treflection?: {\n\t\t/** Interval in ms between consolidation runs (default 300_000 = 5 min). */\n\t\tinterval?: number;\n\t\t/** Enable/disable periodic reflection (default true when consolidateFn is available). */\n\t\tenabled?: boolean;\n\t};\n};\n\nexport type AgentMemoryGraph<TMem = unknown> = Graph & {\n\treadonly distillBundle: DistillBundle<TMem>;\n\treadonly compact: Node<Array<{ key: string; value: TMem; score: number }>>;\n\treadonly size: Node<number>;\n\t/** Vector index bundle (null if not enabled). */\n\treadonly vectors: VectorIndexBundle<TMem> | null;\n\t/** Knowledge graph (null if not enabled). */\n\treadonly kg: KnowledgeGraphGraph<unknown, string> | null;\n\t/** Memory tiers bundle (null if not configured). */\n\treadonly memoryTiers: MemoryTiersBundle<TMem> | null;\n\t/** Retrieval result node (null if no retrieval pipeline configured). */\n\treadonly retrieval: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null;\n\t/** Latest retrieval trace for observability (null if no retrieval pipeline). */\n\treadonly retrievalTrace: Node<RetrievalTrace<TMem> | null> | null;\n\t/**\n\t * Execute a retrieval query (null if no retrieval pipeline).\n\t *\n\t * **Synchronous consumer API** — returns the result immediately and batch-writes\n\t * `retrieval` and `retrievalTrace` state nodes for observers. Reads the store\n\t * snapshot and context value **at call time** (external-boundary read).\n\t *\n\t * **Do not call from inside a reactive fn body** (derived fn, subscribe callback,\n\t * effect body). The cache reads would become transitive protocol violations and\n\t * may observe wave-progressive rather than wave-final state.\n\t *\n\t * **Caller-batch caveat:** if invoked inside a caller's `batch(() => ...)` alongside\n\t * upstream store mutations, the store snapshot reflects what has been committed to\n\t * `store.entries.cache` at call time. State-backed stores update cache synchronously\n\t * so batched inserts are visible; derived-backed store transforms may defer. If you\n\t * need fresh state after batched mutations, call `retrieve` after the batch returns.\n\t */\n\treadonly retrieve: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null;\n};\n\n/**\n * Pre-wired agentic memory graph. Composes `distill()` with optional\n * `knowledgeGraph()`, `vectorIndex()`, `lightCollection()` (permanent tier),\n * `decay()`, and `attachStorage()` (archive tier). Supports 3D admission\n * scoring, a default retrieval pipeline, periodic reflection, and\n * retrieval observability traces.\n */\n\n/** Extract the key→value map from a reactive_map snapshot. */\nfunction extractStoreMap<TMem>(snapshot: unknown): ReadonlyMap<string, TMem> {\n\tif (snapshot instanceof Map) return snapshot as ReadonlyMap<string, TMem>;\n\treturn new Map<string, TMem>();\n}\n\nexport function agentMemory<TMem = unknown>(\n\tname: string,\n\tsource: NodeInput<unknown>,\n\topts: AgentMemoryOptions<TMem>,\n): AgentMemoryGraph<TMem> {\n\tconst graph = new Graph(name, opts.graph);\n\tconst keepaliveSubs: Array<() => void> = [];\n\n\t// --- Extract function resolution ---\n\tlet rawExtractFn: (\n\t\traw: unknown,\n\t\texisting: ReadonlyMap<string, TMem>,\n\t) => NodeInput<Extraction<TMem>>;\n\tif (opts.extractFn) {\n\t\trawExtractFn = opts.extractFn;\n\t} else if (opts.adapter && opts.extractPrompt) {\n\t\trawExtractFn = llmExtractor<unknown, TMem>(opts.extractPrompt, { adapter: opts.adapter });\n\t} else {\n\t\tthrow new Error(\"agentMemory: provide either extractFn or adapter + extractPrompt\");\n\t}\n\tconst extractFn = (\n\t\traw: unknown,\n\t\texisting: ReadonlyMap<string, TMem>,\n\t): NodeInput<Extraction<TMem>> => {\n\t\tif (raw == null) return { upsert: [] };\n\t\treturn rawExtractFn(raw, existing);\n\t};\n\n\t// --- Admission filter ---\n\tlet filteredSource = source;\n\tif (opts.admissionFilter) {\n\t\tconst srcNode = fromAny(source);\n\t\tconst filter = opts.admissionFilter;\n\t\tfilteredSource = derived(\n\t\t\t[srcNode],\n\t\t\t([raw]) => {\n\t\t\t\tif (filter(raw)) return raw;\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{ name: \"admissionFilter\", describeKind: \"derived\" },\n\t\t);\n\t}\n\n\t// --- Consolidation ---\n\tlet consolidateFn:\n\t\t| ((entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>)\n\t\t| undefined;\n\tif (opts.consolidateFn) {\n\t\tconsolidateFn = opts.consolidateFn;\n\t} else if (opts.adapter && opts.consolidatePrompt) {\n\t\tconsolidateFn = llmConsolidator<TMem>(opts.consolidatePrompt, { adapter: opts.adapter });\n\t}\n\n\t// --- Reflection: default consolidateTrigger from fromTimer ---\n\tlet consolidateTrigger = opts.consolidateTrigger;\n\tif (!consolidateTrigger && consolidateFn && opts.reflection?.enabled !== false) {\n\t\tconst interval = opts.reflection?.interval ?? 300_000;\n\t\tconsolidateTrigger = fromTimer(interval, { period: interval });\n\t}\n\n\t// --- Build distill bundle ---\n\tconst distillOpts: DistillOptions<TMem> = {\n\t\tscore: opts.score,\n\t\tcost: opts.cost,\n\t\tbudget: opts.budget ?? 2000,\n\t\tcontext: opts.context,\n\t\tconsolidate: consolidateFn,\n\t\tconsolidateTrigger,\n\t};\n\tconst distillBundle = distill<unknown, TMem>(filteredSource, extractFn, distillOpts);\n\n\tgraph.add(\"store\", distillBundle.store.entries);\n\tgraph.add(\"compact\", distillBundle.compact);\n\tgraph.add(\"size\", distillBundle.size);\n\n\t// --- Vector index (optional) ---\n\tlet vectors: VectorIndexBundle<TMem> | null = null;\n\tif (opts.vectorDimensions && opts.vectorDimensions > 0 && opts.embedFn) {\n\t\tvectors = vectorIndex<TMem>({ dimension: opts.vectorDimensions });\n\t\tgraph.add(\"vectorIndex\", vectors.entries);\n\t}\n\n\t// --- Knowledge graph (optional) ---\n\tlet kg: KnowledgeGraphGraph<unknown, string> | null = null;\n\tif (opts.enableKnowledgeGraph) {\n\t\tkg = knowledgeGraph<unknown, string>(`${name}-kg`);\n\t\tgraph.mount(\"kg\", kg);\n\t}\n\n\t// --- 3-tier storage (optional) ---\n\tlet memoryTiersBundle: MemoryTiersBundle<TMem> | null = null;\n\tif (opts.tiers) {\n\t\tconst tiersOpts = opts.tiers;\n\t\tconst decayRate = tiersOpts.decayRate ?? DEFAULT_DECAY_RATE;\n\t\tconst maxActive = tiersOpts.maxActive ?? 1000;\n\t\tconst archiveThreshold = tiersOpts.archiveThreshold ?? 0.1;\n\t\tconst permanentFilter = tiersOpts.permanentFilter ?? (() => false);\n\n\t\t// Permanent tier\n\t\tconst permanent = lightCollection<TMem>({ name: \"permanent\" });\n\t\tgraph.add(\"permanent\", permanent.entries);\n\n\t\t// Track which keys are permanent\n\t\tconst permanentKeys = new Set<string>();\n\n\t\tconst tierOf = (key: string): MemoryTier => {\n\t\t\tif (permanentKeys.has(key)) return \"permanent\";\n\t\t\tconst storeMap = extractStoreMap<TMem>(distillBundle.store.entries.cache);\n\t\t\tif (storeMap.has(key)) return \"active\";\n\t\t\treturn \"archived\";\n\t\t};\n\n\t\tconst markPermanent = (key: string, value: TMem): void => {\n\t\t\tpermanentKeys.add(key);\n\t\t\tpermanent.upsert(key, value);\n\t\t};\n\n\t\t// Track entry creation times for accurate decay age calculation\n\t\tconst entryCreatedAtNs = new Map<string, number>();\n\n\t\t// Post-extraction hook: classify into tiers and archive low-scored entries\n\t\tconst storeNode = distillBundle.store.entries;\n\t\tconst contextNode = opts.context ? fromAny(opts.context) : state<unknown>(null);\n\t\tconst tierClassifier = effect([storeNode, contextNode], ([snapshot, ctx]) => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(snapshot);\n\t\t\tconst nowNs = monotonicNs();\n\t\t\tconst toArchive: string[] = [];\n\t\t\tconst toPermanent: Array<{ key: string; value: TMem }> = [];\n\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\t// Track creation time for new entries\n\t\t\t\tif (!entryCreatedAtNs.has(key)) {\n\t\t\t\t\tentryCreatedAtNs.set(key, nowNs);\n\t\t\t\t}\n\n\t\t\t\t// Check permanent classification\n\t\t\t\tif (permanentFilter(key, mem)) {\n\t\t\t\t\ttoPermanent.push({ key, value: mem });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Compute decayed score for active tier\n\t\t\t\tconst baseScore = opts.score(mem, ctx);\n\t\t\t\tconst createdNs = entryCreatedAtNs.get(key) ?? nowNs;\n\t\t\t\tconst ageSeconds = Number(nowNs - createdNs) / 1e9;\n\t\t\t\tconst decayed = decay(baseScore, ageSeconds, decayRate);\n\t\t\t\tif (decayed < archiveThreshold) {\n\t\t\t\t\ttoArchive.push(key);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Clean up creation times for removed entries\n\t\t\tfor (const key of entryCreatedAtNs.keys()) {\n\t\t\t\tif (!storeMap.has(key)) entryCreatedAtNs.delete(key);\n\t\t\t}\n\n\t\t\t// Move to permanent\n\t\t\tfor (const { key, value } of toPermanent) {\n\t\t\t\tif (!permanentKeys.has(key)) {\n\t\t\t\t\tmarkPermanent(key, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Archive and evict from active (respect maxActive, excluding permanent keys)\n\t\t\tconst activeCount = storeMap.size - permanentKeys.size;\n\t\t\tif (activeCount > maxActive) {\n\t\t\t\tconst scored = [...storeMap.entries()]\n\t\t\t\t\t.filter(([k]) => !permanentKeys.has(k))\n\t\t\t\t\t.map(([k, m]) => ({ key: k, score: opts.score(m, ctx) }))\n\t\t\t\t\t.sort((a, b) => a.score - b.score);\n\t\t\t\tconst excess = activeCount - maxActive;\n\t\t\t\tfor (let i = 0; i < excess && i < scored.length; i++) {\n\t\t\t\t\tconst sk = scored[i]!.key;\n\t\t\t\t\tif (!toArchive.includes(sk)) toArchive.push(sk);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Evict archived keys from active store\n\t\t\tif (toArchive.length > 0) {\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const key of toArchive) {\n\t\t\t\t\t\tdistillBundle.store.delete(key);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tkeepaliveSubs.push(tierClassifier.subscribe(() => undefined));\n\n\t\t// Archive checkpoint\n\t\tlet archiveHandle: StorageHandle | null = null;\n\t\tif (tiersOpts.archiveTier) {\n\t\t\tarchiveHandle = graph.attachStorage(\n\t\t\t\t[tiersOpts.archiveTier],\n\t\t\t\ttiersOpts.archiveStorageOptions ?? {},\n\t\t\t);\n\t\t}\n\n\t\tmemoryTiersBundle = {\n\t\t\tpermanent,\n\t\t\tactiveEntries: storeNode,\n\t\t\tarchiveHandle,\n\t\t\ttierOf,\n\t\t\tmarkPermanent,\n\t\t};\n\t}\n\n\t// --- Post-extraction hooks: vector + KG indexing ---\n\tif (vectors || kg) {\n\t\tconst embedFn = opts.embedFn;\n\t\tconst entityFn = opts.entityFn;\n\t\tconst storeNode = distillBundle.store.entries;\n\n\t\tconst indexer = effect([storeNode], ([snapshot]) => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(snapshot);\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\t// Vector indexing\n\t\t\t\tif (vectors && embedFn) {\n\t\t\t\t\tconst vec = embedFn(mem);\n\t\t\t\t\tif (vec) vectors.upsert(key, vec, mem);\n\t\t\t\t}\n\t\t\t\t// Knowledge graph entity/relation extraction\n\t\t\t\tif (kg && entityFn) {\n\t\t\t\t\tconst extracted = entityFn(key, mem);\n\t\t\t\t\tif (extracted) {\n\t\t\t\t\t\tfor (const ent of extracted.entities ?? []) {\n\t\t\t\t\t\t\tkg.upsertEntity(ent.id, ent.value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const rel of extracted.relations ?? []) {\n\t\t\t\t\t\t\tkg.link(rel.from, rel.to, rel.relation as string, rel.weight);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tkeepaliveSubs.push(indexer.subscribe(() => undefined));\n\t}\n\n\t// --- Retrieval pipeline (optional) ---\n\tlet retrievalNode: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null = null;\n\tlet retrievalTraceNode: Node<RetrievalTrace<TMem> | null> | null = null;\n\tlet retrieveFn: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null = null;\n\n\tif (vectors || kg) {\n\t\tconst topK = opts.retrieval?.topK ?? 20;\n\t\tconst graphDepth = opts.retrieval?.graphDepth ?? 1;\n\t\tconst budget = opts.budget ?? 2000;\n\t\tconst costFn = opts.cost;\n\t\tconst scoreFn = opts.score;\n\n\t\tconst contextNode = opts.context ? fromAny(opts.context) : state<unknown>(null);\n\n\t\t// Observer-facing state nodes. `retrieve()` writes both in a batch on every call.\n\t\t// (Option W from the 2026-04-12 P3 audit — retrieveFn is a sync consumer API that\n\t\t// reads store/context at call time, computes inline, and publishes results via\n\t\t// state writes. No derived, no queryInput, no closure side-channel.)\n\t\tconst retrievalOutput = state<ReadonlyArray<RetrievalEntry<TMem>>>([], {\n\t\t\tname: \"retrieval\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"retrieval_pipeline\"),\n\t\t});\n\t\tgraph.add(\"retrieval\", retrievalOutput);\n\t\tretrievalNode = retrievalOutput;\n\n\t\tconst traceState = state<RetrievalTrace<TMem> | null>(null, {\n\t\t\tname: \"retrievalTrace\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"retrieval_trace\"),\n\t\t});\n\t\tgraph.add(\"retrievalTrace\", traceState);\n\t\tretrievalTraceNode = traceState;\n\n\t\t// Sync consumer API. Reads `store.entries.cache` and `contextNode.cache` at\n\t\t// call time — these are external-boundary reads, allowed per the foundation\n\t\t// redesign. **Do not call from inside a reactive fn body**: the cache reads\n\t\t// would become transitive P3 violations.\n\t\tretrieveFn = (query: RetrievalQuery): ReadonlyArray<RetrievalEntry<TMem>> => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(distillBundle.store.entries.cache);\n\t\t\tconst ctx = contextNode.cache;\n\n\t\t\tconst candidateMap = new Map<\n\t\t\t\tstring,\n\t\t\t\t{ value: TMem; sources: Set<\"vector\" | \"graph\" | \"store\"> }\n\t\t\t>();\n\n\t\t\t// Stage 1: Vector search\n\t\t\tlet vectorCandidates: VectorSearchResult<TMem>[] = [];\n\t\t\tif (vectors && query.vector) {\n\t\t\t\tvectorCandidates = vectors.search(query.vector, topK) as VectorSearchResult<TMem>[];\n\t\t\t\tfor (const vc of vectorCandidates) {\n\t\t\t\t\tconst mem = storeMap.get(vc.id);\n\t\t\t\t\tif (mem) {\n\t\t\t\t\t\tcandidateMap.set(vc.id, { value: mem, sources: new Set([\"vector\"]) });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Stage 2: KG expansion\n\t\t\tconst graphExpanded: string[] = [];\n\t\t\tif (kg) {\n\t\t\t\tconst seedIds = [...(query.entityIds ?? []), ...[...candidateMap.keys()]];\n\t\t\t\tconst visited = new Set<string>();\n\t\t\t\tlet frontier = seedIds;\n\t\t\t\tfor (let depth = 0; depth < graphDepth; depth++) {\n\t\t\t\t\tconst nextFrontier: string[] = [];\n\t\t\t\t\tfor (const id of frontier) {\n\t\t\t\t\t\tif (visited.has(id)) continue;\n\t\t\t\t\t\tvisited.add(id);\n\t\t\t\t\t\tconst related = kg.related(id);\n\t\t\t\t\t\tfor (const edge of related) {\n\t\t\t\t\t\t\tconst targetId = edge.to;\n\t\t\t\t\t\t\tif (!visited.has(targetId)) {\n\t\t\t\t\t\t\t\tnextFrontier.push(targetId);\n\t\t\t\t\t\t\t\tconst mem = storeMap.get(targetId);\n\t\t\t\t\t\t\t\tif (mem) {\n\t\t\t\t\t\t\t\t\tconst existing = candidateMap.get(targetId);\n\t\t\t\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\t\t\t\texisting.sources.add(\"graph\");\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcandidateMap.set(targetId, { value: mem, sources: new Set([\"graph\"]) });\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tgraphExpanded.push(targetId);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfrontier = nextFrontier;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Also include direct store matches not yet in candidates\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\tif (!candidateMap.has(key)) {\n\t\t\t\t\tcandidateMap.set(key, { value: mem, sources: new Set([\"store\"]) });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Stage 3: Score and rank\n\t\t\tconst ranked: RetrievalEntry<TMem>[] = [];\n\t\t\tfor (const [key, { value, sources }] of candidateMap) {\n\t\t\t\tconst score = scoreFn(value, ctx);\n\t\t\t\tranked.push({ key, value, score, sources: [...sources] });\n\t\t\t}\n\t\t\tranked.sort((a, b) => b.score - a.score);\n\n\t\t\t// Stage 4: Budget packing\n\t\t\tconst packed: RetrievalEntry<TMem>[] = [];\n\t\t\tlet usedBudget = 0;\n\t\t\tfor (const entry of ranked) {\n\t\t\t\tconst c = costFn(entry.value);\n\t\t\t\tif (usedBudget + c > budget && packed.length > 0) break;\n\t\t\t\tpacked.push(entry);\n\t\t\t\tusedBudget += c;\n\t\t\t}\n\n\t\t\tconst trace: RetrievalTrace<TMem> = {\n\t\t\t\tvectorCandidates,\n\t\t\t\tgraphExpanded,\n\t\t\t\tranked,\n\t\t\t\tpacked,\n\t\t\t};\n\n\t\t\tbatch(() => {\n\t\t\t\tretrievalOutput.down([[DATA, packed]]);\n\t\t\t\ttraceState.down([[DATA, trace]]);\n\t\t\t});\n\n\t\t\treturn packed;\n\t\t};\n\t}\n\n\t// --- Cleanup ---\n\tgraph.addDisposer(() => {\n\t\tfor (const unsub of keepaliveSubs) unsub();\n\t\tkeepaliveSubs.length = 0;\n\t});\n\n\treturn Object.assign(graph, {\n\t\tdistillBundle,\n\t\tcompact: distillBundle.compact,\n\t\tsize: distillBundle.size,\n\t\tvectors,\n\t\tkg,\n\t\tmemoryTiers: memoryTiersBundle,\n\t\tretrieval: retrievalNode,\n\t\tretrievalTrace: retrievalTraceNode,\n\t\tretrieve: retrieveFn,\n\t}) as AgentMemoryGraph<TMem>;\n}\n\n// ---------------------------------------------------------------------------\n// agentLoop\n// ---------------------------------------------------------------------------\n\nexport type AgentLoopOptions = {\n\tgraph?: GraphOptions;\n\tadapter: LLMAdapter;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n\tmaxTurns?: number;\n\tstopWhen?: (response: LLMResponse) => boolean;\n\tonToolCall?: (call: ToolCall) => void;\n\tmaxMessages?: number;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n};\n\nexport class AgentLoopGraph extends Graph {\n\treadonly chat: ChatStreamGraph;\n\treadonly tools: ToolRegistryGraph;\n\treadonly status: Node<AgentLoopStatus>;\n\treadonly turnCount: Node<number>;\n\treadonly lastResponse: Node<LLMResponse | null>;\n\tprivate readonly _statusState: Node<AgentLoopStatus>;\n\tprivate readonly _turnCountState: Node<number>;\n\tprivate readonly _adapter: LLMAdapter;\n\tprivate readonly _maxTurns: number;\n\tprivate readonly _stopWhen?: (response: LLMResponse) => boolean;\n\tprivate readonly _onToolCall?: (call: ToolCall) => void;\n\tprivate readonly _systemPrompt?: string;\n\tprivate readonly _model?: string;\n\tprivate readonly _temperature?: number;\n\tprivate readonly _maxTokens?: number;\n\tprivate _running = false;\n\tprivate _abortController: AbortController | null = null;\n\n\tconstructor(name: string, opts: AgentLoopOptions) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis._adapter = opts.adapter;\n\t\tthis._maxTurns = opts.maxTurns ?? 10;\n\t\tthis._stopWhen = opts.stopWhen;\n\t\tthis._onToolCall = opts.onToolCall;\n\t\tthis._systemPrompt = opts.systemPrompt;\n\t\tthis._model = opts.model;\n\t\tthis._temperature = opts.temperature;\n\t\tthis._maxTokens = opts.maxTokens;\n\n\t\t// Mount chat subgraph\n\t\tthis.chat = chatStream(`${name}-chat`, { maxMessages: opts.maxMessages });\n\t\tthis.mount(\"chat\", this.chat);\n\n\t\t// Mount tool registry subgraph\n\t\tthis.tools = toolRegistry(`${name}-tools`);\n\t\tthis.mount(\"tools\", this.tools);\n\n\t\t// Register initial tools\n\t\tif (opts.tools) {\n\t\t\tfor (const tool of opts.tools) {\n\t\t\t\tthis.tools.register(tool);\n\t\t\t}\n\t\t}\n\n\t\t// Status state\n\t\tthis._statusState = state<AgentLoopStatus>(\"idle\", {\n\t\t\tname: \"status\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_status\"),\n\t\t});\n\t\tthis.status = this._statusState;\n\t\tthis.add(\"status\", this.status);\n\n\t\t// Turn count\n\t\tthis._turnCountState = state<number>(0, {\n\t\t\tname: \"turnCount\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_turn_count\"),\n\t\t});\n\t\tthis.turnCount = this._turnCountState;\n\t\tthis.add(\"turnCount\", this.turnCount);\n\n\t\t// Last LLM response\n\t\tthis.lastResponse = state<LLMResponse | null>(null, {\n\t\t\tname: \"lastResponse\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_last_response\"),\n\t\t});\n\t\tthis.add(\"lastResponse\", this.lastResponse);\n\t}\n\n\t/**\n\t * Start the agent loop with a user message. The loop runs reactively:\n\t * think (LLM call) → act (tool execution) → repeat until done.\n\t *\n\t * Messages accumulate across calls. Call `chat.clear()` before `run()`\n\t * to reset conversation history.\n\t */\n\tasync run(userMessage: string): Promise<LLMResponse | null> {\n\t\tif (this._running) throw new Error(\"agentLoop: already running\");\n\t\tthis._running = true;\n\t\tthis._abortController = new AbortController();\n\t\tconst { signal } = this._abortController;\n\n\t\tbatch(() => {\n\t\t\tthis._statusState.down([[DATA, \"idle\" as AgentLoopStatus]]);\n\t\t\tthis._turnCountState.down([[DATA, 0]]);\n\t\t});\n\t\tthis.chat.append(\"user\", userMessage);\n\n\t\ttry {\n\t\t\tlet turns = 0;\n\t\t\twhile (turns < this._maxTurns) {\n\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\t\t\t\tturns++;\n\t\t\t\tbatch(() => {\n\t\t\t\t\tthis._turnCountState.down([[DATA, turns]]);\n\t\t\t\t\tthis._statusState.down([[DATA, \"thinking\" as AgentLoopStatus]]);\n\t\t\t\t});\n\n\t\t\t\t// Invoke LLM\n\t\t\t\tconst msgs = this.chat.allMessages();\n\t\t\t\tconst toolSchemas = (this.tools.schemas.cache as readonly ToolDefinition[]) ?? [];\n\t\t\t\tconst response = await this._invokeLLM(msgs, toolSchemas, signal);\n\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\n\t\t\t\t(this.lastResponse as Node<LLMResponse | null>).down([[DATA, response]]);\n\n\t\t\t\t// Append assistant message\n\t\t\t\tthis.chat.append(\"assistant\", response.content, {\n\t\t\t\t\ttoolCalls: response.toolCalls,\n\t\t\t\t});\n\n\t\t\t\t// Check stop conditions\n\t\t\t\tif (this._shouldStop(response)) {\n\t\t\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\t\t\tthis._running = false;\n\t\t\t\t\tthis._abortController = null;\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Execute tool calls if present\n\t\t\t\tif (response.toolCalls && response.toolCalls.length > 0) {\n\t\t\t\t\tthis._statusState.down([[DATA, \"acting\" as AgentLoopStatus]]);\n\t\t\t\t\tfor (const call of response.toolCalls) {\n\t\t\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\t\t\t\t\t\tthis._onToolCall?.(call);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await this.tools.execute(call.name, call.arguments);\n\t\t\t\t\t\t\tthis.chat.appendToolResult(call.id, JSON.stringify(result));\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tthis.chat.appendToolResult(call.id, JSON.stringify({ error: String(err) }));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// No tool calls and not explicitly stopped → done\n\t\t\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\t\t\tthis._running = false;\n\t\t\t\t\tthis._abortController = null;\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Max turns reached\n\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\tthis._running = false;\n\t\t\tthis._abortController = null;\n\t\t\treturn this.lastResponse.cache as LLMResponse | null;\n\t\t} catch (err) {\n\t\t\tthis._statusState.down([[DATA, \"error\" as AgentLoopStatus]]);\n\t\t\tthis._running = false;\n\t\t\tthis._abortController = null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate async _invokeLLM(\n\t\tmsgs: readonly ChatMessage[],\n\t\ttools: readonly ToolDefinition[],\n\t\tsignal?: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tconst result = this._adapter.invoke(msgs, {\n\t\t\ttools: tools.length > 0 ? tools : undefined,\n\t\t\tsystemPrompt: this._systemPrompt,\n\t\t\tmodel: this._model,\n\t\t\ttemperature: this._temperature,\n\t\t\tmaxTokens: this._maxTokens,\n\t\t\tsignal,\n\t\t});\n\t\t// Null/undefined guard\n\t\tif (result == null) {\n\t\t\tthrow new Error(\"_invokeLLM: adapter.invoke() returned null or undefined\");\n\t\t}\n\t\t// String guard — fromAny would iterate characters\n\t\tif (typeof result === \"string\") {\n\t\t\tthrow new Error(\"_invokeLLM: adapter.invoke() returned a string, expected LLMResponse\");\n\t\t}\n\t\t// If result is already an LLMResponse (sync adapter), return directly\n\t\tif (\n\t\t\ttypeof result === \"object\" &&\n\t\t\t\"content\" in result &&\n\t\t\t!(\"subscribe\" in result) &&\n\t\t\t!(\"then\" in result)\n\t\t) {\n\t\t\treturn result as LLMResponse;\n\t\t}\n\t\t// If result is a Promise, await it then check for LLMResponse\n\t\tif (isPromiseLike(result)) {\n\t\t\tconst awaited = await result;\n\t\t\tif (\n\t\t\t\ttypeof awaited === \"object\" &&\n\t\t\t\tawaited !== null &&\n\t\t\t\t\"content\" in awaited &&\n\t\t\t\t!(\"subscribe\" in awaited)\n\t\t\t) {\n\t\t\t\treturn awaited as LLMResponse;\n\t\t\t}\n\t\t\treturn firstDataFromNode(fromAny(awaited as NodeInput<LLMResponse>)) as Promise<LLMResponse>;\n\t\t}\n\t\t// If result is a Node or async iterable, resolve via fromAny + firstDataFromNode\n\t\treturn firstDataFromNode(fromAny(result)) as Promise<LLMResponse>;\n\t}\n\n\tprivate _shouldStop(response: LLMResponse): boolean {\n\t\tif (\n\t\t\tresponse.finishReason === \"end_turn\" &&\n\t\t\t(!response.toolCalls || response.toolCalls.length === 0)\n\t\t)\n\t\t\treturn true;\n\t\tif (this._stopWhen?.(response)) return true;\n\t\treturn false;\n\t}\n\n\toverride destroy(): void {\n\t\tif (this._abortController) {\n\t\t\tthis._abortController.abort();\n\t\t\tthis._abortController = null;\n\t\t}\n\t\tthis._running = false;\n\t\tsuper.destroy();\n\t}\n}\n\nexport function agentLoop(name: string, opts: AgentLoopOptions): AgentLoopGraph {\n\treturn new AgentLoopGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// 5.4 — LLM tool integration\n// ---------------------------------------------------------------------------\n\n/** OpenAI function-calling tool schema. */\nexport type OpenAIToolSchema = {\n\treadonly type: \"function\";\n\treadonly function: {\n\t\treadonly name: string;\n\t\treadonly description: string;\n\t\treadonly parameters: Record<string, unknown>;\n\t};\n};\n\n/** MCP (Model Context Protocol) tool schema. */\nexport type McpToolSchema = {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly inputSchema: Record<string, unknown>;\n};\n\n/** Result of {@link knobsAsTools}. */\nexport type KnobsAsToolsResult = {\n\t/** OpenAI function-calling tool schemas. */\n\treadonly openai: readonly OpenAIToolSchema[];\n\t/** MCP tool schemas. */\n\treadonly mcp: readonly McpToolSchema[];\n\t/** GraphReFly ToolDefinitions with handlers that call `graph.set()`. */\n\treadonly definitions: readonly ToolDefinition[];\n};\n\n/**\n * Build a JSON Schema `properties.value` descriptor from a node's meta fields.\n *\n * Maps `meta.type`, `meta.range`, `meta.values`, `meta.format`, and `meta.unit`\n * to a JSON Schema property definition.\n */\nfunction metaToJsonSchema(meta: Record<string, unknown>): Record<string, unknown> {\n\tconst schema: Record<string, unknown> = {};\n\n\tconst metaType = meta.type as string | undefined;\n\tif (metaType === \"enum\" && Array.isArray(meta.values)) {\n\t\tschema.type = \"string\";\n\t\tschema.enum = meta.values;\n\t} else if (metaType === \"integer\") {\n\t\tschema.type = \"integer\";\n\t} else if (metaType === \"number\") {\n\t\tschema.type = \"number\";\n\t} else if (metaType === \"boolean\") {\n\t\tschema.type = \"boolean\";\n\t} else if (metaType === \"string\") {\n\t\tschema.type = \"string\";\n\t} else {\n\t\t// Unknown or unspecified — accept anything\n\t\tschema.type = [\"string\", \"number\", \"boolean\"];\n\t}\n\n\tif (Array.isArray(meta.range) && meta.range.length === 2) {\n\t\tschema.minimum = meta.range[0];\n\t\tschema.maximum = meta.range[1];\n\t}\n\n\tif (typeof meta.format === \"string\") {\n\t\tschema.description = `Format: ${meta.format}`;\n\t}\n\n\tif (typeof meta.unit === \"string\") {\n\t\tif (schema.description) {\n\t\t\tschema.description += ` (${meta.unit})`;\n\t\t} else {\n\t\t\tschema.description = `Unit: ${meta.unit}`;\n\t\t}\n\t}\n\n\treturn schema;\n}\n\n/**\n * Derive tool schemas from a graph's writable (knob) nodes.\n *\n * Knobs are state nodes whose `meta.access` is `\"llm\"`, `\"both\"`, or absent\n * (default: writable). Each knob becomes a tool that calls `graph.set()`.\n *\n * Speaks **domain language** (spec §5.4): the returned schemas use node names\n * and meta descriptions — no protocol internals exposed.\n *\n * @param graph - The graph to introspect.\n * @param actor - Optional actor for guard-scoped describe.\n * @returns OpenAI, MCP, and GraphReFly tool schemas.\n */\nexport function knobsAsTools(graph: Graph, actor?: Actor): KnobsAsToolsResult {\n\tconst described = graph.describe({ actor, detail: \"full\" });\n\tconst openai: OpenAIToolSchema[] = [];\n\tconst mcp: McpToolSchema[] = [];\n\tconst definitions: ToolDefinition[] = [];\n\n\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\t// Only state nodes are writable knobs\n\t\tif (node.type !== \"state\") continue;\n\n\t\t// Skip meta companion nodes (§2.3)\n\t\tif (path.includes(\"::__meta__::\")) continue;\n\n\t\t// Skip terminal-state nodes (§1.3.4 — no further messages after COMPLETE/ERROR)\n\t\tif (node.status === \"completed\" || node.status === \"errored\") continue;\n\n\t\t// Skip if access explicitly excludes LLM\n\t\tconst meta = node.meta ?? {};\n\t\tconst access = meta.access as string | undefined;\n\t\tif (access === \"human\" || access === \"system\") continue;\n\n\t\tconst description = (meta.description as string) ?? `Set the value of ${path}`;\n\t\tconst valueSchema = metaToJsonSchema(meta);\n\n\t\tconst parameterSchema: Record<string, unknown> = {\n\t\t\ttype: \"object\",\n\t\t\trequired: [\"value\"],\n\t\t\tproperties: {\n\t\t\t\tvalue: valueSchema,\n\t\t\t},\n\t\t\tadditionalProperties: false,\n\t\t};\n\n\t\t// OpenAI requires [a-zA-Z0-9_-] in function names; sanitize :: separators\n\t\tconst sanitizedName = path.replace(/::/g, \"__\");\n\n\t\topenai.push({\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: sanitizedName,\n\t\t\t\tdescription,\n\t\t\t\tparameters: parameterSchema,\n\t\t\t},\n\t\t});\n\n\t\tmcp.push({\n\t\t\tname: path,\n\t\t\tdescription,\n\t\t\tinputSchema: parameterSchema,\n\t\t});\n\n\t\tconst graphRef = graph;\n\t\tconst actorRef = actor;\n\t\tconst nv = node.v;\n\t\tdefinitions.push({\n\t\t\tname: path,\n\t\t\tdescription,\n\t\t\tparameters: parameterSchema,\n\t\t\thandler(args: Record<string, unknown>) {\n\t\t\t\tgraphRef.set(path, args.value, actorRef ? { actor: actorRef } : undefined);\n\t\t\t\treturn args.value;\n\t\t\t},\n\t\t\t...(nv != null ? { version: { id: nv.id, version: nv.version } } : {}),\n\t\t});\n\t}\n\n\treturn { openai, mcp, definitions };\n}\n\n// ---------------------------------------------------------------------------\n// gaugesAsContext\n// ---------------------------------------------------------------------------\n\nexport type GaugesAsContextOptions = {\n\t/** Group gauges by `meta.tags` (default true). */\n\tgroupByTags?: boolean;\n\t/** Separator between gauge lines (default \"\\n\"). */\n\tseparator?: string;\n\t/**\n\t * V0 delta mode (§6.0b): only include nodes whose `v.version` exceeds\n\t * the corresponding entry in this map. Nodes without V0 or not in the\n\t * map are always included. Callers maintain this map across calls.\n\t *\n\t * The `id` field guards against node replacement: if a node is removed\n\t * and re-added under the same name (new id), it is always included.\n\t */\n\tsinceVersion?: ReadonlyMap<string, { id: string; version: number }>;\n};\n\n/**\n * Format a graph's readable (gauge) nodes as a context string for LLM\n * system prompts.\n *\n * Gauges are nodes with `meta.description` or `meta.format`. Values are\n * formatted using `meta.format` and `meta.unit` hints.\n *\n * @param graph - The graph to introspect.\n * @param actor - Optional actor for guard-scoped describe.\n * @param options - Formatting options.\n * @returns A formatted string ready for system prompt injection.\n */\nexport function gaugesAsContext(\n\tgraph: Graph,\n\tactor?: Actor,\n\toptions?: GaugesAsContextOptions,\n): string {\n\tconst described = graph.describe({ actor, detail: \"full\" });\n\tconst groupByTags = options?.groupByTags ?? true;\n\tconst separator = options?.separator ?? \"\\n\";\n\n\ttype GaugeEntry = { path: string; description: string; formatted: string };\n\tconst entries: GaugeEntry[] = [];\n\n\tconst sinceVersion = options?.sinceVersion;\n\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\tconst meta = node.meta ?? {};\n\t\tconst desc = meta.description as string | undefined;\n\t\tconst format = meta.format as string | undefined;\n\t\t// Must have description or format to be a gauge\n\t\tif (!desc && !format) continue;\n\t\t// V0 delta filter: skip nodes unchanged since last seen version (§6.0b).\n\t\tif (sinceVersion != null && node.v != null) {\n\t\t\tconst lastSeen = sinceVersion.get(path);\n\t\t\tif (lastSeen != null && lastSeen.id === node.v.id && node.v.version <= lastSeen.version)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tconst label = desc ?? path;\n\t\tconst value = node.value;\n\t\tconst unit = meta.unit as string | undefined;\n\n\t\tlet formatted: string;\n\t\tif (format === \"currency\" && typeof value === \"number\") {\n\t\t\tformatted = `$${value.toFixed(2)}`;\n\t\t} else if (format === \"percentage\" && typeof value === \"number\") {\n\t\t\tformatted = `${(value * 100).toFixed(1)}%`;\n\t\t} else if (value === undefined || value === null) {\n\t\t\tformatted = \"(no value)\";\n\t\t} else {\n\t\t\tformatted = String(value);\n\t\t}\n\n\t\tif (unit && format !== \"currency\" && format !== \"percentage\") {\n\t\t\tformatted = `${formatted} ${unit}`;\n\t\t}\n\n\t\tentries.push({ path, description: label, formatted });\n\t}\n\n\tif (entries.length === 0) return \"\";\n\n\tif (groupByTags) {\n\t\tconst tagGroups = new Map<string, GaugeEntry[]>();\n\t\tconst ungrouped: GaugeEntry[] = [];\n\n\t\tfor (const entry of entries) {\n\t\t\tconst node = described.nodes[entry.path]!;\n\t\t\tconst tags = node.meta?.tags as string[] | undefined;\n\t\t\tif (tags && tags.length > 0) {\n\t\t\t\t// Use first tag for grouping to avoid duplicating entries across groups\n\t\t\t\tconst tag = tags[0]!;\n\t\t\t\tlet group = tagGroups.get(tag);\n\t\t\t\tif (!group) {\n\t\t\t\t\tgroup = [];\n\t\t\t\t\ttagGroups.set(tag, group);\n\t\t\t\t}\n\t\t\t\tgroup.push(entry);\n\t\t\t} else {\n\t\t\t\tungrouped.push(entry);\n\t\t\t}\n\t\t}\n\n\t\tif (tagGroups.size === 0) {\n\t\t\treturn entries.map((e) => `- ${e.description}: ${e.formatted}`).join(separator);\n\t\t}\n\n\t\tconst sections: string[] = [];\n\t\tfor (const [tag, group] of [...tagGroups.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n\t\t\tsections.push(\n\t\t\t\t`[${tag}]${separator}${group.map((e) => `- ${e.description}: ${e.formatted}`).join(separator)}`,\n\t\t\t);\n\t\t}\n\t\tif (ungrouped.length > 0) {\n\t\t\tsections.push(ungrouped.map((e) => `- ${e.description}: ${e.formatted}`).join(separator));\n\t\t}\n\t\treturn sections.join(separator + separator);\n\t}\n\n\treturn entries.map((e) => `- ${e.description}: ${e.formatted}`).join(separator);\n}\n\n// ---------------------------------------------------------------------------\n// validateGraphDef\n// ---------------------------------------------------------------------------\n\n/** Validation result from {@link validateGraphDef}. */\nexport type GraphDefValidation = {\n\treadonly valid: boolean;\n\treadonly errors: readonly string[];\n};\n\nconst VALID_NODE_TYPES = new Set([\"state\", \"derived\", \"producer\", \"operator\", \"effect\"]);\n\n/**\n * Validate an LLM-generated graph definition before passing to\n * `Graph.fromSnapshot()`.\n *\n * Checks:\n * - Required fields: `name`, `nodes`, `edges`\n * - Node types are valid enum values\n * - Edge `from`/`to` reference existing nodes\n * - No duplicate edge entries\n *\n * @param def - The graph definition to validate (parsed JSON).\n * @returns Validation result with errors array.\n */\nexport function validateGraphDef(def: unknown): GraphDefValidation {\n\tconst errors: string[] = [];\n\n\tif (def == null || typeof def !== \"object\") {\n\t\treturn { valid: false, errors: [\"Definition must be a non-null object\"] };\n\t}\n\n\tconst d = def as Record<string, unknown>;\n\n\tif (typeof d.name !== \"string\" || d.name.length === 0) {\n\t\terrors.push(\"Missing or empty 'name' field\");\n\t}\n\n\tif (d.nodes == null || typeof d.nodes !== \"object\" || Array.isArray(d.nodes)) {\n\t\terrors.push(\"Missing or invalid 'nodes' field (must be an object)\");\n\t\treturn { valid: false, errors };\n\t}\n\n\tconst nodeNames = new Set(Object.keys(d.nodes as object));\n\n\tfor (const [name, raw] of Object.entries(d.nodes as Record<string, unknown>)) {\n\t\tif (raw == null || typeof raw !== \"object\") {\n\t\t\terrors.push(`Node \"${name}\": must be an object`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = raw as Record<string, unknown>;\n\t\tif (typeof node.type !== \"string\" || !VALID_NODE_TYPES.has(node.type)) {\n\t\t\terrors.push(\n\t\t\t\t`Node \"${name}\": invalid type \"${String(node.type)}\" (expected: ${[...VALID_NODE_TYPES].join(\", \")})`,\n\t\t\t);\n\t\t}\n\t\tif (Array.isArray(node.deps)) {\n\t\t\tfor (const dep of node.deps) {\n\t\t\t\tif (typeof dep === \"string\" && !nodeNames.has(dep)) {\n\t\t\t\t\terrors.push(`Node \"${name}\": dep \"${dep}\" does not reference an existing node`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!Array.isArray(d.edges)) {\n\t\tif (d.edges !== undefined) {\n\t\t\terrors.push(\"'edges' must be an array\");\n\t\t}\n\t\t// edges are optional — no error if absent\n\t} else {\n\t\tconst seen = new Set<string>();\n\t\tfor (let i = 0; i < (d.edges as unknown[]).length; i++) {\n\t\t\tconst edge = (d.edges as unknown[])[i];\n\t\t\tif (edge == null || typeof edge !== \"object\") {\n\t\t\t\terrors.push(`Edge [${i}]: must be an object`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst e = edge as Record<string, unknown>;\n\t\t\tif (typeof e.from !== \"string\" || !nodeNames.has(e.from)) {\n\t\t\t\terrors.push(`Edge [${i}]: 'from' \"${String(e.from)}\" does not reference an existing node`);\n\t\t\t}\n\t\t\tif (typeof e.to !== \"string\" || !nodeNames.has(e.to)) {\n\t\t\t\terrors.push(`Edge [${i}]: 'to' \"${String(e.to)}\" does not reference an existing node`);\n\t\t\t}\n\t\t\tconst key = `${e.from}->${e.to}`;\n\t\t\tif (seen.has(key)) {\n\t\t\t\terrors.push(`Edge [${i}]: duplicate edge ${key}`);\n\t\t\t}\n\t\t\tseen.add(key);\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// graphFromSpec\n// ---------------------------------------------------------------------------\n\nexport type GraphFromSpecOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Callback to construct topology before values are applied (passed to `Graph.fromSnapshot`). */\n\tbuild?: (g: Graph) => void;\n\t/** Extra instructions appended to the system prompt. */\n\tsystemPromptExtra?: string;\n};\n\n/** Strip markdown code fences, handling trailing commentary after closing fence. */\nfunction stripFences(text: string): string {\n\tconst match = text.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```[\\s\\S]*$/);\n\treturn match ? match[1]! : text;\n}\n\nconst GRAPH_FROM_SPEC_SYSTEM_PROMPT = `You are a graph architect for GraphReFly, a reactive graph protocol.\n\nGiven a natural-language description, produce a JSON graph definition with this structure:\n\n{\n \"name\": \"<graph_name>\",\n \"nodes\": {\n \"<node_name>\": {\n \"type\": \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\",\n \"value\": <initial_value_or_null>,\n \"deps\": [\"<dep_node_name>\", ...],\n \"meta\": {\n \"description\": \"<human-readable purpose>\",\n \"type\": \"string\" | \"number\" | \"boolean\" | \"integer\" | \"enum\",\n \"range\": [min, max],\n \"values\": [\"a\", \"b\"],\n \"format\": \"currency\" | \"percentage\" | \"status\",\n \"access\": \"human\" | \"llm\" | \"both\" | \"system\",\n \"unit\": \"<unit>\",\n \"tags\": [\"<tag>\"]\n }\n }\n },\n \"edges\": [\n { \"from\": \"<source_node>\", \"to\": \"<target_node>\" }\n ]\n}\n\nRules:\n- \"state\" nodes have no deps and hold user/LLM-writable values (knobs).\n- \"derived\" nodes have deps and compute from them.\n- \"effect\" nodes have deps but produce side effects (no return value).\n- \"producer\" nodes have no deps but generate values asynchronously.\n- Edges wire output of one node as input to another. They must match deps.\n- meta.description is required for every node.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/**\n * Ask an LLM to compose a Graph from a natural-language description.\n *\n * The LLM returns a JSON graph definition which is validated and then\n * constructed via `Graph.fromSnapshot()`.\n *\n * @param naturalLanguage - The problem/use-case description.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options and optional `build` callback for node factories.\n * @returns A constructed Graph.\n * @throws On invalid LLM output or validation failure.\n */\nexport async function graphFromSpec(\n\tnaturalLanguage: string,\n\tadapter: LLMAdapter,\n\topts?: GraphFromSpecOptions,\n): Promise<Graph> {\n\tconst systemPrompt = opts?.systemPromptExtra\n\t\t? `${GRAPH_FROM_SPEC_SYSTEM_PROMPT}\\n\\n${opts.systemPromptExtra}`\n\t\t: GRAPH_FROM_SPEC_SYSTEM_PROMPT;\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{ role: \"user\", content: naturalLanguage },\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\tconst response = (await resolveToolHandlerResult(rawResult)) as LLMResponse;\n\tlet content = response.content.trim();\n\n\t// Strip markdown fences if present (handles trailing commentary after ```)\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`graphFromSpec: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateGraphDef(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`graphFromSpec: invalid graph definition:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tconst def = parsed as Record<string, unknown>;\n\t// Ensure version field is present for fromSnapshot envelope check\n\tif (def.version === undefined) def.version = 1;\n\tif (!Array.isArray(def.subgraphs)) def.subgraphs = [];\n\treturn Graph.fromSnapshot(def as GraphPersistSnapshot, opts?.build);\n}\n\n// ---------------------------------------------------------------------------\n// suggestStrategy\n// ---------------------------------------------------------------------------\n\n/** A single operation in a strategy plan. */\nexport type StrategyOperation =\n\t| {\n\t\t\treadonly type: \"add_node\";\n\t\t\treadonly name: string;\n\t\t\treadonly nodeType: string;\n\t\t\treadonly meta?: Record<string, unknown>;\n\t\t\treadonly initial?: unknown;\n\t }\n\t| { readonly type: \"remove_node\"; readonly name: string }\n\t| { readonly type: \"connect\"; readonly from: string; readonly to: string }\n\t| { readonly type: \"disconnect\"; readonly from: string; readonly to: string }\n\t| { readonly type: \"set_value\"; readonly name: string; readonly value: unknown }\n\t| {\n\t\t\treadonly type: \"update_meta\";\n\t\t\treadonly name: string;\n\t\t\treadonly key: string;\n\t\t\treadonly value: unknown;\n\t };\n\n/** Structured strategy plan returned by {@link suggestStrategy}. */\nexport type StrategyPlan = {\n\treadonly summary: string;\n\treadonly operations: readonly StrategyOperation[];\n\treadonly reasoning: string;\n};\n\nexport type SuggestStrategyOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\tactor?: Actor;\n};\n\nconst SUGGEST_STRATEGY_SYSTEM_PROMPT = `You are a reactive graph optimizer for GraphReFly.\n\nGiven a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.\n\nReturn ONLY valid JSON with this structure:\n{\n \"summary\": \"<one-line summary of the strategy>\",\n \"reasoning\": \"<explanation of why these changes help>\",\n \"operations\": [\n { \"type\": \"add_node\", \"name\": \"<name>\", \"nodeType\": \"state|derived|effect|producer|operator\", \"meta\": {...}, \"initial\": <value> },\n { \"type\": \"remove_node\", \"name\": \"<name>\" },\n { \"type\": \"connect\", \"from\": \"<source>\", \"to\": \"<target>\" },\n { \"type\": \"disconnect\", \"from\": \"<source>\", \"to\": \"<target>\" },\n { \"type\": \"set_value\", \"name\": \"<name>\", \"value\": <new_value> },\n { \"type\": \"update_meta\", \"name\": \"<name>\", \"key\": \"<meta_key>\", \"value\": <new_value> }\n ]\n}\n\nRules:\n- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).\n- Keep changes minimal — prefer the smallest set of operations that solves the problem.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/**\n * Ask an LLM to analyze a graph and suggest topology/parameter changes\n * to solve a stated problem.\n *\n * Returns a structured plan — does NOT auto-apply. The caller reviews\n * and selectively applies operations.\n *\n * @param graph - The graph to analyze.\n * @param problem - Natural-language problem statement.\n * @param adapter - LLM adapter for the analysis call.\n * @param opts - Model and actor options.\n * @returns A structured strategy plan.\n * @throws On invalid LLM output.\n */\nexport async function suggestStrategy(\n\tgraph: Graph,\n\tproblem: string,\n\tadapter: LLMAdapter,\n\topts?: SuggestStrategyOptions,\n): Promise<StrategyPlan> {\n\tconst { expand: _, ...described } = graph.describe({ actor: opts?.actor, detail: \"standard\" });\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: SUGGEST_STRATEGY_SYSTEM_PROMPT },\n\t\t{\n\t\t\trole: \"user\",\n\t\t\tcontent: JSON.stringify({\n\t\t\t\tgraph: described,\n\t\t\t\tproblem,\n\t\t\t}),\n\t\t},\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\tconst response = (await resolveToolHandlerResult(rawResult)) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = content.replace(/^```(?:json)?\\s*/, \"\").replace(/\\s*```$/, \"\");\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`suggestStrategy: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst plan = parsed as Record<string, unknown>;\n\n\tif (typeof plan.summary !== \"string\") {\n\t\tthrow new Error(\"suggestStrategy: missing 'summary' in response\");\n\t}\n\tif (typeof plan.reasoning !== \"string\") {\n\t\tthrow new Error(\"suggestStrategy: missing 'reasoning' in response\");\n\t}\n\tif (!Array.isArray(plan.operations)) {\n\t\tthrow new Error(\"suggestStrategy: missing 'operations' array in response\");\n\t}\n\n\treturn {\n\t\tsummary: plan.summary,\n\t\treasoning: plan.reasoning,\n\t\toperations: plan.operations as readonly StrategyOperation[],\n\t};\n}\n","/**\n * Memory patterns (roadmap §4.3).\n *\n * Domain-layer helpers composed from GraphRefly primitives. `vectorIndex` uses\n * an exact-search backend by default; an HNSW adapter can be injected as an\n * optional dependency.\n */\n\nimport { monotonicNs } from \"../core/clock.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { Graph } from \"../graph/graph.js\";\n\nexport type CollectionPolicy = \"fifo\" | \"lru\";\nexport type VectorBackend = \"flat\" | \"hnsw\";\n\nexport type LightCollectionEntry<T> = {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: number;\n\treadonly lastAccessNs: number;\n};\n\nexport type LightCollectionOptions = {\n\tname?: string;\n\tmaxSize?: number;\n\tpolicy?: CollectionPolicy;\n};\n\nexport type LightCollectionBundle<T> = {\n\treadonly entries: Node<ReadonlyMap<string, LightCollectionEntry<T>>>;\n\tupsert: (id: string, value: T) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tget: (id: string) => T | undefined;\n\thas: (id: string) => boolean;\n};\n\nexport type CollectionEntry<T> = LightCollectionEntry<T> & {\n\treadonly baseScore: number;\n};\n\nexport type RankedCollectionEntry<T> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionOptions<T> = {\n\tmaxSize?: number;\n\tpolicy?: CollectionPolicy;\n\t/**\n\t * Produces a base score at insert/update time.\n\t */\n\tscore?: (value: T) => number;\n\t/**\n\t * Exponential decay rate per second. 0 disables decay.\n\t */\n\tdecayRate?: number;\n\t/**\n\t * Minimum score floor after decay.\n\t */\n\tminScore?: number;\n};\n\nexport type CollectionGraph<T> = Graph & {\n\tupsert: (id: string, value: T, opts?: { score?: number }) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tgetItem: (id: string) => CollectionEntry<T> | undefined;\n};\n\nexport type VectorRecord<TMeta> = {\n\treadonly id: string;\n\treadonly vector: readonly number[];\n\treadonly meta?: TMeta;\n};\n\nexport type VectorSearchResult<TMeta> = {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n};\n\nexport type HnswAdapter<TMeta> = {\n\tupsert: (id: string, vector: readonly number[], meta?: TMeta) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tsearch: (query: readonly number[], k: number) => ReadonlyArray<VectorSearchResult<TMeta>>;\n};\n\nexport type VectorIndexOptions<TMeta> = {\n\tbackend?: VectorBackend;\n\tdimension?: number;\n\t/**\n\t * Optional dependency seam for HNSW.\n\t */\n\thnswFactory?: () => HnswAdapter<TMeta>;\n};\n\nexport type VectorIndexBundle<TMeta> = {\n\treadonly backend: VectorBackend;\n\treadonly entries: Node<ReadonlyMap<string, VectorRecord<TMeta>>>;\n\tupsert: (id: string, vector: readonly number[], meta?: TMeta) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tsearch: (query: readonly number[], k?: number) => ReadonlyArray<VectorSearchResult<TMeta>>;\n};\n\nexport type KnowledgeEdge<TRelation extends string = string> = {\n\treadonly from: string;\n\treadonly to: string;\n\treadonly relation: TRelation;\n\treadonly weight: number;\n};\n\nexport type KnowledgeGraphGraph<TEntity, TRelation extends string = string> = Graph & {\n\tupsertEntity: (id: string, value: TEntity) => void;\n\tremoveEntity: (id: string) => void;\n\tlink: (from: string, to: string, relation: TRelation, weight?: number) => void;\n\tunlink: (from: string, to: string, relation?: TRelation) => void;\n\trelated: (id: string, relation?: TRelation) => ReadonlyArray<KnowledgeEdge<TRelation>>;\n};\n\nexport function decay(\n\tbaseScore: number,\n\tageSeconds: number,\n\tratePerSecond: number,\n\tminScore = 0,\n): number {\n\tif (!Number.isFinite(baseScore)) return minScore;\n\tif (!Number.isFinite(ageSeconds) || ageSeconds <= 0) return Math.max(minScore, baseScore);\n\tif (!Number.isFinite(ratePerSecond) || ratePerSecond <= 0) return Math.max(minScore, baseScore);\n\tconst decayed = baseScore * Math.exp(-ratePerSecond * ageSeconds);\n\treturn Math.max(minScore, decayed);\n}\n\nfunction assertMaxSize(maxSize: number | undefined): void {\n\tif (maxSize !== undefined && maxSize < 1) {\n\t\tthrow new RangeError(\"maxSize must be >= 1\");\n\t}\n}\n\nfunction copyMap<K, V>(m: ReadonlyMap<K, V>): Map<K, V> {\n\treturn new Map(m);\n}\n\nfunction readMap<K, V>(node: Node<ReadonlyMap<K, V>>): ReadonlyMap<K, V> {\n\treturn node.cache ?? new Map<K, V>();\n}\n\nfunction readArray<T>(node: Node<ReadonlyArray<T>>): ReadonlyArray<T> {\n\treturn node.cache ?? [];\n}\n\nfunction cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\treturn dot / Math.sqrt(na * nb);\n}\n\nexport function lightCollection<T>(opts: LightCollectionOptions = {}): LightCollectionBundle<T> {\n\tconst maxSize = opts.maxSize;\n\tconst policy = opts.policy ?? \"fifo\";\n\tassertMaxSize(maxSize);\n\n\tconst entries = state<ReadonlyMap<string, LightCollectionEntry<T>>>(new Map(), {\n\t\tname: opts.name,\n\t\tdescribeKind: \"state\",\n\t});\n\n\tfunction evictIfNeeded(next: Map<string, LightCollectionEntry<T>>): void {\n\t\tif (maxSize === undefined) return;\n\t\twhile (next.size > maxSize) {\n\t\t\tlet victim: LightCollectionEntry<T> | undefined;\n\t\t\tfor (const entry of next.values()) {\n\t\t\t\tif (!victim) {\n\t\t\t\t\tvictim = entry;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lhs = policy === \"lru\" ? entry.lastAccessNs : entry.createdAtNs;\n\t\t\t\tconst rhs = policy === \"lru\" ? victim.lastAccessNs : victim.createdAtNs;\n\t\t\t\tif (lhs < rhs) victim = entry;\n\t\t\t}\n\t\t\tif (!victim) break;\n\t\t\tnext.delete(victim.id);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, LightCollectionEntry<T>>): void {\n\t\tentries.down([[DATA, next]]);\n\t}\n\n\treturn {\n\t\tentries,\n\t\tupsert(id, value) {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst current = readMap(entries);\n\t\t\tconst prev = current.get(id);\n\t\t\tconst next = copyMap(current);\n\t\t\tnext.set(id, {\n\t\t\t\tid,\n\t\t\t\tvalue,\n\t\t\t\tcreatedAtNs: prev?.createdAtNs ?? now,\n\t\t\t\tlastAccessNs: now,\n\t\t\t});\n\t\t\tevictIfNeeded(next);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id) {\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(entries).size === 0) return;\n\t\t\tcommit(new Map());\n\t\t},\n\t\tget(id) {\n\t\t\tconst current = readMap(entries);\n\t\t\tconst found = current.get(id);\n\t\t\tif (!found) return undefined;\n\t\t\tif (policy === \"lru\") {\n\t\t\t\tconst now = monotonicNs();\n\t\t\t\tconst next = copyMap(current);\n\t\t\t\tnext.set(id, { ...found, lastAccessNs: now });\n\t\t\t\tcommit(next);\n\t\t\t}\n\t\t\treturn found.value;\n\t\t},\n\t\thas(id) {\n\t\t\treturn readMap(entries).has(id);\n\t\t},\n\t};\n}\n\nexport function collection<T>(name: string, opts: CollectionOptions<T> = {}): CollectionGraph<T> {\n\tconst maxSize = opts.maxSize;\n\tconst policy = opts.policy ?? \"lru\";\n\tconst decayRate = opts.decayRate ?? 0;\n\tconst minScore = opts.minScore ?? 0;\n\tconst scoreFn = opts.score ?? (() => 1);\n\tassertMaxSize(maxSize);\n\n\tconst graph = new Graph(name);\n\tconst items = state<ReadonlyMap<string, CollectionEntry<T>>>(new Map(), {\n\t\tname: \"items\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst ranked = derived(\n\t\t[items],\n\t\t([snapshot]) => {\n\t\t\tconst typed = (snapshot ?? new Map()) as ReadonlyMap<string, CollectionEntry<T>>;\n\t\t\tconst now = monotonicNs();\n\t\t\tconst out = [...typed.values()].map((entry) => {\n\t\t\t\tconst ageSeconds = (now - entry.lastAccessNs) / 1_000_000_000;\n\t\t\t\treturn {\n\t\t\t\t\t...entry,\n\t\t\t\t\tscore: decay(entry.baseScore, ageSeconds, decayRate, minScore),\n\t\t\t\t};\n\t\t\t});\n\t\t\tout.sort((a, b) => b.score - a.score || b.lastAccessNs - a.lastAccessNs);\n\t\t\treturn out;\n\t\t},\n\t\t{ name: \"ranked\", describeKind: \"derived\" },\n\t);\n\tconst size = derived(\n\t\t[items],\n\t\t([snapshot]) => ((snapshot ?? new Map()) as ReadonlyMap<string, CollectionEntry<T>>).size,\n\t\t{\n\t\t\tname: \"size\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: 0,\n\t\t},\n\t);\n\tvoid ranked.subscribe(() => undefined);\n\tvoid size.subscribe(() => undefined);\n\n\tgraph.add(\"items\", items);\n\tgraph.add(\"ranked\", ranked);\n\tgraph.add(\"size\", size);\n\n\tfunction effective(entry: CollectionEntry<T>, now: number): number {\n\t\tconst ageSeconds = (now - entry.lastAccessNs) / 1_000_000_000;\n\t\treturn decay(entry.baseScore, ageSeconds, decayRate, minScore);\n\t}\n\n\tfunction evictIfNeeded(next: Map<string, CollectionEntry<T>>): void {\n\t\tif (maxSize === undefined) return;\n\t\twhile (next.size > maxSize) {\n\t\t\tconst now = monotonicNs();\n\t\t\tlet victim: CollectionEntry<T> | undefined;\n\t\t\tlet victimScore = Number.POSITIVE_INFINITY;\n\t\t\tfor (const entry of next.values()) {\n\t\t\t\tconst score = effective(entry, now);\n\t\t\t\tif (score < victimScore) {\n\t\t\t\t\tvictim = entry;\n\t\t\t\t\tvictimScore = score;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (score === victimScore && victim) {\n\t\t\t\t\tconst lhs = policy === \"lru\" ? entry.lastAccessNs : entry.createdAtNs;\n\t\t\t\t\tconst rhs = policy === \"lru\" ? victim.lastAccessNs : victim.createdAtNs;\n\t\t\t\t\tif (lhs < rhs) victim = entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!victim) break;\n\t\t\tnext.delete(victim.id);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, CollectionEntry<T>>): void {\n\t\titems.down([[DATA, next]]);\n\t}\n\n\tconst out = Object.assign(graph, {\n\t\tupsert(id: string, value: T, upsertOpts?: { score?: number }) {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst current = readMap(items);\n\t\t\tconst prev = current.get(id);\n\t\t\tconst baseScore = upsertOpts?.score ?? scoreFn(value);\n\t\t\tconst next = copyMap(current);\n\t\t\tnext.set(id, {\n\t\t\t\tid,\n\t\t\t\tvalue,\n\t\t\t\tbaseScore,\n\t\t\t\tcreatedAtNs: prev?.createdAtNs ?? now,\n\t\t\t\tlastAccessNs: now,\n\t\t\t});\n\t\t\tevictIfNeeded(next);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id: string) {\n\t\t\tconst next = copyMap(readMap(items));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(items).size === 0) return;\n\t\t\tcommit(new Map());\n\t\t},\n\t\tgetItem(id: string): CollectionEntry<T> | undefined {\n\t\t\tconst current = readMap(items);\n\t\t\tconst found = current.get(id);\n\t\t\tif (!found) return undefined;\n\t\t\tif (policy === \"lru\") {\n\t\t\t\tconst next = copyMap(current);\n\t\t\t\tnext.set(id, { ...found, lastAccessNs: monotonicNs() });\n\t\t\t\tcommit(next);\n\t\t\t}\n\t\t\treturn found;\n\t\t},\n\t}) as CollectionGraph<T>;\n\treturn out;\n}\n\nexport function vectorIndex<TMeta>(opts: VectorIndexOptions<TMeta> = {}): VectorIndexBundle<TMeta> {\n\tconst backend = opts.backend ?? \"flat\";\n\tconst dimension = opts.dimension;\n\tlet hnsw: HnswAdapter<TMeta> | undefined;\n\tif (backend === \"hnsw\") {\n\t\thnsw = opts.hnswFactory?.();\n\t\tif (!hnsw) {\n\t\t\tthrow new Error(\n\t\t\t\t'vectorIndex backend \"hnsw\" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.',\n\t\t\t);\n\t\t}\n\t}\n\n\tconst entries = state<ReadonlyMap<string, VectorRecord<TMeta>>>(new Map(), {\n\t\tdescribeKind: \"state\",\n\t\tname: \"vector-index\",\n\t});\n\n\tfunction assertDimension(vector: readonly number[]): void {\n\t\tif (dimension !== undefined && vector.length !== dimension) {\n\t\t\tthrow new RangeError(\n\t\t\t\t`vector dimension mismatch: expected ${dimension}, got ${vector.length}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, VectorRecord<TMeta>>): void {\n\t\tentries.down([[DATA, next]]);\n\t}\n\n\treturn {\n\t\tbackend,\n\t\tentries,\n\t\tupsert(id, vector, meta) {\n\t\t\tassertDimension(vector);\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tnext.set(id, { id, vector: [...vector], meta });\n\t\t\tif (backend === \"hnsw\") hnsw!.upsert(id, vector, meta);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id) {\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tif (backend === \"hnsw\") hnsw!.remove(id);\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(entries).size === 0) return;\n\t\t\tif (backend === \"hnsw\") hnsw!.clear();\n\t\t\tcommit(new Map());\n\t\t},\n\t\tsearch(query, k = 5) {\n\t\t\tassertDimension(query);\n\t\t\tif (k <= 0) return [];\n\t\t\tif (backend === \"hnsw\") return hnsw!.search(query, k);\n\t\t\tconst ranked = [...readMap(entries).values()]\n\t\t\t\t.map((row) => ({\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tscore: cosineSimilarity(query, row.vector),\n\t\t\t\t\tmeta: row.meta,\n\t\t\t\t}))\n\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t.slice(0, k);\n\t\t\treturn ranked;\n\t\t},\n\t};\n}\n\nexport function knowledgeGraph<TEntity, TRelation extends string = string>(\n\tname: string,\n): KnowledgeGraphGraph<TEntity, TRelation> {\n\tconst graph = new Graph(name);\n\tconst entities = state<ReadonlyMap<string, TEntity>>(new Map(), {\n\t\tname: \"entities\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst edges = state<ReadonlyArray<KnowledgeEdge<TRelation>>>([], {\n\t\tname: \"edges\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst adjacency = derived(\n\t\t[edges],\n\t\t([rows]) => {\n\t\t\tconst typed = (rows ?? []) as ReadonlyArray<KnowledgeEdge<TRelation>>;\n\t\t\tconst out = new Map<string, ReadonlyArray<KnowledgeEdge<TRelation>>>();\n\t\t\tfor (const edge of typed) {\n\t\t\t\tconst prev = out.get(edge.from) ?? [];\n\t\t\t\tout.set(edge.from, Object.freeze([...prev, edge]));\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t\t{ name: \"adjacency\", describeKind: \"derived\", initial: new Map() },\n\t);\n\tvoid adjacency.subscribe(() => undefined);\n\n\tgraph.add(\"entities\", entities);\n\tgraph.add(\"edges\", edges);\n\tgraph.add(\"adjacency\", adjacency);\n\n\tfunction commitEntities(next: Map<string, TEntity>): void {\n\t\tentities.down([[DATA, next]]);\n\t}\n\n\tfunction commitEdges(next: ReadonlyArray<KnowledgeEdge<TRelation>>): void {\n\t\tedges.down([[DATA, next]]);\n\t}\n\n\tconst out = Object.assign(graph, {\n\t\tupsertEntity(id: string, value: TEntity) {\n\t\t\tconst next = copyMap(readMap(entities));\n\t\t\tnext.set(id, value);\n\t\t\tcommitEntities(next);\n\t\t},\n\t\tremoveEntity(id: string) {\n\t\t\tconst nextEntities = copyMap(readMap(entities));\n\t\t\tconst existed = nextEntities.delete(id);\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst nextEdges = currentEdges.filter((edge) => edge.from !== id && edge.to !== id);\n\t\t\tif (!existed && nextEdges.length === currentEdges.length) return;\n\t\t\tcommitEntities(nextEntities);\n\t\t\tcommitEdges(nextEdges);\n\t\t},\n\t\tlink(from: string, to: string, relation: TRelation, weight = 1) {\n\t\t\tconst key = `${from}\\u0000${to}\\u0000${relation}`;\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst existing = new Set(\n\t\t\t\tcurrentEdges.map((edge) => `${edge.from}\\u0000${edge.to}\\u0000${edge.relation}`),\n\t\t\t);\n\t\t\tconst next = [...currentEdges];\n\t\t\tif (existing.has(key)) {\n\t\t\t\tfor (let i = 0; i < next.length; i += 1) {\n\t\t\t\t\tconst edge = next[i]!;\n\t\t\t\t\tif (edge.from === from && edge.to === to && edge.relation === relation) {\n\t\t\t\t\t\tnext[i] = { ...edge, weight };\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnext.push({ from, to, relation, weight });\n\t\t\t}\n\t\t\tcommitEdges(next);\n\t\t},\n\t\tunlink(from: string, to: string, relation?: TRelation) {\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst next = currentEdges.filter((edge) =>\n\t\t\t\trelation === undefined\n\t\t\t\t\t? !(edge.from === from && edge.to === to)\n\t\t\t\t\t: !(edge.from === from && edge.to === to && edge.relation === relation),\n\t\t\t);\n\t\t\tif (next.length === currentEdges.length) return;\n\t\t\tcommitEdges(next);\n\t\t},\n\t\trelated(id: string, relation?: TRelation): ReadonlyArray<KnowledgeEdge<TRelation>> {\n\t\t\treturn readArray(edges).filter(\n\t\t\t\t(edge) =>\n\t\t\t\t\t(edge.from === id || edge.to === id) &&\n\t\t\t\t\t(relation === undefined || edge.relation === relation),\n\t\t\t);\n\t\t},\n\t}) as KnowledgeGraphGraph<TEntity, TRelation>;\n\treturn out;\n}\n","/**\n * Messaging patterns (roadmap §4.2).\n *\n * Pulsar-inspired messaging features modeled as graph factories:\n * - `topic()` for append-only topic streams\n * - `subscription()` for cursor-based consumers\n * - `jobQueue()` for queue claim/ack flow\n */\n\nimport { batch, COMPLETE, DATA, derived, type Node, node, state } from \"../core/index.js\";\nimport { reactiveList } from \"../extra/reactive-list.js\";\nimport { reactiveLog } from \"../extra/reactive-log.js\";\nimport { reactiveMap } from \"../extra/reactive-map.js\";\nimport { Graph, type GraphOptions } from \"../graph/index.js\";\n\nconst DEFAULT_MAX_PER_PUMP = 2_147_483_647;\n\nfunction requireNonNegativeInt(value: number, label: string): number {\n\tif (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n\t\tthrow new Error(`${label} must be a non-negative integer`);\n\t}\n\treturn value;\n}\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction messagingMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"messaging\", kind, extra);\n}\n\nexport type TopicOptions = {\n\tgraph?: GraphOptions;\n\tretainedLimit?: number;\n};\n\nexport class TopicGraph<T> extends Graph {\n\tprivate readonly _log;\n\treadonly events: Node<readonly T[]>;\n\t/**\n\t * Most recently published value, or `null` when the topic has no entries\n\t * yet. Spec §5.12 reserves `undefined` as the protocol-internal \"never\n\t * sent DATA\" sentinel — `null` is the idiomatic \"empty / no value\" signal\n\t * for domain nodes. F7.\n\t *\n\t * **Caveat when `T` itself includes `null`** (e.g., `topic<number | null>`):\n\t * `latest === null` is ambiguous — it could mean \"no publish yet\" OR \"a\n\t * `null` value was published\". Use {@link hasLatest} to disambiguate, or\n\t * observe {@link events} directly and track length yourself.\n\t */\n\treadonly latest: Node<T | null>;\n\t/**\n\t * Reactive `true` once the topic has at least one published entry.\n\t * Disambiguates \"`null` never published\" from \"`null` was published\" when\n\t * `T` includes `null`.\n\t */\n\treadonly hasLatest: Node<boolean>;\n\n\tconstructor(name: string, opts: TopicOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._log = reactiveLog<T>([], { name: \"events\", maxSize: opts.retainedLimit });\n\t\tthis.events = this._log.entries;\n\t\tthis.add(\"events\", this.events);\n\t\tthis.latest = derived<T | null>(\n\t\t\t[this.events],\n\t\t\t([snapshot]) => {\n\t\t\t\tconst entries = snapshot as readonly T[];\n\t\t\t\treturn entries.length === 0 ? null : (entries[entries.length - 1] as T);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"latest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"topic_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"latest\", this.latest);\n\t\tthis.addDisposer(keepalive(this.latest));\n\n\t\tthis.hasLatest = derived<boolean>(\n\t\t\t[this.events],\n\t\t\t([snapshot]) => (snapshot as readonly T[]).length > 0,\n\t\t\t{\n\t\t\t\tname: \"hasLatest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"topic_has_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"hasLatest\", this.hasLatest);\n\t\tthis.addDisposer(keepalive(this.hasLatest));\n\n\t\t// D1(a): on teardown, propagate COMPLETE on `events` so downstream\n\t\t// derived chains (including any externally-held SubscriptionGraph\n\t\t// sources) see the termination via their `terminalDeps` and can stop\n\t\t// serving stale caches. Tier-3 terminal per spec §2.2.\n\t\tthis.addDisposer(() => {\n\t\t\tthis.events.down([[COMPLETE]]);\n\t\t});\n\t\t// P9: release any memoized tail/slice view keepalives held by the log.\n\t\t// TopicGraph itself doesn't call log.tail/slice, but plugins may have\n\t\t// attached views via `_log` — defensive.\n\t\tthis.addDisposer(() => this._log.disposeAllViews());\n\t}\n\n\tpublish(value: T): void {\n\t\tthis._log.append(value);\n\t}\n\n\tretained(): readonly T[] {\n\t\treturn this.events.cache as readonly T[];\n\t}\n}\n\nexport type SubscriptionOptions = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n};\n\nexport class SubscriptionGraph<T> extends Graph {\n\treadonly source: Node<readonly T[]>;\n\treadonly cursor: Node<number>;\n\treadonly available: Node<readonly T[]>;\n\t/**\n\t * Reference to the upstream topic graph. Intentionally NOT mounted\n\t * under this subscription: a subscription is a VIEW over an\n\t * externally-owned topic. Double-mounting (e.g. hub-owned topic +\n\t * sub-mount here) would make either-side teardown leave the other\n\t * holding a dead reference. Node-level `derived([topicEvents], …)`\n\t * still wires the data dependency across graph boundaries. D1(e).\n\t */\n\treadonly topic: TopicGraph<T>;\n\n\tconstructor(name: string, topicGraph: TopicGraph<T>, opts: SubscriptionOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst initialCursor = requireNonNegativeInt(opts.cursor ?? 0, \"subscription cursor\");\n\t\tthis.topic = topicGraph;\n\t\tconst topicEvents = topicGraph.events;\n\t\tthis.source = derived([topicEvents], ([snapshot]) => snapshot as readonly T[], {\n\t\t\tname: \"source\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: messagingMeta(\"subscription_source\"),\n\t\t\tinitial: topicEvents.cache as readonly T[],\n\t\t});\n\t\tthis.add(\"source\", this.source);\n\t\tthis.cursor = state(initialCursor, {\n\t\t\tname: \"cursor\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"subscription_cursor\"),\n\t\t});\n\t\tthis.add(\"cursor\", this.cursor);\n\t\tthis.available = derived(\n\t\t\t[this.source, this.cursor],\n\t\t\t([sourceSnapshot, cursor]) => {\n\t\t\t\tconst entries = sourceSnapshot as readonly T[];\n\t\t\t\tconst start = Math.max(0, Math.trunc((cursor as number) ?? 0));\n\t\t\t\treturn entries.slice(start);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"available\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"subscription_available\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tthis.add(\"available\", this.available);\n\t\t// No `connect(\"topic::events\", \"source\")` — topic is not mounted here.\n\t\t// The node-level dep `derived([topicEvents], …)` above is the live wire.\n\t\tthis.addDisposer(keepalive(this.source));\n\t\tthis.addDisposer(keepalive(this.available));\n\t}\n\n\tack(count?: number): number {\n\t\tconst available = this.available.cache as readonly T[];\n\t\tconst requested =\n\t\t\tcount === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(count, \"subscription ack count\");\n\t\tconst step = Math.min(requested, available.length);\n\t\tif (step <= 0) return this.cursor.cache as number;\n\t\tconst next = (this.cursor.cache as number) + step;\n\t\t// F8: use emit() so the pipeline auto-prefixes DIRTY, runs equals\n\t\t// substitution, and produces a proper two-phase wave (the raw\n\t\t// `down([[DATA, next]])` path bypassed those contracts).\n\t\tthis.cursor.emit(next);\n\t\treturn next;\n\t}\n\n\tpull(limit?: number, opts: { ack?: boolean } = {}): readonly T[] {\n\t\tconst available = this.available.cache as readonly T[];\n\t\tconst max =\n\t\t\tlimit === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(limit, \"subscription pull limit\");\n\t\tconst out = available.slice(0, max);\n\t\tif (opts.ack && out.length > 0) this.ack(out.length);\n\t\treturn out;\n\t}\n}\n\nexport type JobState = \"queued\" | \"inflight\";\n\nexport type JobEnvelope<T> = {\n\tid: string;\n\tpayload: T;\n\tattempts: number;\n\tmetadata: Readonly<Record<string, unknown>>;\n\tstate: JobState;\n};\n\nexport type JobQueueOptions = {\n\tgraph?: GraphOptions;\n};\n\nexport class JobQueueGraph<T> extends Graph {\n\tprivate readonly _pending;\n\tprivate readonly _jobs;\n\tprivate _seq = 0;\n\treadonly pending: Node<readonly string[]>;\n\treadonly jobs: Node<ReadonlyMap<string, JobEnvelope<T>>>;\n\treadonly depth: Node<number>;\n\n\tconstructor(name: string, opts: JobQueueOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._pending = reactiveList<string>([], { name: \"pending\" });\n\t\tthis._jobs = reactiveMap<string, JobEnvelope<T>>({ name: \"jobs\" });\n\t\tthis.pending = this._pending.items;\n\t\tthis.jobs = this._jobs.entries;\n\t\tthis.add(\"pending\", this.pending);\n\t\tthis.add(\"jobs\", this.jobs);\n\t\tthis.depth = derived([this.pending], ([snapshot]) => (snapshot as readonly string[]).length, {\n\t\t\tname: \"depth\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: messagingMeta(\"queue_depth\"),\n\t\t\tinitial: 0,\n\t\t});\n\t\tthis.add(\"depth\", this.depth);\n\t\tthis.addDisposer(keepalive(this.depth));\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\tconst id = opts.id ?? `${this.name}-${++this._seq}`;\n\t\tif (this._jobs.get(id) !== undefined) {\n\t\t\tthrow new Error(`jobQueue(\"${this.name}\"): duplicate job id \"${id}\"`);\n\t\t}\n\t\tconst job: JobEnvelope<T> = {\n\t\t\tid,\n\t\t\tpayload,\n\t\t\tattempts: 0,\n\t\t\tmetadata: Object.freeze({ ...(opts.metadata ?? {}) }),\n\t\t\tstate: \"queued\",\n\t\t};\n\t\tthis._jobs.set(id, job);\n\t\tthis._pending.append(id);\n\t\treturn id;\n\t}\n\n\tclaim(limit = 1): readonly JobEnvelope<T>[] {\n\t\tconst max = requireNonNegativeInt(limit, \"job queue claim limit\");\n\t\tif (max === 0) return [];\n\t\tconst out: JobEnvelope<T>[] = [];\n\t\twhile (out.length < max) {\n\t\t\tconst ids = this.pending.cache as readonly string[];\n\t\t\tif (ids.length === 0) break;\n\t\t\tconst id = this._pending.pop(0);\n\t\t\tconst job = this._jobs.get(id);\n\t\t\tif (!job || job.state !== \"queued\") continue;\n\t\t\tconst inflight: JobEnvelope<T> = {\n\t\t\t\t...job,\n\t\t\t\tstate: \"inflight\",\n\t\t\t\tattempts: job.attempts + 1,\n\t\t\t};\n\t\t\tthis._jobs.set(id, inflight);\n\t\t\tout.push(inflight);\n\t\t}\n\t\treturn out;\n\t}\n\n\tack(id: string): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n\n\tnack(id: string, opts: { requeue?: boolean } = {}): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tif (opts.requeue ?? true) {\n\t\t\tthis._jobs.set(id, { ...job, state: \"queued\" });\n\t\t\tthis._pending.append(id);\n\t\t\treturn true;\n\t\t}\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n}\n\nexport type JobFlowOptions = {\n\tgraph?: GraphOptions;\n\tstages?: readonly string[];\n\tmaxPerPump?: number;\n};\n\nexport class JobFlowGraph<T> extends Graph {\n\tprivate readonly _stageNames: readonly string[];\n\tprivate readonly _queues = new Map<string, JobQueueGraph<T>>();\n\tprivate readonly _completed;\n\treadonly completed: Node<readonly JobEnvelope<T>[]>;\n\treadonly completedCount: Node<number>;\n\n\tconstructor(name: string, opts: JobFlowOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst stages = (opts.stages ?? [\"incoming\", \"processing\", \"done\"]).map((v) => v.trim());\n\t\tif (stages.length < 2) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): requires at least 2 stages`);\n\t\t}\n\t\tconst unique = new Set(stages);\n\t\tif (unique.size !== stages.length) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): stage names must be unique`);\n\t\t}\n\t\tthis._stageNames = Object.freeze([...stages]);\n\t\tfor (const stage of this._stageNames) {\n\t\t\tconst q = jobQueue<T>(`${name}-${stage}`);\n\t\t\tthis._queues.set(stage, q);\n\t\t\tthis.mount(stage, q);\n\t\t}\n\t\tthis._completed = reactiveLog<JobEnvelope<T>>([], { name: \"completed\" });\n\t\tthis.completed = this._completed.entries;\n\t\tthis.add(\"completed\", this.completed);\n\t\tthis.completedCount = derived(\n\t\t\t[this.completed],\n\t\t\t([snapshot]) => (snapshot as readonly JobEnvelope<T>[]).length,\n\t\t\t{\n\t\t\t\tname: \"completedCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"job_flow_completed_count\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"completedCount\", this.completedCount);\n\t\tthis.addDisposer(keepalive(this.completedCount));\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"job flow maxPerPump\"),\n\t\t);\n\t\tfor (let i = 0; i < this._stageNames.length; i += 1) {\n\t\t\tconst stage = this._stageNames[i] as string;\n\t\t\tconst current = this.queue(stage);\n\t\t\tconst next =\n\t\t\t\ti + 1 < this._stageNames.length ? this.queue(this._stageNames[i + 1] as string) : null;\n\t\t\tconst pump = node<unknown>(\n\t\t\t\t[current.pending],\n\t\t\t\t() => {\n\t\t\t\t\tlet moved = 0;\n\t\t\t\t\twhile (moved < maxPerPump) {\n\t\t\t\t\t\tconst claim = current.claim(1);\n\t\t\t\t\t\tif (claim.length === 0) break;\n\t\t\t\t\t\tconst job = claim[0] as JobEnvelope<T>;\n\t\t\t\t\t\tif (!job) break;\n\t\t\t\t\t\tif (next) {\n\t\t\t\t\t\t\tnext.enqueue(job.payload, {\n\t\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\t\t...job.metadata,\n\t\t\t\t\t\t\t\t\tjob_flow_from: stage,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis._completed.append(job);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrent.ack(job.id);\n\t\t\t\t\t\tmoved += 1;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `pump_${stage}`,\n\t\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\t\tmeta: messagingMeta(\"job_flow_pump\"),\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.add(`pump_${stage}`, pump);\n\t\t\tthis.addDisposer(keepalive(pump));\n\t\t}\n\t}\n\n\tstages(): readonly string[] {\n\t\treturn this._stageNames;\n\t}\n\n\tqueue(stage: string): JobQueueGraph<T> {\n\t\tconst q = this._queues.get(stage);\n\t\tif (!q) throw new Error(`jobFlow(\"${this.name}\"): unknown stage \"${stage}\"`);\n\t\treturn q;\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\treturn this.queue(this._stageNames[0] as string).enqueue(payload, opts);\n\t}\n\n\tretainedCompleted(): readonly JobEnvelope<T>[] {\n\t\treturn this.completed.cache as readonly JobEnvelope<T>[];\n\t}\n}\n\nexport type TopicBridgeOptions<TIn, TOut> = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n\tmaxPerPump?: number;\n\tmap?: (value: TIn) => TOut | undefined;\n};\n\nexport class TopicBridgeGraph<TIn, TOut = TIn> extends Graph {\n\tprivate readonly _sourceSub;\n\tprivate readonly _target;\n\treadonly bridgedCount: Node<number>;\n\n\tconstructor(\n\t\tname: string,\n\t\tsourceTopic: TopicGraph<TIn>,\n\t\ttargetTopic: TopicGraph<TOut>,\n\t\topts: TopicBridgeOptions<TIn, TOut> = {},\n\t) {\n\t\tsuper(name, opts.graph);\n\t\tthis._sourceSub = subscription<TIn>(`${name}-subscription`, sourceTopic, {\n\t\t\tcursor: opts.cursor,\n\t\t});\n\t\tthis._target = targetTopic;\n\t\tthis.mount(\"subscription\", this._sourceSub);\n\t\tthis.bridgedCount = state(0, {\n\t\t\tname: \"bridgedCount\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"topic_bridge_count\"),\n\t\t});\n\t\tthis.add(\"bridgedCount\", this.bridgedCount);\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"topic bridge maxPerPump\"),\n\t\t);\n\t\tconst mapValue = opts.map ?? ((value: TIn) => value as unknown as TOut);\n\t\tconst pump = node<unknown>(\n\t\t\t[this._sourceSub.available],\n\t\t\t() => {\n\t\t\t\tconst available = this._sourceSub.pull(maxPerPump, { ack: true });\n\t\t\t\tif (available.length === 0) return;\n\t\t\t\tlet bridged = 0;\n\t\t\t\tfor (const value of available) {\n\t\t\t\t\tconst mapped = mapValue(value as TIn);\n\t\t\t\t\tif (mapped === undefined) continue;\n\t\t\t\t\tthis._target.publish(mapped);\n\t\t\t\t\tbridged += 1;\n\t\t\t\t}\n\t\t\t\tif (bridged > 0) {\n\t\t\t\t\tconst current = this.bridgedCount.cache as number;\n\t\t\t\t\tthis.bridgedCount.down([[DATA, current + bridged]]);\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"pump\",\n\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\tmeta: messagingMeta(\"topic_bridge_pump\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"pump\", pump);\n\t\tthis.addDisposer(keepalive(pump));\n\t}\n}\n\n// ── MessagingHubGraph ─────────────────────────────────────────────────────\n\nexport type MessagingHubOptions = {\n\tgraph?: GraphOptions;\n\t/**\n\t * Default `TopicOptions` applied to every topic created via `topic(name)`\n\t * without explicit options. Per-call opts override. Default: `{}`\n\t * (unbounded retention per topic unless `retainedLimit` is set per call).\n\t */\n\tdefaultTopicOptions?: TopicOptions;\n};\n\n/**\n * Lazy Pulsar-inspired topic registry. Manages a named set of {@link TopicGraph}\n * instances with retention + cursor semantics. Topics are created on first\n * access; `removeTopic(name)` unmounts and tears down via {@link Graph.remove}.\n *\n * **Relationship to `pubsub()` in `src/extra/pubsub.ts`:** `pubsub` is a\n * lightweight last-value state hub (no retention, no cursors). `MessagingHubGraph`\n * is the full messaging hub — retained message logs, cursor-based subscriptions,\n * and pattern-layer lifecycle management.\n *\n * @category patterns\n */\nexport class MessagingHubGraph extends Graph {\n\tprivate readonly _topics = new Map<string, TopicGraph<unknown>>();\n\tprivate _version = 0;\n\tprivate readonly _defaultTopicOptions: TopicOptions;\n\n\tconstructor(name: string, opts: MessagingHubOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\t// P8: shallow-copy caller-provided defaults so post-construction\n\t\t// mutations by the caller don't leak into every future `topic()` call.\n\t\tthis._defaultTopicOptions = { ...(opts.defaultTopicOptions ?? {}) };\n\t}\n\n\t/** Monotonic counter advancing on topic create/remove. */\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\t/** Number of topics currently in the hub. */\n\tget size(): number {\n\t\treturn this._topics.size;\n\t}\n\n\t/** Checks topic existence without creating. */\n\thas(name: string): boolean {\n\t\treturn this._topics.has(name);\n\t}\n\n\t/** Iterator over topic names. */\n\ttopicNames(): IterableIterator<string> {\n\t\treturn this._topics.keys();\n\t}\n\n\t/**\n\t * Returns the {@link TopicGraph} for `name`, creating lazily on first call.\n\t * Subsequent calls with the same name return the same instance (options on\n\t * repeat calls are ignored — the topic is already configured).\n\t */\n\ttopic<T = unknown>(name: string, opts?: TopicOptions): TopicGraph<T> {\n\t\tlet t = this._topics.get(name) as TopicGraph<T> | undefined;\n\t\tif (t === undefined) {\n\t\t\tconst effective: TopicOptions = { ...this._defaultTopicOptions, ...(opts ?? {}) };\n\t\t\tt = new TopicGraph<T>(name, effective);\n\t\t\tthis._topics.set(name, t as TopicGraph<unknown>);\n\t\t\tthis.mount(name, t);\n\t\t\tthis._version += 1;\n\t\t}\n\t\treturn t;\n\t}\n\n\t/**\n\t * Publishes a value to the topic, lazily creating it on first publish.\n\t *\n\t * **Late-subscriber caveat:** the topic is created lazily, so subscribers\n\t * that attach AFTER a publish only see the retained window (governed by\n\t * `retainedLimit` on `TopicOptions` / `defaultTopicOptions`). If\n\t * `retainedLimit === 0` is set explicitly, early publishes are\n\t * effectively dropped — prefer an unset `retainedLimit` (unbounded\n\t * retention) or subscribe before publishing when late-subscribers matter.\n\t */\n\tpublish<T = unknown>(name: string, value: T): void {\n\t\tthis.topic<T>(name).publish(value);\n\t}\n\n\t/**\n\t * Bulk publish — issues all publishes inside one outer batch. New topics\n\t * are created on demand. No-op if `entries` yields nothing.\n\t *\n\t * **Iterable consumption (F6):** `entries` is consumed once (single-pass)\n\t * INSIDE the batch frame. If the iterator throws mid-way, the batch is\n\t * discarded and NO publishes are visible to subscribers (all-or-nothing).\n\t * Pass an array or `Set` for multi-shot callers.\n\t */\n\tpublishMany(entries: Iterable<[string, unknown]>): void {\n\t\t// P2: iterate inside batch — no `[...entries]` materialization so large\n\t\t// / infinite iterables don't OOM, and iterator throws are contained.\n\t\tbatch(() => {\n\t\t\tfor (const [name, value] of entries) {\n\t\t\t\tthis.topic(name).publish(value);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Creates a {@link SubscriptionGraph} over a named topic. The topic is\n\t * lazily created if missing. Subscription lifecycle is owned by the caller —\n\t * the hub does NOT mount the subscription.\n\t *\n\t * @param subName - Local name for the subscription graph.\n\t * @param topicName - Hub topic to subscribe to.\n\t * @param opts - `SubscriptionOptions` (initial cursor, etc.).\n\t */\n\tsubscribe<T = unknown>(\n\t\tsubName: string,\n\t\ttopicName: string,\n\t\topts?: SubscriptionOptions,\n\t): SubscriptionGraph<T> {\n\t\tconst t = this.topic<T>(topicName);\n\t\treturn new SubscriptionGraph<T>(subName, t, opts);\n\t}\n\n\t/**\n\t * Unmounts and tears down the topic's graph. Returns `true` if the topic\n\t * existed. Subscribers receive `TEARDOWN` via {@link Graph.remove}.\n\t */\n\tremoveTopic(name: string): boolean {\n\t\tif (!this._topics.has(name)) return false;\n\t\t// P1 / P3: Graph.remove first — if it throws, `_topics` must NOT still\n\t\t// hold the broken half-disposed topic (otherwise the next\n\t\t// `hub.topic(name)` returns the corrupted reference). Wrap in\n\t\t// try/finally so `_topics` / `_version` converge to a consistent state\n\t\t// regardless of whether `remove` throws. Mount-orphan safety is\n\t\t// preserved by removing before deleting.\n\t\ttry {\n\t\t\tthis.remove(name); // unmounts, drops edges, tears down\n\t\t} finally {\n\t\t\tthis._topics.delete(name);\n\t\t\tthis._version += 1;\n\t\t}\n\t\treturn true;\n\t}\n}\n\n/**\n * Creates a Pulsar-inspired topic graph (append-only retained stream + latest value).\n */\nexport function topic<T>(name: string, opts?: TopicOptions): TopicGraph<T> {\n\treturn new TopicGraph<T>(name, opts);\n}\n\n/**\n * Creates a lazy Pulsar-inspired messaging hub. Topics are created on first access\n * via `hub.topic(name)`; `hub.publish(name, value)` shortcuts through the registry.\n *\n * @example\n * ```ts\n * import { messagingHub } from \"@graphrefly/graphrefly-ts\";\n *\n * const hub = messagingHub(\"main\", { defaultTopicOptions: { retainedLimit: 256 } });\n * hub.publish(\"orders\", { id: 1 });\n * hub.publishMany([[\"shipments\", { id: 1 }], [\"orders\", { id: 2 }]]);\n * const sub = hub.subscribe(\"orders-worker\", \"orders\", { cursor: 0 });\n * ```\n */\nexport function messagingHub(name: string, opts?: MessagingHubOptions): MessagingHubGraph {\n\treturn new MessagingHubGraph(name, opts);\n}\n\n/**\n * Creates a cursor-based subscription graph over a topic.\n */\nexport function subscription<T>(\n\tname: string,\n\ttopicGraph: TopicGraph<T>,\n\topts?: SubscriptionOptions,\n): SubscriptionGraph<T> {\n\treturn new SubscriptionGraph<T>(name, topicGraph, opts);\n}\n\n/**\n * Creates a Pulsar-inspired job queue graph with claim/ack/nack workflow.\n */\nexport function jobQueue<T>(name: string, opts?: JobQueueOptions): JobQueueGraph<T> {\n\treturn new JobQueueGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous multi-stage queue chain graph.\n */\nexport function jobFlow<T>(name: string, opts?: JobFlowOptions): JobFlowGraph<T> {\n\treturn new JobFlowGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous cursor-based topic relay graph.\n */\nexport function topicBridge<TIn, TOut = TIn>(\n\tname: string,\n\tsourceTopic: TopicGraph<TIn>,\n\ttargetTopic: TopicGraph<TOut>,\n\topts?: TopicBridgeOptions<TIn, TOut>,\n): TopicBridgeGraph<TIn, TOut> {\n\treturn new TopicBridgeGraph<TIn, TOut>(name, sourceTopic, targetTopic, opts);\n}\n","/**\n * Orchestration patterns (roadmap §4.1).\n *\n * Domain-layer helpers that build workflow shapes on top of core + extra primitives.\n * Exported under the `patterns.orchestration` namespace to avoid collisions with\n * Phase 2 operator names (for example `gate`, `forEach`).\n */\n\nimport { batch } from \"../core/batch.js\";\nimport type { NodeActions } from \"../core/config.js\";\nimport { COMPLETE, DATA, ERROR, type Messages, RESOLVED } from \"../core/messages.js\";\nimport { type Node, type NodeFn, type NodeOptions, node } from \"../core/node.js\";\nimport { type DerivedFn, derived, state } from \"../core/sugar.js\";\nimport { GRAPH_META_SEGMENT, Graph, type GraphOptions } from \"../graph/graph.js\";\n\nexport type StepRef = string | Node<unknown>;\n\ntype OrchestrationMeta = {\n\torchestration?: true;\n\torchestration_type?: string;\n};\n\nexport type OrchestrationStepOptions = Omit<\n\tNodeOptions<unknown>,\n\t\"describeKind\" | \"name\" | \"meta\"\n> & {\n\tdeps?: ReadonlyArray<StepRef>;\n\tmeta?: Record<string, unknown> & OrchestrationMeta;\n};\n\nexport type BranchResult<T> = {\n\tbranch: \"then\" | \"else\";\n\tvalue: T;\n};\n\nexport type SensorControls<T> = {\n\tnode: Node<T>;\n\tpush(value: T): void;\n\terror(err: unknown): void;\n\tcomplete(): void;\n};\n\nexport type LoopOptions = Omit<OrchestrationStepOptions, \"deps\"> & {\n\titerations?: number | StepRef;\n};\n\nexport type WaitOptions = Omit<OrchestrationStepOptions, \"deps\">;\n\nexport type SubPipelineBuilder = (sub: Graph) => void;\n\nfunction resolveDep(graph: Graph, dep: StepRef): { node: Node<unknown>; path?: string } {\n\tif (typeof dep === \"string\") {\n\t\treturn { node: graph.resolve(dep), path: dep };\n\t}\n\tconst path = findRegisteredNodePath(graph, dep);\n\tif (!path) {\n\t\tthrow new Error(\n\t\t\t\"orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first\",\n\t\t);\n\t}\n\treturn { node: dep, path };\n}\n\nfunction findRegisteredNodePath(graph: Graph, target: Node<unknown>): string | undefined {\n\tconst described = graph.describe();\n\tconst metaSegment = `::${GRAPH_META_SEGMENT}::`;\n\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\ttry {\n\t\t\tif (graph.resolve(path) === target) return path;\n\t\t} catch {\n\t\t\t/* ignore stale path while scanning */\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction registerStep(\n\tgraph: Graph,\n\tname: string,\n\tstep: Node<unknown>,\n\tdepPaths: ReadonlyArray<string>,\n): void {\n\tgraph.add(name, step);\n\t// depPaths used to drive graph.connect() edge-registry calls; after\n\t// Unit 7 edges are derived from node _deps and this wiring is a no-op.\n\tvoid depPaths;\n}\n\nimport { domainMeta } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"orchestration\", kind, meta);\n}\n\nfunction coerceLoopIterations(raw: unknown): number {\n\tconst parseString = (value: string): number => {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed.length === 0) return 0;\n\t\treturn Number(trimmed);\n\t};\n\tlet parsed: number;\n\tif (typeof raw === \"string\") {\n\t\tparsed = parseString(raw);\n\t} else if (raw === null) {\n\t\tparsed = 0;\n\t} else {\n\t\tparsed = Number(raw);\n\t}\n\tif (!Number.isFinite(parsed)) return 1;\n\treturn Math.max(0, Math.trunc(parsed));\n}\n\n/**\n * Creates an orchestration graph container.\n */\nexport function pipeline(name: string, opts?: GraphOptions): Graph {\n\treturn new Graph(name, opts);\n}\n\n/**\n * Registers a workflow task node.\n */\nexport function task<T>(\n\tgraph: Graph,\n\tname: string,\n\trun: DerivedFn<T>,\n\topts?: OrchestrationStepOptions,\n): Node<T> {\n\tconst depRefs = opts?.deps ?? [];\n\tconst deps = depRefs.map((dep) => resolveDep(graph, dep));\n\tconst { deps: _deps, ...nodeOpts } = opts ?? {};\n\tconst wrapped: NodeFn = (batchData, actions, ctx) => {\n\t\tconst data = batchData.map((batch, i) =>\n\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t);\n\t\tactions.emit(run(data, ctx));\n\t\treturn undefined;\n\t};\n\tconst step = node<T>(\n\t\tdeps.map((d) => d.node),\n\t\twrapped,\n\t\t{\n\t\t\t...nodeOpts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"task\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\tdeps.flatMap((d) => (d.path ? [d.path] : [])),\n\t);\n\treturn step;\n}\n\n/**\n * Emits tagged branch outcomes (`then` / `else`) for each source value.\n */\nexport function branch<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tpredicate: (value: T) => boolean,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<BranchResult<T>> {\n\tconst src = resolveDep(graph, source);\n\tconst step = derived<BranchResult<T>>(\n\t\t[src.node],\n\t\t([value]) => ({\n\t\t\tbranch: predicate(value as T) ? \"then\" : \"else\",\n\t\t\tvalue: value as T,\n\t\t}),\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tmeta: baseMeta(\"branch\", opts?.meta),\n\t\t} as NodeOptions<BranchResult<T>>,\n\t);\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n\n/**\n * Forwards source values only while `control` is truthy.\n */\nexport function valve<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tcontrol: StepRef,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst ctrl = resolveDep(graph, control);\n\t// Raw node so we can emit RESOLVED (hold) instead of DATA(undefined) when closed.\n\tconst step = node<T>(\n\t\t[src.node, ctrl.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst batch0 = batchData[0];\n\t\t\tconst batch1 = batchData[1];\n\t\t\t// undefined = control never sent DATA (closed); falsy = explicitly closed.\n\t\t\tconst ctrlVal = batch1 != null && batch1.length > 0 ? batch1.at(-1) : ctx.prevData[1];\n\t\t\t// Control just opened and no new source data this wave: re-emit last source value.\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\tif (batch1 != null && batch1.length > 0 && ctrlVal && ctx.prevData[0] !== undefined) {\n\t\t\t\t\tactions.emit(ctx.prevData[0] as T);\n\t\t\t\t} else {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!ctrlVal) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) actions.emit(v);\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"valve\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, ctrl.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\nexport type ApprovalOptions = Omit<OrchestrationStepOptions, \"deps\"> & {\n\tisApproved?: (value: unknown) => boolean;\n};\n\n/**\n * Human/LLM approval gate over a source value.\n */\nexport function approval<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tapprover: StepRef,\n\topts?: ApprovalOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst ctrl = resolveDep(graph, approver);\n\tconst isApproved = opts?.isApproved ?? ((value: unknown) => Boolean(value));\n\t// Raw node so we can emit RESOLVED (hold) instead of DATA(undefined) when not approved.\n\tconst step = node<T>(\n\t\t[src.node, ctrl.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst batch0 = batchData[0];\n\t\t\tconst batch1 = batchData[1];\n\t\t\t// undefined = approver never sent DATA (not yet approved).\n\t\t\tconst ctrlVal = batch1 != null && batch1.length > 0 ? batch1.at(-1) : ctx.prevData[1];\n\t\t\tif (ctrlVal === undefined || !isApproved(ctrlVal)) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\t// Approval just granted and no new source data: re-emit last source value.\n\t\t\t\tif (batch1 != null && batch1.length > 0 && ctx.prevData[0] !== undefined) {\n\t\t\t\t\tactions.emit(ctx.prevData[0] as T);\n\t\t\t\t} else {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) actions.emit(v);\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"approval\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, ctrl.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\n// ---------------------------------------------------------------------------\n// gate — human-in-the-loop approval with pending queue\n// ---------------------------------------------------------------------------\n\nexport interface GateOptions {\n\t/** Maximum queue size. Oldest values are FIFO-dropped when exceeded. Default: Infinity. */\n\tmaxPending?: number;\n\t/** Start in open mode (auto-approve). Default: false. */\n\tstartOpen?: boolean;\n\tmeta?: Record<string, unknown>;\n}\n\n/** Control surface returned by {@link gate}. */\nexport interface GateController<T> {\n\t/** The output node registered in the graph (subscribe to receive approved values). */\n\tnode: Node<T>;\n\t/** Reactive queue of values waiting for approval. */\n\tpending: Node<T[]>;\n\t/** Derived count of pending items. */\n\tcount: Node<number>;\n\t/** Whether the gate is currently open (auto-approving). */\n\tisOpen: Node<boolean>;\n\t/** Approve and forward the next `count` pending values (default: 1). */\n\tapprove(count?: number): void;\n\t/** Reject (discard) the next `count` pending values (default: 1). */\n\treject(count?: number): void;\n\t/**\n\t * Transform and forward `count` pending values (default: 1).\n\t * `fn` receives `(value, index, pending)` — Array.map-style.\n\t */\n\tmodify(fn: (value: T, index: number, pending: readonly T[]) => T, count?: number): void;\n\t/** Flush all pending values and auto-approve future values. */\n\topen(): void;\n\t/** Re-enable manual gating (stop auto-approving). */\n\tclose(): void;\n}\n\n/**\n * Human-in-the-loop gate: queues incoming values from `source` and lets an external\n * controller {@link GateController.approve approve}, {@link GateController.reject reject},\n * or {@link GateController.modify modify} them before forwarding downstream.\n *\n * Observable surfaces (`pending`, `count`, `isOpen`) are reactive nodes registered in\n * the graph. The gate output node is also registered.\n */\nexport function gate<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\topts?: GateOptions,\n): GateController<T> {\n\tconst maxPending = opts?.maxPending ?? Infinity;\n\tif (maxPending < 1 && maxPending !== Infinity) {\n\t\tthrow new RangeError(\"gate: maxPending must be >= 1\");\n\t}\n\tconst startOpen = opts?.startOpen ?? false;\n\n\tconst src = resolveDep(graph, source);\n\n\t// Internal reactive state\n\tconst pendingNode = state<T[]>([], { name: \"pending\", equals: () => false });\n\tconst isOpenNode = state<boolean>(startOpen, { name: \"isOpen\" });\n\tconst countNode = derived<number>([pendingNode], ([arr]) => (arr as T[]).length, {\n\t\tname: \"count\",\n\t});\n\n\tlet queue: T[] = [];\n\tlet torn = false;\n\t// Capture `isOpenNode` DATA into a closure variable fed by its own subscribe\n\t// handler. The output producer consults `latestIsOpen` instead of reading\n\t// `isOpenNode.cache` from inside its callback — keeps the gate decision on\n\t// the protocol delivery path (P3 audit #11). Seeded with `startOpen` at\n\t// wiring time so the first item arriving before any open()/close() uses\n\t// the same value the state node was constructed with. Same template as\n\t// the `stratify` rule-capture pattern.\n\tlet latestIsOpen = startOpen;\n\tconst isOpenUnsub = isOpenNode.subscribe((msgs) => {\n\t\tfor (const m of msgs) {\n\t\t\tif (m[0] === DATA) latestIsOpen = m[1] as boolean;\n\t\t}\n\t});\n\n\tfunction syncPending(): void {\n\t\tpendingNode.down([[DATA, [...queue]]]);\n\t}\n\n\tfunction enqueue(value: T): void {\n\t\tqueue.push(value);\n\t\tif (queue.length > maxPending) queue.shift();\n\t\tsyncPending();\n\t}\n\n\tfunction dequeue(n: number): T[] {\n\t\tconst items = queue.splice(0, n);\n\t\tsyncPending();\n\t\treturn items;\n\t}\n\n\tfunction guardTorn(method: string): void {\n\t\tif (torn) throw new Error(`gate: ${method}() called after gate was torn down`);\n\t}\n\n\tconst output = node<T>(\n\t\t[src.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst terminal = ctx.terminalDeps[0];\n\t\t\tif (terminal !== undefined) {\n\t\t\t\ttorn = true;\n\t\t\t\tqueue = [];\n\t\t\t\tsyncPending();\n\t\t\t\tactions.down(terminal === true ? [[COMPLETE]] : [[ERROR, terminal]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst batch0 = batchData[0];\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) {\n\t\t\t\tif (latestIsOpen) {\n\t\t\t\t\tactions.emit(v);\n\t\t\t\t} else {\n\t\t\t\t\tenqueue(v);\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"gate\", opts?.meta),\n\t\t},\n\t);\n\n\tconst controller: GateController<T> = {\n\t\tnode: output,\n\t\tpending: pendingNode,\n\t\tcount: countNode,\n\t\tisOpen: isOpenNode,\n\t\tapprove(count = 1) {\n\t\t\tguardTorn(\"approve\");\n\t\t\tconst items = dequeue(count);\n\t\t\tfor (const item of items) {\n\t\t\t\tif (torn) break;\n\t\t\t\toutput.down([[DATA, item]]);\n\t\t\t}\n\t\t},\n\t\treject(count = 1) {\n\t\t\tguardTorn(\"reject\");\n\t\t\tdequeue(count);\n\t\t},\n\t\tmodify(fn, count = 1) {\n\t\t\tguardTorn(\"modify\");\n\t\t\tconst snapshot = [...queue] as readonly T[];\n\t\t\tconst items = dequeue(count);\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\tif (torn) break;\n\t\t\t\toutput.down([[DATA, fn(items[i], i, snapshot)]]);\n\t\t\t}\n\t\t},\n\t\topen() {\n\t\t\tguardTorn(\"open\");\n\t\t\t// Wrap the isOpen transition + queued flush in one batch so every\n\t\t\t// `output.down` is tier-3-deferred until after the `isOpenNode` dep\n\t\t\t// wave settles. Without this, queued DATAs could interleave with\n\t\t\t// the in-flight isOpen settlement wave under async runners — item\n\t\t\t// order relative to the open signal would be non-deterministic.\n\t\t\tbatch(() => {\n\t\t\t\tisOpenNode.down([[DATA, true]]);\n\t\t\t\tconst items = dequeue(queue.length);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tif (torn) break;\n\t\t\t\t\toutput.down([[DATA, item]]);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tguardTorn(\"close\");\n\t\t\tisOpenNode.down([[DATA, false]]);\n\t\t},\n\t};\n\n\t// Activate count so it stays reactive\n\tgraph.addDisposer(countNode.subscribe(() => undefined));\n\t// Tear down the isOpen capture when the owning graph disposes.\n\tgraph.addDisposer(isOpenUnsub);\n\n\t// Register output + internal state as a mounted subgraph (aligned with PY)\n\tregisterStep(graph, name, output as unknown as Node<unknown>, src.path ? [src.path] : []);\n\tconst internal = new Graph(`${name}_state`);\n\tinternal.add(\"pending\", pendingNode);\n\tinternal.add(\"isOpen\", isOpenNode);\n\tinternal.add(\"count\", countNode);\n\tgraph.mount(`${name}_state`, internal);\n\n\treturn controller;\n}\n\n/**\n * Registers a workflow side-effect step that runs `run` for each upstream\n * DATA value.\n *\n * `run` receives the full `NodeActions` and is the **sole emission point** —\n * call `actions.emit(v)` or `actions.down(msgs)` inside `run` to produce\n * downstream output. If `run` does not emit, this step acts as a pure\n * side-effect sink (graph-observable but no output). Throwing inside `run`\n * terminates the step with ERROR.\n */\nexport function forEach<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\trun: (value: T, actions: NodeActions) => void,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tlet terminated = false;\n\tconst step = node<T>(\n\t\t[src.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tif (terminated) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Terminal from dep\n\t\t\tconst terminal = ctx.terminalDeps[0];\n\t\t\tif (terminal !== undefined) {\n\t\t\t\tterminated = true;\n\t\t\t\tactions.down(terminal === true ? [[COMPLETE]] : [[ERROR, terminal]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst batch0 = batchData[0];\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) {\n\t\t\t\ttry {\n\t\t\t\t\trun(v, actions);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tterminated = true;\n\t\t\t\t\tactions.down([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"effect\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tmeta: baseMeta(\"forEach\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\t// registerStep registers the edge for graph visibility. g.connect's dedup\n\t// check skips _addDep since src.node is already a constructor dep.\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n\n/**\n * Registers a join step that emits a tuple of latest dependency values.\n */\nexport function join<T extends readonly unknown[]>(\n\tgraph: Graph,\n\tname: string,\n\tdeps: { [K in keyof T]: StepRef },\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst resolved = deps.map((dep) => resolveDep(graph, dep));\n\tconst step = derived<T>(\n\t\tresolved.map((d) => d.node),\n\t\t(values) => values as T,\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tmeta: baseMeta(\"join\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\tresolved.flatMap((d) => (d.path ? [d.path] : [])),\n\t);\n\treturn step;\n}\n\n/**\n * Registers a loop step that applies `iterate` to each source value N times.\n */\nexport function loop<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\titerate: (value: T, iteration: number, actions: NodeActions) => T,\n\topts?: LoopOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst iterRef = opts?.iterations;\n\tconst iterDep =\n\t\ttypeof iterRef === \"number\" || iterRef === undefined ? undefined : resolveDep(graph, iterRef);\n\tconst staticIterations = typeof iterRef === \"number\" ? iterRef : undefined;\n\tconst step = node<T>(\n\t\titerDep ? [src.node, iterDep.node] : [src.node],\n\t\t(depValues, actions, ctx) => {\n\t\t\tconst batch0 = depValues[0];\n\t\t\tlet current = (batch0 != null && batch0.length > 0 ? batch0.at(-1) : ctx.prevData[0]) as T;\n\t\t\tconst batch1 = iterDep ? depValues[1] : undefined;\n\t\t\tconst rawCount =\n\t\t\t\tstaticIterations ??\n\t\t\t\t(iterDep ? (batch1 != null && batch1.length > 0 ? batch1.at(-1) : ctx.prevData[1]) : 1);\n\t\t\tconst count = coerceLoopIterations(rawCount);\n\t\t\tfor (let i = 0; i < count; i += 1) {\n\t\t\t\tcurrent = iterate(current, i, actions);\n\t\t\t}\n\t\t\tactions.emit(current);\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"loop\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, iterDep?.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\n/**\n * Mounts and returns a child workflow graph.\n */\nexport function subPipeline(\n\tgraph: Graph,\n\tname: string,\n\tchildOrBuild?: Graph | SubPipelineBuilder,\n\topts?: GraphOptions,\n): Graph {\n\tconst child = childOrBuild instanceof Graph ? childOrBuild : pipeline(name, opts);\n\tif (typeof childOrBuild === \"function\") {\n\t\tchildOrBuild(child);\n\t}\n\tgraph.mount(name, child);\n\treturn child;\n}\n\n/**\n * Registers a producer-style sensor source and returns imperative controls.\n */\nexport function sensor<T>(\n\tgraph: Graph,\n\tname: string,\n\tinitial?: T,\n\topts?: Omit<NodeOptions<unknown>, \"name\" | \"describeKind\" | \"meta\"> & {\n\t\tmeta?: Record<string, unknown>;\n\t},\n): SensorControls<T> {\n\tconst source = node<T>([], () => undefined, {\n\t\t...opts,\n\t\tname,\n\t\tinitial,\n\t\tdescribeKind: \"producer\",\n\t\tmeta: baseMeta(\"sensor\", opts?.meta),\n\t});\n\tregisterStep(graph, name, source as unknown as Node<unknown>, []);\n\treturn {\n\t\tnode: source,\n\t\tpush(value: T) {\n\t\t\tsource.down([[DATA, value]] satisfies Messages);\n\t\t},\n\t\terror(err: unknown) {\n\t\t\tsource.down([[ERROR, err]] satisfies Messages);\n\t\t},\n\t\tcomplete() {\n\t\t\tsource.down([[COMPLETE]] satisfies Messages);\n\t\t},\n\t};\n}\n\n/**\n * Registers a delayed-forwarding step (value-level wait).\n */\nexport function wait<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tms: number,\n\topts?: WaitOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst timers = new Set<ReturnType<typeof setTimeout>>();\n\tlet terminated = false;\n\tlet completed = false;\n\n\tfunction clearAllTimers(): void {\n\t\tfor (const id of timers) clearTimeout(id);\n\t\ttimers.clear();\n\t}\n\n\t// Producer pattern: 0 deps, manual subscribe to source.\n\t// Under Model B (push-on-subscribe) the fn runs eagerly via _startProducer,\n\t// ensuring the cleanup is registered and timers are cleared on teardown.\n\t// Only set initial if source has a real cached value (not SENTINEL/undefined).\n\tconst srcVal = src.node.cache;\n\tconst initialOpt = srcVal !== undefined ? { initial: srcVal as T } : {};\n\n\tconst step = node<T>(\n\t\t[],\n\t\t(_deps, actions) => {\n\t\t\tclearAllTimers();\n\t\t\tterminated = false;\n\t\t\tcompleted = false;\n\t\t\tconst unsub = src.node.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (terminated) return;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst id = setTimeout(() => {\n\t\t\t\t\t\t\ttimers.delete(id);\n\t\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t\t\tif (completed && timers.size === 0) {\n\t\t\t\t\t\t\t\tactions.down([[COMPLETE]] satisfies Messages);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, ms);\n\t\t\t\t\t\ttimers.add(id);\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tterminated = true;\n\t\t\t\t\t\tcompleted = true;\n\t\t\t\t\t\tif (timers.size === 0) {\n\t\t\t\t\t\t\tactions.down([[COMPLETE]] satisfies Messages);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tterminated = true;\n\t\t\t\t\t\tclearAllTimers();\n\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tclearAllTimers();\n\t\t\t\tterminated = true;\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\t...initialOpt,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tmeta: baseMeta(\"wait\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\t// Producer pattern: register in graph without dep edges (manual subscription).\n\t// Post edge-registry deletion (Unit 7), edges are derived from node `_deps`\n\t// exclusively; this producer's logical dep on `src` is not reflected in\n\t// `describe()` — by design, since there is no real constructor-time\n\t// dependency to show.\n\tgraph.add(name, step as unknown as Node<unknown>);\n\treturn step;\n}\n\n/**\n * Registers an error-recovery step for a source.\n */\nexport function onFailure<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\trecover: (err: unknown, actions: NodeActions) => T,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tlet terminated = false;\n\t// Producer pattern: manually subscribe to source for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\tconst step = node<T>(\n\t\t[],\n\t\t(_data, actions) => {\n\t\t\tconst unsub = src.node.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (terminated) return;\n\t\t\t\t\tif (msg[0] === ERROR) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tactions.emit(recover(msg[1], actions));\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tterminated = true;\n\t\t\t\t\t\t\tactions.down([[ERROR, err]] satisfies Messages);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t\tif (msg[0] === COMPLETE) terminated = true;\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\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t// onFailure handles errors via manual subscription (recover callback).\n\t\t\t// Disable auto-propagation so dep-channel ERROR doesn't terminate this\n\t\t\t// node before the recover callback has a chance to emit a replacement value.\n\t\t\terrorWhenDepsError: false,\n\t\t\tmeta: baseMeta(\"onFailure\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n","/**\n * Three-pane demo shell (roadmap §7.2).\n *\n * A `Graph(\"demo-shell\")` that dogfoods reactive coordination for the\n * main/side split layout with synchronized cross-highlighting.\n *\n * **Zero framework dependency** — framework bindings wrap pane components only.\n * The shell graph is headless and fully testable.\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { describeNode, resolveDescribeFields } from \"../core/meta.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { Graph } from \"../graph/graph.js\";\nimport type { MeasurementAdapter } from \"./reactive-layout/reactive-layout.js\";\nimport { analyzeAndMeasure, computeLineBreaks } from \"./reactive-layout/reactive-layout.js\";\n\n// ——————————————————————————————————————————————————————————\n// Types\n// ——————————————————————————————————————————————————————————\n\n/** Identifies which pane is the source of a hover event. */\nexport type HoverPaneType = \"visual\" | \"graph\" | \"code\";\n\n/** Cross-highlighting hover target. `null` means nothing hovered. */\nexport type HoverTarget = { pane: HoverPaneType; id: string } | null;\n\n/** Which pane is full-screened (null = normal layout). */\nexport type FullscreenPane = \"main\" | \"graph\" | \"code\" | null;\n\n/**\n * Cross-referencing registry: maps node paths to code line numbers and\n * visual element selectors. Provided by each demo's `store.ts`.\n */\nexport type NodeRegistry = Map<string, { codeLine: number; visualSelector: string }>;\n\n/** Callbacks for cross-highlighting effect nodes. */\nexport type HighlightCallbacks = {\n\t/** Called when code-scroll highlight target changes. */\n\tcodeScroll?: (line: number | null) => void;\n\t/** Called when visual highlight target changes. */\n\tvisual?: (selector: string | null) => void;\n\t/** Called when graph highlight target changes. */\n\tgraph?: (nodeId: string | null) => void;\n};\n\n/** Label dimensions for graph node sizing. */\nexport type GraphLabelSize = { width: number; height: number };\n\n/** Options for {@link demoShell}. */\nexport type DemoShellOptions = {\n\t/** Initial main/side split ratio (0–1). Default: `0.65`. */\n\tmainRatio?: number;\n\t/** Initial graph/code vertical split in the side pane (0–1). Default: `0.5`. */\n\tsideSplit?: number;\n\t/** Initial viewport width in pixels. Default: `1280`. */\n\tviewportWidth?: number;\n\t/** Cross-referencing registry for hover→code/visual/graph mapping. */\n\tnodeRegistry?: NodeRegistry;\n\t/** Measurement adapter for layout engine integration. When provided, enables layout/* derived nodes. */\n\tadapter?: MeasurementAdapter;\n\t/** Font string for layout measurement. Default: `\"14px monospace\"`. */\n\tlayoutFont?: string;\n\t/** Callbacks for cross-highlighting effect nodes. When provided, creates effect nodes visible in describe(). */\n\tonHighlight?: HighlightCallbacks;\n};\n\n/** Return type of {@link demoShell}. */\nexport type DemoShellHandle = {\n\t/** The demo-shell graph. */\n\tgraph: Graph;\n\n\t// ── Convenience setters (shorthand for graph.set) ──────────\n\tsetMainRatio(ratio: number): void;\n\tsetSideSplit(ratio: number): void;\n\tsetFullscreen(pane: FullscreenPane): void;\n\tsetViewportWidth(width: number): void;\n\tsetHoverTarget(target: HoverTarget): void;\n\tsetDemoGraph(g: Graph | null): void;\n\tbumpGraphTick(): void;\n\tselectNode(path: string | null): void;\n\tsetMetaDebug(on: boolean): void;\n\t/** Set code text for layout/code-lines measurement (requires adapter). */\n\tsetCodeText(text: string): void;\n\t/** Atomic multi-set — wraps core `batch()` for glitch-free updates. */\n\tbatch(fn: () => void): void;\n\tdestroy(): void;\n};\n\n// ——————————————————————————————————————————————————————————\n// Helpers\n// ——————————————————————————————————————————————————————————\n\nfunction clamp01(v: number): number {\n\treturn Math.max(0, Math.min(1, v));\n}\n\n// ——————————————————————————————————————————————————————————\n// Factory\n// ——————————————————————————————————————————————————————————\n\n/**\n * Creates the three-pane demo shell graph (roadmap §7.2).\n *\n * All coordination is reactive — no polling, no imperative triggers.\n * Framework bindings subscribe to named nodes and drive `state` inputs.\n */\nexport function demoShell(opts?: DemoShellOptions): DemoShellHandle {\n\tconst mainRatioInit = clamp01(opts?.mainRatio ?? 0.65);\n\tconst sideSplitInit = clamp01(opts?.sideSplit ?? 0.5);\n\tconst viewportInit = Math.max(0, opts?.viewportWidth ?? 1280);\n\tconst registry = opts?.nodeRegistry ?? new Map();\n\tconst adapter = opts?.adapter ?? null;\n\tconst layoutFont = opts?.layoutFont ?? \"14px monospace\";\n\tconst onHighlight = opts?.onHighlight;\n\n\tconst g = new Graph(\"demo-shell\");\n\n\t// ── Layout state ─────────────────────────────────────\n\tconst paneMainRatio = state(mainRatioInit, { name: \"pane/main-ratio\" });\n\tconst paneSideSplit = state(sideSplitInit, { name: \"pane/side-split\" });\n\tconst paneFullscreen = state<FullscreenPane>(null, {\n\t\tname: \"pane/fullscreen\",\n\t});\n\tconst viewportWidth = state(viewportInit, { name: \"viewport/width\" });\n\n\tg.add(\"pane/main-ratio\", paneMainRatio);\n\tg.add(\"pane/side-split\", paneSideSplit);\n\tg.add(\"pane/fullscreen\", paneFullscreen);\n\tg.add(\"viewport/width\", viewportWidth);\n\n\t// ── Derived pane dimensions ──────────────────────────\n\tconst paneMainWidth = derived(\n\t\t[paneMainRatio, viewportWidth, paneFullscreen],\n\t\t([ratio, vw, fs]) => {\n\t\t\tconst r = ratio as number;\n\t\t\tconst w = vw as number;\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tif (fullscreen === \"main\") return w;\n\t\t\tif (fullscreen === \"graph\" || fullscreen === \"code\") return 0;\n\t\t\treturn Math.round(w * r);\n\t\t},\n\t\t{ name: \"pane/main-width\" },\n\t);\n\n\tconst paneSideWidth = derived(\n\t\t[paneMainWidth, viewportWidth, paneFullscreen],\n\t\t([main, vw, fs]) => {\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tconst w = vw as number;\n\t\t\tif (fullscreen === \"main\") return 0;\n\t\t\tif (fullscreen === \"graph\" || fullscreen === \"code\") return w;\n\t\t\treturn (w as number) - (main as number);\n\t\t},\n\t\t{ name: \"pane/side-width\" },\n\t);\n\n\tconst paneGraphHeight = derived(\n\t\t[paneSideSplit, paneFullscreen],\n\t\t([split, fs]) => {\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tif (fullscreen === \"graph\") return 1;\n\t\t\tif (fullscreen === \"code\") return 0;\n\t\t\tif (fullscreen === \"main\") return 0;\n\t\t\treturn clamp01(split as number);\n\t\t},\n\t\t{ name: \"pane/graph-height-ratio\" },\n\t);\n\n\tconst paneCodeHeight = derived(\n\t\t[paneGraphHeight, paneFullscreen],\n\t\t([graphH, fs]) => {\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tif (fullscreen === \"code\") return 1;\n\t\t\tif (fullscreen === \"graph\" || fullscreen === \"main\") return 0;\n\t\t\treturn 1 - (graphH as number);\n\t\t},\n\t\t{ name: \"pane/code-height-ratio\" },\n\t);\n\n\tg.add(\"pane/main-width\", paneMainWidth);\n\tg.add(\"pane/side-width\", paneSideWidth);\n\tg.add(\"pane/graph-height-ratio\", paneGraphHeight);\n\tg.add(\"pane/code-height-ratio\", paneCodeHeight);\n\n\t// ── External graph observation ───────────────────────\n\tconst demoGraphRef = state<Graph | null>(null, {\n\t\tname: \"demo/graph-ref\",\n\t});\n\tconst demoGraphTick = state(0, { name: \"demo/graph-tick\" });\n\n\tg.add(\"demo/graph-ref\", demoGraphRef);\n\tg.add(\"demo/graph-tick\", demoGraphTick);\n\n\tconst graphMermaid = derived(\n\t\t[demoGraphRef, demoGraphTick],\n\t\t([ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tif (!demo) return \"\";\n\t\t\treturn demo.describe({ format: \"mermaid\" });\n\t\t},\n\t\t{ name: \"graph/mermaid\" },\n\t);\n\n\tconst graphDescribe = derived(\n\t\t[demoGraphRef, demoGraphTick],\n\t\t([ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tif (!demo) return null;\n\t\t\tconst { expand: _, ...snapshot } = demo.describe({ detail: \"standard\" });\n\t\t\treturn snapshot;\n\t\t},\n\t\t{ name: \"graph/describe\" },\n\t);\n\n\tg.add(\"graph/mermaid\", graphMermaid);\n\tg.add(\"graph/describe\", graphDescribe);\n\n\t// ── Cross-highlighting ───────────────────────────────\n\tconst hoverTarget = state<HoverTarget>(null, { name: \"hover/target\" });\n\tg.add(\"hover/target\", hoverTarget);\n\n\tconst highlightCodeScroll = derived(\n\t\t[hoverTarget],\n\t\t([target]) => {\n\t\t\tconst t = target as HoverTarget;\n\t\t\tif (!t) return null;\n\t\t\tconst entry = registry.get(t.id);\n\t\t\treturn entry ? entry.codeLine : null;\n\t\t},\n\t\t{ name: \"highlight/code-scroll\" },\n\t);\n\n\tconst highlightVisual = derived(\n\t\t[hoverTarget],\n\t\t([target]) => {\n\t\t\tconst t = target as HoverTarget;\n\t\t\tif (!t) return null;\n\t\t\tconst entry = registry.get(t.id);\n\t\t\treturn entry ? entry.visualSelector : null;\n\t\t},\n\t\t{ name: \"highlight/visual\" },\n\t);\n\n\tconst highlightGraph = derived(\n\t\t[hoverTarget],\n\t\t([target]) => {\n\t\t\tconst t = target as HoverTarget;\n\t\t\tif (!t) return null;\n\t\t\treturn t.id;\n\t\t},\n\t\t{ name: \"highlight/graph\" },\n\t);\n\n\tg.add(\"highlight/code-scroll\", highlightCodeScroll);\n\tg.add(\"highlight/visual\", highlightVisual);\n\tg.add(\"highlight/graph\", highlightGraph);\n\n\t// ── Cross-highlighting effect nodes (optional) ─────\n\t// Created when onHighlight callbacks are provided, making the full\n\t// source→derived→effect chain visible in describe()/toMermaid().\n\n\tif (onHighlight?.codeScroll) {\n\t\tconst cb = onHighlight.codeScroll;\n\t\tconst applyCodeScroll = effect([highlightCodeScroll], ([line]) => {\n\t\t\tcb(line as number | null);\n\t\t});\n\t\tg.add(\"highlight/apply-code-scroll\", applyCodeScroll);\n\t}\n\n\tif (onHighlight?.visual) {\n\t\tconst cb = onHighlight.visual;\n\t\tconst applyVisual = effect([highlightVisual], ([selector]) => {\n\t\t\tcb(selector as string | null);\n\t\t});\n\t\tg.add(\"highlight/apply-visual\", applyVisual);\n\t}\n\n\tif (onHighlight?.graph) {\n\t\tconst cb = onHighlight.graph;\n\t\tconst applyGraph = effect([highlightGraph], ([nodeId]) => {\n\t\t\tcb(nodeId as string | null);\n\t\t});\n\t\tg.add(\"highlight/apply-graph\", applyGraph);\n\t}\n\n\t// ── Inspect panel ────────────────────────────────────\n\tconst inspectSelected = state<string | null>(null, {\n\t\tname: \"inspect/selected-node\",\n\t});\n\tg.add(\"inspect/selected-node\", inspectSelected);\n\n\tconst standardFields = resolveDescribeFields(\"standard\");\n\n\tconst inspectNodeDetail = derived(\n\t\t[inspectSelected, demoGraphRef, demoGraphTick],\n\t\t([path, ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tconst p = path as string | null;\n\t\t\tif (!demo || !p) return null;\n\t\t\ttry {\n\t\t\t\tconst nd = demo.resolve(p);\n\t\t\t\tconst nodeDesc = describeNode(nd, standardFields);\n\t\t\t\treturn { path: p, ...nodeDesc, value: nd.cache };\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t\t{ name: \"inspect/node-detail\" },\n\t);\n\n\tconst inspectTraceLog = derived(\n\t\t[demoGraphRef, demoGraphTick],\n\t\t([ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tif (!demo) return [];\n\t\t\treturn demo.trace();\n\t\t},\n\t\t{ name: \"inspect/trace-log\" },\n\t);\n\n\tg.add(\"inspect/node-detail\", inspectNodeDetail);\n\tg.add(\"inspect/trace-log\", inspectTraceLog);\n\n\t// ── Meta debug toggle ────────────────────────────────\n\tconst metaDebug = state(false, { name: \"meta/debug\" });\n\tg.add(\"meta/debug\", metaDebug);\n\n\tconst metaShellMermaid = derived(\n\t\t[metaDebug, demoGraphTick],\n\t\t([debug, _tick]) => {\n\t\t\tif (!(debug as boolean)) return \"\";\n\t\t\treturn g.describe({ format: \"mermaid\" });\n\t\t},\n\t\t{ name: \"meta/shell-mermaid\" },\n\t);\n\tg.add(\"meta/shell-mermaid\", metaShellMermaid);\n\n\t// ── Layout engine integration (optional, requires adapter) ──\n\tconst codeTextNode = state(\"\", { name: \"layout/code-text\" });\n\tg.add(\"layout/code-text\", codeTextNode);\n\n\tif (adapter) {\n\t\tconst measureCache = new Map<string, Map<string, number>>();\n\n\t\tconst graphLabels = derived(\n\t\t\t[graphDescribe],\n\t\t\t([desc]) => {\n\t\t\t\tconst d = desc as { nodes: Record<string, { type: string }> } | null;\n\t\t\t\tif (!d) return new Map<string, GraphLabelSize>();\n\t\t\t\tconst result = new Map<string, GraphLabelSize>();\n\t\t\t\tfor (const [name] of Object.entries(d.nodes)) {\n\t\t\t\t\tconst segments = analyzeAndMeasure(name, layoutFont, adapter, measureCache);\n\t\t\t\t\tconst lb = computeLineBreaks(segments, Infinity, adapter, layoutFont, measureCache);\n\t\t\t\t\tconst width = lb.lines.reduce((max, l) => Math.max(max, l.width), 0);\n\t\t\t\t\tconst height = lb.lineCount * 20; // line-height approximation\n\t\t\t\t\tresult.set(name, { width, height });\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"layout/graph-labels\",\n\t\t\t\tequals: (a, b) => {\n\t\t\t\t\tif (a === b) return true;\n\t\t\t\t\tconst ma = a as Map<string, GraphLabelSize>;\n\t\t\t\t\tconst mb = b as Map<string, GraphLabelSize>;\n\t\t\t\t\tif (ma.size !== mb.size) return false;\n\t\t\t\t\tfor (const [k, v] of ma) {\n\t\t\t\t\t\tconst bv = mb.get(k);\n\t\t\t\t\t\tif (!bv || bv.width !== v.width || bv.height !== v.height) return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tconst codeLines = derived(\n\t\t\t[codeTextNode, paneSideWidth],\n\t\t\t([text, sideW]) => {\n\t\t\t\tconst t = text as string;\n\t\t\t\tif (!t) return { lineCount: 0, lines: [] };\n\t\t\t\tconst segments = analyzeAndMeasure(t, layoutFont, adapter, measureCache);\n\t\t\t\tconst maxW = (sideW as number) - 40; // side pane minus padding\n\t\t\t\treturn computeLineBreaks(segments, Math.max(100, maxW), adapter, layoutFont, measureCache);\n\t\t\t},\n\t\t\t{ name: \"layout/code-lines\" },\n\t\t);\n\n\t\tconst sideWidthHint = derived(\n\t\t\t[graphLabels],\n\t\t\t([labels]) => {\n\t\t\t\tconst m = labels as Map<string, GraphLabelSize>;\n\t\t\t\tif (m.size === 0) return 200; // minimum default\n\t\t\t\tlet maxW = 0;\n\t\t\t\tfor (const { width } of m.values()) {\n\t\t\t\t\tif (width > maxW) maxW = width;\n\t\t\t\t}\n\t\t\t\t// widest label + padding (node box chrome + margin)\n\t\t\t\treturn Math.max(200, Math.round(maxW + 80));\n\t\t\t},\n\t\t\t{ name: \"layout/side-width-hint\" },\n\t\t);\n\n\t\tg.add(\"layout/graph-labels\", graphLabels);\n\t\tg.add(\"layout/code-lines\", codeLines);\n\t\tg.add(\"layout/side-width-hint\", sideWidthHint);\n\t}\n\n\t// ── Edges (explicit wiring for describe/toMermaid) ───\n\n\t// ── Handle ───────────────────────────────────────────\n\tlet tickCounter = 0;\n\treturn {\n\t\tgraph: g,\n\t\tsetMainRatio(ratio: number) {\n\t\t\tg.set(\"pane/main-ratio\", clamp01(ratio));\n\t\t},\n\t\tsetSideSplit(ratio: number) {\n\t\t\tg.set(\"pane/side-split\", clamp01(ratio));\n\t\t},\n\t\tsetFullscreen(pane: FullscreenPane) {\n\t\t\tg.set(\"pane/fullscreen\", pane);\n\t\t},\n\t\tsetViewportWidth(width: number) {\n\t\t\tg.set(\"viewport/width\", Math.max(0, width));\n\t\t},\n\t\tsetHoverTarget(target: HoverTarget) {\n\t\t\tg.set(\"hover/target\", target);\n\t\t},\n\t\tsetDemoGraph(demo: Graph | null) {\n\t\t\tg.set(\"demo/graph-ref\", demo);\n\t\t},\n\t\tbumpGraphTick() {\n\t\t\tg.set(\"demo/graph-tick\", ++tickCounter);\n\t\t},\n\t\tselectNode(path: string | null) {\n\t\t\tg.set(\"inspect/selected-node\", path);\n\t\t},\n\t\tsetMetaDebug(on: boolean) {\n\t\t\tg.set(\"meta/debug\", on);\n\t\t},\n\t\tsetCodeText(text: string) {\n\t\t\tg.set(\"layout/code-text\", text);\n\t\t},\n\t\tbatch(fn: () => void) {\n\t\t\tbatch(fn);\n\t\t},\n\t\tdestroy() {\n\t\t\tg.destroy();\n\t\t},\n\t};\n}\n","/**\n * Domain templates (roadmap §8.2).\n *\n * Opinionated Graph factories for common \"info → action\" domains.\n * Each template wires up §8.1 reduction primitives (stratify, funnel, feedback,\n * budgetGate, scorer) with domain-specific stages. Users fork/extend by\n * accessing named nodes and swapping stages.\n *\n * **Source injection (option B):** templates accept a `source` node, not a\n * hardcoded adapter. Pass `fromOTel(...)`, `fromGitHook(...)`, or a test\n * `state()` — the topology is the same.\n *\n * @module\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { reactiveLog } from \"../extra/reactive-log.js\";\nimport { Graph, type GraphOptions } from \"../graph/graph.js\";\nimport { feedback, type StratifyRule, scorer, stratify } from \"./reduction.js\";\n\n// ---------------------------------------------------------------------------\n// Shared\n// ---------------------------------------------------------------------------\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"domain_template\", kind, extra);\n}\n\n// ---------------------------------------------------------------------------\n// 1. observabilityGraph\n// ---------------------------------------------------------------------------\n\n/** Stratification branch config for observability signals. */\nexport type ObservabilityBranch = {\n\tname: string;\n\tclassify: (value: unknown) => boolean;\n};\n\n/** Options for {@link observabilityGraph}. */\nexport type ObservabilityGraphOptions = GraphOptions & {\n\t/** Ingested signal source (e.g. fromOTel(...) or test state). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Classification rules for signal stratification.\n\t * Default: errors / traces / metrics branches.\n\t */\n\tbranches?: ObservabilityBranch[];\n\n\t/**\n\t * Correlation function: receives stratified branch values and produces\n\t * correlated insights. Default: identity pass-through.\n\t */\n\tcorrelate?: (values: unknown[]) => unknown;\n\n\t/**\n\t * SLO verification function: returns a verification result for a\n\t * correlated insight. Default: always passes.\n\t */\n\tsloCheck?: (value: unknown) => unknown;\n\n\t/**\n\t * Scorer weights for alert prioritization. One per branch.\n\t * Default: equal weights [1, 1, 1].\n\t */\n\tweights?: number[];\n\n\t/** Max feedback iterations for false-positive learning. Default: 5. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * OTel ingest → stratified reduction → correlation → SLO verification →\n * alert prioritization → output.\n *\n * Well-known node names:\n * - `\"source\"` — injected signal source\n * - `\"stratify::branch/<name>\"` — per-branch classification\n * - `\"correlate\"` — cross-branch correlation\n * - `\"slo_value\"`, `\"slo_verified\"` — SLO verification pair\n * - `\"alerts\"` — scored, prioritized output\n * - `\"output\"` — final output (alias for alerts)\n *\n * @category patterns\n */\nexport function observabilityGraph(name: string, opts: ObservabilityGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Stratify ---\n\tconst defaultBranches: ObservabilityBranch[] = [\n\t\t{ name: \"errors\", classify: (v) => isTagged(v, \"error\") },\n\t\t{ name: \"traces\", classify: (v) => isTagged(v, \"trace\") },\n\t\t{ name: \"metrics\", classify: (v) => isTagged(v, \"metric\") },\n\t];\n\tconst branches = opts.branches ?? defaultBranches;\n\tconst rules: StratifyRule<unknown>[] = branches.map((b) => ({\n\t\tname: b.name,\n\t\tclassify: b.classify,\n\t}));\n\tconst strat = stratify(\"stratify\", opts.source, rules);\n\tg.mount(\"stratify\", strat);\n\n\t// --- Correlate ---\n\t// Collect latest value from each branch, produce correlated output.\n\t// Wrap each branch in a derived with `initial: null` so every branch has\n\t// a seed value at subscribe time — this lets the correlate wave reach its\n\t// first-run gate even when the classifier only routes to one branch.\n\tconst branchNodes = branches.map((b) => {\n\t\ttry {\n\t\t\tconst raw = g.resolve(`stratify::branch/${b.name}`);\n\t\t\treturn derived([raw as Node], ([v]) => v, { initial: null });\n\t\t} catch {\n\t\t\treturn state<unknown>(null);\n\t\t}\n\t});\n\tconst correlateFn = opts.correlate ?? ((vals: unknown[]) => vals);\n\tconst correlateNode = derived<unknown>(\n\t\tbranchNodes as Node[],\n\t\t(vals) => correlateFn(vals as unknown[]),\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"correlate\" }),\n\t\t},\n\t);\n\tg.add(\"correlate\", correlateNode);\n\n\t// --- SLO verification ---\n\tconst sloCheckFn = opts.sloCheck ?? (() => ({ pass: true }));\n\tconst sloValue = derived<unknown>([correlateNode], (vals) => vals[0], {\n\t\tmeta: baseMeta(\"observability\", { stage: \"slo_value\" }),\n\t});\n\tconst sloVerified = derived<unknown>([sloValue], (vals) => sloCheckFn(vals[0]), {\n\t\tmeta: baseMeta(\"observability\", { stage: \"slo_verified\" }),\n\t});\n\tg.add(\"slo_value\", sloValue);\n\tg.add(\"slo_verified\", sloVerified);\n\n\t// --- Alert scorer ---\n\tconst weightValues = opts.weights ?? branches.map(() => 1);\n\tconst signalNodes = branchNodes.map((bn) =>\n\t\tderived<number>([bn], (vals) => (vals[0] != null ? 1 : 0)),\n\t);\n\tconst weightNodes = weightValues.map((w) => state<number>(w));\n\tfor (let i = 0; i < signalNodes.length; i++) {\n\t\tg.add(`__signal_${i}`, signalNodes[i] as Node<unknown>);\n\t\tg.add(`__weight_${i}`, weightNodes[i] as Node<unknown>);\n\t}\n\tconst alerts = scorer(\n\t\tsignalNodes as ReadonlyArray<Node<number>>,\n\t\tweightNodes as ReadonlyArray<Node<number>>,\n\t);\n\tg.add(\"alerts\", alerts as Node<unknown>);\n\n\t// --- Output alias ---\n\tconst output = derived<unknown>(\n\t\t[alerts as Node, sloVerified],\n\t\t(vals) => ({\n\t\t\tscored: vals[0],\n\t\t\tslo: vals[1],\n\t\t}),\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"output\" }),\n\t\t},\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (false-positive learning) ---\n\t// SLO failures feed back to re-check with updated context.\n\tconst fbReentry = state<unknown>(null, {\n\t\tmeta: baseMeta(\"observability\", { stage: \"feedback_reentry\" }),\n\t});\n\tg.add(\"feedback_reentry\", fbReentry);\n\tconst fbCondition = derived<unknown>(\n\t\t[sloVerified],\n\t\t(vals) => {\n\t\t\tconst result = vals[0] as Record<string, unknown> | null;\n\t\t\tif (result && result.pass === false) return result;\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"feedback_reentry\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 5,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 2. issueTrackerGraph\n// ---------------------------------------------------------------------------\n\n/** A structured issue extracted from raw findings. */\nexport type ExtractedIssue = {\n\tid: string;\n\ttitle: string;\n\tseverity: number;\n\tsource: string;\n\traw: unknown;\n};\n\n/** Options for {@link issueTrackerGraph}. */\nexport type IssueTrackerGraphOptions = GraphOptions & {\n\t/** Findings source (e.g. fromGitHook(...), fromFSWatch(...)). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Extract structured issues from raw findings.\n\t * Default: wraps raw value as a single issue.\n\t */\n\textract?: (raw: unknown) => ExtractedIssue;\n\n\t/**\n\t * Verify an extracted issue (assertion check).\n\t * Default: always valid.\n\t */\n\tverify?: (issue: ExtractedIssue) => unknown;\n\n\t/**\n\t * Detect regression by comparing against known patterns.\n\t * Receives (current issue, known patterns).\n\t * Default: no regression detected.\n\t */\n\tdetectRegression?: (issue: ExtractedIssue, known: unknown) => unknown;\n\n\t/** Max feedback iterations for re-scanning. Default: 3. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * Findings ingest → extraction → verification → regression detection →\n * distillation → prioritized queue.\n *\n * Well-known node names:\n * - `\"source\"` — injected findings source\n * - `\"extract\"` — structured issue extraction\n * - `\"verify\"` — issue verification\n * - `\"known_patterns\"` — accumulated known issue patterns (state)\n * - `\"regression\"` — regression detection\n * - `\"priority\"` — severity-based prioritization\n * - `\"output\"` — final prioritized output\n *\n * @category patterns\n */\nexport function issueTrackerGraph(name: string, opts: IssueTrackerGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Extract ---\n\tlet _issueCounter = 0;\n\tconst defaultExtract = (raw: unknown): ExtractedIssue => ({\n\t\tid: `issue-${++_issueCounter}`,\n\t\ttitle: String(raw),\n\t\tseverity: 1,\n\t\tsource: \"unknown\",\n\t\traw,\n\t});\n\tconst extractFn = opts.extract ?? defaultExtract;\n\tconst extractNode = derived<ExtractedIssue>([opts.source], (vals) => extractFn(vals[0]), {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"extract\" }),\n\t});\n\tg.add(\"extract\", extractNode as Node<unknown>);\n\n\t// --- Verify ---\n\tconst verifyFn = opts.verify ?? (() => ({ valid: true }));\n\tconst verifyNode = derived<unknown>(\n\t\t[extractNode as Node],\n\t\t(vals) => {\n\t\t\tconst issue = vals[0] as ExtractedIssue;\n\t\t\treturn { issue, verification: verifyFn(issue) };\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"verify\" }),\n\t\t},\n\t);\n\tg.add(\"verify\", verifyNode);\n\n\t// --- Known patterns (memory / distillation state) ---\n\tconst knownPatterns = state<unknown[]>([], {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"known_patterns\" }),\n\t});\n\tg.add(\"known_patterns\", knownPatterns as Node<unknown>);\n\n\t// --- Regression detection ---\n\tconst detectFn = opts.detectRegression ?? (() => ({ regression: false }));\n\tconst regressionNode = derived<unknown>(\n\t\t[extractNode as Node, knownPatterns as Node],\n\t\t(vals) => {\n\t\t\tconst issue = vals[0] as ExtractedIssue;\n\t\t\tconst known = vals[1];\n\t\t\treturn { issue, regression: detectFn(issue, known) };\n\t\t},\n\t\t{ meta: baseMeta(\"issue_tracker\", { stage: \"regression\" }) },\n\t);\n\tg.add(\"regression\", regressionNode);\n\n\t// --- Priority scoring ---\n\tconst severitySignal = derived<number>([extractNode as Node], (vals) => {\n\t\tconst issue = vals[0] as ExtractedIssue;\n\t\treturn issue?.severity ?? 0;\n\t});\n\tconst regressionSignal = derived<number>([regressionNode], (vals) => {\n\t\tconst r = vals[0] as Record<string, unknown> | null;\n\t\treturn r?.regression ? 2 : 0;\n\t});\n\tg.add(\"__severity_signal\", severitySignal as Node<unknown>);\n\tg.add(\"__regression_signal\", regressionSignal as Node<unknown>);\n\n\tconst severityWeight = state<number>(1);\n\tconst regressionWeight = state<number>(1.5);\n\tg.add(\"__severity_weight\", severityWeight as Node<unknown>);\n\tg.add(\"__regression_weight\", regressionWeight as Node<unknown>);\n\n\tconst priority = scorer([severitySignal, regressionSignal], [severityWeight, regressionWeight]);\n\tg.add(\"priority\", priority as Node<unknown>);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[verifyNode, regressionNode, priority as Node],\n\t\t(vals) => ({\n\t\t\tverified: vals[0],\n\t\t\tregression: vals[1],\n\t\t\tpriority: vals[2],\n\t\t}),\n\t\t{ meta: baseMeta(\"issue_tracker\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (re-scan on verification failure) ---\n\tconst fbReentry = state<unknown>(null, {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"feedback_reentry\" }),\n\t});\n\tg.add(\"feedback_reentry\", fbReentry);\n\tconst fbCondition = derived<unknown>(\n\t\t[verifyNode],\n\t\t(vals) => {\n\t\t\tconst result = vals[0] as Record<string, unknown> | null;\n\t\t\tif (result) {\n\t\t\t\tconst v = result.verification as Record<string, unknown> | null;\n\t\t\t\tif (v && v.valid === false) return result;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"feedback_reentry\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 3,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 3. contentModerationGraph\n// ---------------------------------------------------------------------------\n\n/** Classification result from LLM moderation. */\nexport type ModerationResult = {\n\tlabel: \"safe\" | \"review\" | \"block\";\n\tconfidence: number;\n\treason?: string;\n\toriginal: unknown;\n};\n\n/** Options for {@link contentModerationGraph}. */\nexport type ContentModerationGraphOptions = GraphOptions & {\n\t/** Content source (text/multimedia ingest). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Classification function: returns a ModerationResult.\n\t * Default: labels everything \"review\" with confidence 0.5.\n\t */\n\tclassify?: (content: unknown) => ModerationResult;\n\n\t/** System prompt for LLM classification. */\n\tsystemPrompt?: string;\n\n\t/** Scorer weights: [safe, review, block]. Default: [0.1, 1, 2]. */\n\tweights?: [number, number, number];\n\n\t/** Max feedback iterations for policy refinement. Default: 5. */\n\tmaxFeedbackIterations?: number;\n\n\t/** Max review queue size. When set, oldest entries are trimmed on overflow. */\n\tmaxQueueSize?: number;\n};\n\n/**\n * Content ingest → LLM/rule classification → stratified routing (safe/review/block) →\n * human review queue → scorer → feedback (false positives → policy refinement) → output.\n *\n * Well-known node names:\n * - `\"source\"` — content ingest\n * - `\"classify\"` — LLM or rule-based classification\n * - `\"stratify::branch/safe\"`, `\"stratify::branch/review\"`, `\"stratify::branch/block\"` — routed branches\n * - `\"review_queue\"` — state node for human review items\n * - `\"priority\"` — scored priority output\n * - `\"policy\"` — writable state for policy refinement\n * - `\"output\"` — final moderation output\n *\n * @category patterns\n */\nexport function contentModerationGraph(name: string, opts: ContentModerationGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Classify ---\n\tconst defaultClassify = (content: unknown): ModerationResult => ({\n\t\tlabel: \"review\",\n\t\tconfidence: 0.5,\n\t\toriginal: content,\n\t});\n\tconst classifyFn = opts.classify ?? defaultClassify;\n\tconst classifyNode = derived<ModerationResult>([opts.source], (vals) => classifyFn(vals[0]), {\n\t\tmeta: baseMeta(\"content_moderation\", { stage: \"classify\" }),\n\t});\n\tg.add(\"classify\", classifyNode as Node<unknown>);\n\n\t// --- Stratify (safe / review / block) ---\n\tconst strat = stratify<ModerationResult>(\"stratify\", classifyNode, [\n\t\t{ name: \"safe\", classify: (v) => v.label === \"safe\" },\n\t\t{ name: \"review\", classify: (v) => v.label === \"review\" },\n\t\t{ name: \"block\", classify: (v) => v.label === \"block\" },\n\t]);\n\tg.mount(\"stratify\", strat);\n\n\t// --- Review queue (reactiveLog — O(1) append, bounded) ---\n\tconst reviewLog = reactiveLog<ModerationResult>([], {\n\t\tname: \"review_queue\",\n\t\tmaxSize: opts.maxQueueSize,\n\t});\n\tg.add(\"review_queue\", reviewLog.entries as Node<unknown>);\n\n\t// Bridge review branch → review queue accumulator\n\tlet reviewBranch: Node<unknown>;\n\ttry {\n\t\treviewBranch = g.resolve(\"stratify::branch/review\");\n\t} catch {\n\t\treviewBranch = state<unknown>(null);\n\t\tg.add(\"__review_fallback\", reviewBranch);\n\t}\n\tconst reviewAccumulator = effect([reviewBranch], (vals) => {\n\t\tconst item = vals[0] as ModerationResult | null;\n\t\tif (item) {\n\t\t\treviewLog.append(item);\n\t\t}\n\t});\n\tg.add(\"__review_accumulator\", reviewAccumulator as Node<unknown>);\n\tg.addDisposer(keepalive(reviewAccumulator as Node<unknown>));\n\ttry {\n\t} catch {\n\t\t// fallback branch — no stratify edge to register\n\t}\n\n\t// --- Policy state (human/LLM writable) ---\n\tconst policy = state<Record<string, unknown>>(\n\t\t{},\n\t\t{\n\t\t\tmeta: baseMeta(\"content_moderation\", {\n\t\t\t\tstage: \"policy\",\n\t\t\t\taccess: \"both\",\n\t\t\t\tdescription: \"Moderation policy rules — updated via feedback\",\n\t\t\t}),\n\t\t},\n\t);\n\tg.add(\"policy\", policy as Node<unknown>);\n\n\t// --- Priority scorer ---\n\tconst weights = opts.weights ?? [0.1, 1, 2];\n\tconst confidenceSignal = derived<number>([classifyNode as Node], (vals) => {\n\t\tconst r = vals[0] as ModerationResult | null;\n\t\treturn r?.confidence ?? 0;\n\t});\n\tconst severitySignal = derived<number>([classifyNode as Node], (vals) => {\n\t\tconst r = vals[0] as ModerationResult | null;\n\t\tif (!r) return 0;\n\t\treturn r.label === \"block\" ? weights[2] : r.label === \"review\" ? weights[1] : weights[0];\n\t});\n\tg.add(\"__confidence_signal\", confidenceSignal as Node<unknown>);\n\tg.add(\"__severity_signal\", severitySignal as Node<unknown>);\n\n\tconst wConfidence = state<number>(1);\n\tconst wSeverity = state<number>(1);\n\tg.add(\"__w_confidence\", wConfidence as Node<unknown>);\n\tg.add(\"__w_severity\", wSeverity as Node<unknown>);\n\n\tconst priority = scorer([confidenceSignal, severitySignal], [wConfidence, wSeverity]);\n\tg.add(\"priority\", priority as Node<unknown>);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[classifyNode as Node, priority as Node],\n\t\t(vals) => ({\n\t\t\tclassification: vals[0],\n\t\t\tpriority: vals[1],\n\t\t}),\n\t\t{ meta: baseMeta(\"content_moderation\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (false positive → policy refinement) ---\n\t// Feedback condition: human marks a review item as false positive.\n\t// When review_queue changes and policy exists, signal for update.\n\tconst fbCondition = derived<unknown>(\n\t\t[reviewLog.entries as Node, policy as Node],\n\t\t(vals) => {\n\t\t\tconst entries = vals[0] as readonly ModerationResult[] | null;\n\t\t\tif (entries && entries.length > 0) {\n\t\t\t\tconst latest = entries[entries.length - 1];\n\t\t\t\t// Items explicitly marked as false positive feed back\n\t\t\t\tif (latest && (latest as unknown as Record<string, unknown>).falsePositive) {\n\t\t\t\t\treturn latest;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"content_moderation\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"policy\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 5,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 4. dataQualityGraph\n// ---------------------------------------------------------------------------\n\n/** Schema validation result. */\nexport type ValidationResult = {\n\tvalid: boolean;\n\terrors: string[];\n\trecord: unknown;\n};\n\n/** Anomaly detection result. */\nexport type AnomalyResult = {\n\tanomaly: boolean;\n\tscore: number;\n\tdetail?: string;\n\trecord: unknown;\n};\n\n/** Options for {@link dataQualityGraph}. */\nexport type DataQualityGraphOptions = GraphOptions & {\n\t/** Data source (e.g. fromPrisma(...), fromKysely(...)). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Schema validation function.\n\t * Default: always valid.\n\t */\n\tvalidate?: (record: unknown) => ValidationResult;\n\n\t/**\n\t * Anomaly detection function.\n\t * Default: no anomaly.\n\t */\n\tdetectAnomaly?: (record: unknown) => AnomalyResult;\n\n\t/**\n\t * Drift detection: compares current record against baseline.\n\t * Default: no drift.\n\t */\n\tdetectDrift?: (record: unknown, baseline: unknown) => unknown;\n\n\t/**\n\t * Remediation suggestion function.\n\t * Default: no suggestion.\n\t */\n\tsuggest?: (result: { validation: ValidationResult; anomaly: AnomalyResult }) => unknown;\n\n\t/** Max feedback iterations for rule refinement. Default: 3. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * Data ingest → schema validation → anomaly detection → drift alerting →\n * auto-remediation suggestions → output.\n *\n * Well-known node names:\n * - `\"source\"` — data ingest\n * - `\"validate\"` — schema validation\n * - `\"anomaly\"` — anomaly detection\n * - `\"baseline\"` — rolling baseline state\n * - `\"drift\"` — drift detection\n * - `\"remediate\"` — auto-remediation suggestions\n * - `\"output\"` — combined quality report\n *\n * @category patterns\n */\nexport function dataQualityGraph(name: string, opts: DataQualityGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Schema validation ---\n\tconst validateFn =\n\t\topts.validate ??\n\t\t((record: unknown): ValidationResult => ({\n\t\t\tvalid: true,\n\t\t\terrors: [],\n\t\t\trecord,\n\t\t}));\n\tconst validateNode = derived<ValidationResult | undefined>(\n\t\t[opts.source],\n\t\t(vals) => (vals[0] != null ? validateFn(vals[0]) : undefined),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"validate\" }) },\n\t);\n\tg.add(\"validate\", validateNode as Node<unknown>);\n\n\t// --- Anomaly detection ---\n\tconst detectAnomalyFn =\n\t\topts.detectAnomaly ??\n\t\t((record: unknown): AnomalyResult => ({\n\t\t\tanomaly: false,\n\t\t\tscore: 0,\n\t\t\trecord,\n\t\t}));\n\tconst anomalyNode = derived<AnomalyResult | undefined>(\n\t\t[opts.source],\n\t\t(vals) => (vals[0] != null ? detectAnomalyFn(vals[0]) : undefined),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"anomaly\" }) },\n\t);\n\tg.add(\"anomaly\", anomalyNode as Node<unknown>);\n\n\t// --- Baseline (rolling state) ---\n\tconst baseline = state<unknown>(null, {\n\t\tmeta: baseMeta(\"data_quality\", {\n\t\t\tstage: \"baseline\",\n\t\t\tdescription: \"Rolling baseline for drift detection\",\n\t\t}),\n\t});\n\tg.add(\"baseline\", baseline);\n\n\t// Update baseline on valid records\n\tconst baselineUpdater = effect([validateNode as Node], (vals) => {\n\t\tconst result = vals[0] as ValidationResult;\n\t\tif (result?.valid) {\n\t\t\tbatch(() => {\n\t\t\t\tbaseline.down([[DATA, result.record]]);\n\t\t\t});\n\t\t}\n\t});\n\tg.add(\"__baseline_updater\", baselineUpdater as Node<unknown>);\n\tkeepalive(baselineUpdater as Node<unknown>);\n\n\t// --- Drift detection ---\n\tconst detectDriftFn = opts.detectDrift ?? (() => ({ drift: false }));\n\tconst driftNode = derived<unknown>(\n\t\t[opts.source, baseline],\n\t\t(vals) => detectDriftFn(vals[0], vals[1]),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"drift\" }) },\n\t);\n\tg.add(\"drift\", driftNode);\n\n\t// --- Remediation suggestions ---\n\tconst suggestFn = opts.suggest ?? (() => null);\n\tconst remediateNode = derived<unknown>(\n\t\t[validateNode as Node, anomalyNode as Node],\n\t\t(vals) =>\n\t\t\tsuggestFn({\n\t\t\t\tvalidation: vals[0] as ValidationResult,\n\t\t\t\tanomaly: vals[1] as AnomalyResult,\n\t\t\t}),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"remediate\" }) },\n\t);\n\tg.add(\"remediate\", remediateNode);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[validateNode as Node, anomalyNode as Node, driftNode, remediateNode],\n\t\t(vals) => ({\n\t\t\tvalidation: vals[0],\n\t\t\tanomaly: vals[1],\n\t\t\tdrift: vals[2],\n\t\t\tremediation: vals[3],\n\t\t}),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (anomaly → validation rule refinement) ---\n\tconst validationRules = state<unknown[]>([], {\n\t\tmeta: baseMeta(\"data_quality\", { stage: \"validation_rules\" }),\n\t});\n\tg.add(\"validation_rules\", validationRules as Node<unknown>);\n\n\tconst fbCondition = derived<unknown>(\n\t\t[anomalyNode as Node],\n\t\t(vals) => {\n\t\t\tconst a = vals[0] as AnomalyResult | null;\n\t\t\tif (a?.anomaly) return a;\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"data_quality\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"validation_rules\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 3,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Check if a value has a `type` or `kind` tag matching the given label. */\nfunction isTagged(value: unknown, tag: string): boolean {\n\tif (value == null || typeof value !== \"object\") return false;\n\tconst v = value as Record<string, unknown>;\n\treturn v.type === tag || v.kind === tag;\n}\n","/**\n * Reduction primitives (roadmap §8.1).\n *\n * Composable building blocks for taking heterogeneous massive inputs and producing\n * prioritized, auditable, human-actionable output. Each primitive is either a Graph\n * factory or a Node factory, built on top of core + extra primitives.\n *\n * @module\n */\n\nimport { batch } from \"../core/batch.js\";\nimport type { NodeActions } from \"../core/config.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\ttype Message,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport { type Node, type NodeOptions, node } from \"../core/node.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { merge } from \"../extra/operators.js\";\nimport { reactiveMap } from \"../extra/reactive-map.js\";\nimport { Graph, type GraphOptions } from \"../graph/graph.js\";\n\n// ---------------------------------------------------------------------------\n// Shared helpers (same pattern as orchestration.ts)\n// ---------------------------------------------------------------------------\n\nexport type StepRef = string | Node<unknown>;\n\nimport { domainMeta, keepalive, tryIncrementBounded } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"reduction\", kind, meta);\n}\n\n// ---------------------------------------------------------------------------\n// stratify\n// ---------------------------------------------------------------------------\n\n/** A single routing rule for {@link stratify}. */\nexport type StratifyRule<T> = {\n\t/** Branch name (used as node name under `branch/<name>`). */\n\tname: string;\n\t/** Classifier: returns `true` if the value belongs to this branch. */\n\tclassify: (value: T) => boolean;\n\t/** Optional operator chain applied to the branch after classification. */\n\tops?: (n: Node<T>) => Node;\n};\n\n/** Options for {@link stratify}. */\nexport type StratifyOptions = GraphOptions & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Route input to different reduction branches based on classifier functions.\n *\n * Each branch gets an independent operator chain. Rules are reactive — update\n * the `\"rules\"` state node to rewrite classification at runtime. Rule updates\n * affect **future items only** (streaming classification, not retroactive).\n *\n * Branch nodes are structural — created at construction time and persist for\n * the graph's lifetime. If a rule name is removed from the rules array, the\n * corresponding branch silently drops items (classifier not found). To tear\n * down a dead branch, call `graph.remove(\"branch/<name>\")`.\n *\n * @param name - Graph name.\n * @param source - Input node (registered externally or will be added as `\"source\"`).\n * @param rules - Initial routing rules.\n * @param opts - Optional graph/meta options.\n * @returns Graph with `\"source\"`, `\"rules\"`, and `\"branch/<name>\"` nodes.\n *\n * @category patterns\n */\nexport function stratify<T>(\n\tname: string,\n\tsource: Node<T>,\n\trules: ReadonlyArray<StratifyRule<T>>,\n\topts?: StratifyOptions,\n): Graph {\n\tconst g = new Graph(name, opts);\n\n\tg.add(\"source\", source as Node<unknown>);\n\tconst rulesNode = state<ReadonlyArray<StratifyRule<T>>>(rules, {\n\t\tmeta: baseMeta(\"stratify_rules\"),\n\t});\n\tg.add(\"rules\", rulesNode as Node<unknown>);\n\n\tfor (const rule of rules) {\n\t\t_addBranch(g, source, rulesNode, rule);\n\t}\n\n\treturn g;\n}\n\nfunction _addBranch<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\trulesNode: Node<ReadonlyArray<StratifyRule<T>>>,\n\trule: StratifyRule<T>,\n): void {\n\tconst branchName = `branch/${rule.name}`;\n\n\t// Two-dep gating: intercepts messages from BOTH source (dep 0) and rules\n\t// (dep 1). Classification is deferred until all dirty deps have settled,\n\t// eliminating the stale-rules race when both are updated in the same batch().\n\t//\n\t// Protocol: DIRTY is buffered until DATA arrives. If the classifier matches,\n\t// emit [DIRTY, DATA]. If not, emit [DIRTY, RESOLVED] so downstream exits\n\t// dirty status cleanly (spec §1.3.1). Source RESOLVED forwards as RESOLVED.\n\t// Rules-only changes produce no downstream emission (\"future items only\").\n\t//\n\t// Producer pattern with `[]` deps: the framework does NOT auto-propagate\n\t// DIRTY/RESOLVED/COMPLETE from source or rules. We forward source terminals\n\t// explicitly below, and we silently absorb rules signals — preserving the\n\t// \"future items only\" semantic (rules changes are invisible downstream).\n\tconst _noValue: unique symbol = Symbol(\"noValue\");\n\tlet sourceDirty = false;\n\tlet rulesDirty = false;\n\tlet sourcePhase2 = false; // source delivered DATA or RESOLVED this cycle\n\tlet sourceValue: T | typeof _noValue = _noValue; // DATA payload, or _noValue for RESOLVED\n\tlet pendingDirty = false; // owe downstream a DIRTY\n\t// Latest rules DATA, seeded at factory time (wiring-time external read —\n\t// allowed per foundation-redesign §3.6). Updated by the rules subscribe\n\t// handler so `resolve()` never reads `rulesNode.cache` from a reactive context.\n\tlet latestRules: ReadonlyArray<StratifyRule<T>> = rulesNode.cache ?? [];\n\n\tfunction resolve(actions: NodeActions): void {\n\t\tif (sourcePhase2) {\n\t\t\tsourcePhase2 = false;\n\t\t\tconst value = sourceValue;\n\t\t\tsourceValue = _noValue;\n\t\t\tif (value !== _noValue) {\n\t\t\t\t// Source emitted DATA — classify with settled rules\n\t\t\t\tconst currentRule = latestRules.find((r) => r.name === rule.name);\n\t\t\t\tlet matches = false;\n\t\t\t\ttry {\n\t\t\t\t\tmatches = currentRule?.classify(value) ?? false;\n\t\t\t\t} catch {\n\t\t\t\t\tmatches = false;\n\t\t\t\t}\n\t\t\t\tif (matches) {\n\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\tactions.emit(value);\n\t\t\t\t} else {\n\t\t\t\t\tif (pendingDirty) {\n\t\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\t\tactions.down([[DIRTY], [RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Source RESOLVED (unchanged)\n\t\t\t\tif (pendingDirty) {\n\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\tactions.down([[DIRTY], [RESOLVED]]);\n\t\t\t\t} else {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// else: rules-only change — no reclassification (\"future items only\")\n\t}\n\n\t// Producer pattern: manually subscribe to source and rules for per-message\n\t// interception (onMessage removed in v5)\n\tconst filterNode = node<T>(\n\t\t[],\n\t\t(_data, filterActions) => {\n\t\t\tconst srcUnsub = (source as Node).subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t_handleStratifyMessage(msg, 0, filterActions);\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst rulesUnsub = (rulesNode as Node).subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t_handleStratifyMessage(msg, 1, filterActions);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsrcUnsub();\n\t\t\t\trulesUnsub();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"stratify_branch\", { branch: rule.name }),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t},\n\t);\n\n\tfunction _handleStratifyMessage(msg: Message, depIndex: number, actions: NodeActions): boolean {\n\t\tconst t = msg[0];\n\n\t\t// --- DIRTY (phase 1) ---\n\t\tif (t === DIRTY) {\n\t\t\tif (depIndex === 0) {\n\t\t\t\tsourceDirty = true;\n\t\t\t\tpendingDirty = true;\n\t\t\t} else {\n\t\t\t\trulesDirty = true;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// --- Phase 2 (DATA / RESOLVED) ---\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (depIndex === 0) {\n\t\t\t\tsourceDirty = false;\n\t\t\t\tsourcePhase2 = true;\n\t\t\t\tsourceValue = t === DATA ? (msg[1] as T) : _noValue;\n\t\t\t} else {\n\t\t\t\t// Rules dep: capture DATA payload into closure before settling.\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tlatestRules = msg[1] as ReadonlyArray<StratifyRule<T>>;\n\t\t\t\t}\n\t\t\t\trulesDirty = false;\n\t\t\t}\n\n\t\t\t// Wait for all dirty deps to settle\n\t\t\tif (sourceDirty || rulesDirty) return true;\n\n\t\t\tresolve(actions);\n\t\t\treturn true;\n\t\t}\n\n\t\t// --- Terminal ---\n\t\tif (t === COMPLETE || t === ERROR || t === TEARDOWN) {\n\t\t\tsourceDirty = false;\n\t\t\trulesDirty = false;\n\t\t\tsourcePhase2 = false;\n\t\t\tsourceValue = _noValue;\n\t\t\tpendingDirty = false;\n\t\t\tif (depIndex === 0) {\n\t\t\t\tactions.down([msg]);\n\t\t\t}\n\t\t\t// Rules terminal: swallow (branch stays alive)\n\t\t\treturn true;\n\t\t}\n\n\t\t// Swallow PAUSE/RESUME/INVALIDATE from rules dep (internal impl detail)\n\t\tif (depIndex === 1) return true;\n\n\t\treturn false;\n\t}\n\n\tgraph.add(branchName, filterNode as Node<unknown>);\n\n\t// If the rule has an ops chain, apply it and connect the edge\n\tif (rule.ops) {\n\t\tconst transformed = rule.ops(filterNode);\n\t\tconst transformedName = `branch/${rule.name}/out`;\n\t\tgraph.add(transformedName, transformed as Node<unknown>);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// funnel\n// ---------------------------------------------------------------------------\n\n/** A named stage for {@link funnel}. */\nexport type FunnelStage = {\n\t/** Stage name (mounted as subgraph). */\n\tname: string;\n\t/** Builder: receives a sub-graph, should add an `\"input\"` and `\"output\"` node. */\n\tbuild: (sub: Graph) => void;\n};\n\n/** Options for {@link funnel}. */\nexport type FunnelOptions = GraphOptions & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Multi-source merge with sequential reduction stages.\n *\n * Sources are merged into a single stream. Each stage is a named subgraph\n * (mounted via `graph.mount()`). Stages connect linearly:\n * `merged → stage[0].input → stage[0].output → stage[1].input → ...`\n *\n * @param name - Graph name.\n * @param sources - Input nodes to merge.\n * @param stages - Sequential reduction stages.\n * @param opts - Optional graph/meta options.\n * @returns Graph with `\"merged\"` and mounted stage subgraphs.\n *\n * @category patterns\n */\nexport function funnel<T>(\n\tname: string,\n\tsources: ReadonlyArray<Node<T>>,\n\tstages: ReadonlyArray<FunnelStage>,\n\topts?: FunnelOptions,\n): Graph {\n\tif (sources.length === 0) throw new RangeError(\"funnel requires at least one source\");\n\tif (stages.length === 0) throw new RangeError(\"funnel requires at least one stage\");\n\n\tconst g = new Graph(name, opts);\n\n\t// Merge all sources\n\tconst merged = sources.length === 1 ? sources[0] : merge(...(sources as unknown as Node<T>[]));\n\tg.add(\"merged\", merged as Node<unknown>);\n\n\t// Build and mount each stage linearly.\n\t// Stage inputs are standalone state nodes, so we bridge via subscribe\n\t// (connect() requires constructor deps). Bridge effects forward DATA\n\t// from the previous output to the next stage's input.\n\tlet prevOutputPath = \"merged\";\n\tfor (let i = 0; i < stages.length; i++) {\n\t\tconst stage = stages[i];\n\t\tconst sub = new Graph(stage.name);\n\t\tstage.build(sub);\n\n\t\t// Validate that the stage has input and output nodes\n\t\ttry {\n\t\t\tsub.resolve(\"input\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"input\" node`);\n\t\t}\n\t\ttry {\n\t\t\tsub.resolve(\"output\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"output\" node`);\n\t\t}\n\n\t\tg.mount(stage.name, sub);\n\n\t\t// Bridge replacement: effect that forwards DATA from previous output\n\t\t// to the next stage's input. TEARDOWN excluded because stage lifecycle\n\t\t// is managed by the parent graph. Shows up in describe().\n\t\tconst prevNode = g.resolve(prevOutputPath);\n\t\tconst stageInputPath = `${stage.name}::input`;\n\t\tconst stageInput = g.resolve(stageInputPath);\n\t\tconst bridgeName = `__bridge_${prevOutputPath}→${stage.name}_input`;\n\t\tconst br = effect(\n\t\t\t[prevNode],\n\t\t\t([data]) => {\n\t\t\t\tstageInput.down([[DATA, data]]);\n\t\t\t},\n\t\t\t{ name: bridgeName },\n\t\t);\n\t\tg.add(bridgeName, br as Node<unknown>);\n\t\tg.addDisposer(keepalive(br));\n\n\t\tprevOutputPath = `${stage.name}::output`;\n\t}\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// feedback\n// ---------------------------------------------------------------------------\n\n/** Options for {@link feedback}. */\nexport type FeedbackOptions = {\n\t/** Maximum feedback iterations before stopping (default: 10). */\n\tmaxIterations?: number;\n\t/** Optional budget gate node path for cost-bounded iteration. */\n\tbudgetNode?: StepRef;\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Introduce a bounded reactive cycle into an existing graph.\n *\n * When `condition` emits a non-null DATA value, the feedback effect routes it\n * back to the `reentry` state node — creating a cycle. Bounded by\n * `maxIterations` (default 10). The counter node (`__feedback_<condition>`)\n * is the source of truth — reset it to 0 to allow more iterations.\n *\n * To remove the feedback cycle, call `graph.remove(\"__feedback_<condition>\")`.\n *\n * @param graph - Existing graph to augment with a feedback cycle.\n * @param condition - Path to a node whose DATA triggers feedback.\n * @param reentry - Path to a state node that receives the feedback value.\n * @param opts - Iteration bounds and metadata.\n * @returns The same graph (mutated with feedback nodes added).\n *\n * @category patterns\n */\nexport function feedback(\n\tgraph: Graph,\n\tcondition: string,\n\treentry: string,\n\topts?: FeedbackOptions,\n): Graph {\n\tconst maxIter = opts?.maxIterations ?? 10;\n\n\t// Internal counter node — source of truth for iteration bound.\n\t// Reset to 0 to allow more iterations.\n\tconst counterName = `__feedback_${condition}`;\n\tconst counter = state<number>(0, {\n\t\tmeta: baseMeta(\"feedback_counter\", {\n\t\t\tmaxIterations: maxIter,\n\t\t\tfeedbackFrom: condition,\n\t\t\tfeedbackTo: reentry,\n\t\t}),\n\t});\n\tgraph.add(counterName, counter as Node<unknown>);\n\n\t// Resolve the condition and reentry nodes\n\tconst condNode = graph.resolve(condition);\n\tconst reentryNode = graph.resolve(reentry);\n\n\t// Graph-visible feedback effect: intercepts condition DATA, routes back to\n\t// reentry with iteration counting. Registered in the graph so it shows up\n\t// in describe() and cleans up on graph.destroy().\n\t// Feedback effect: subscribe to condition node for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\tconst feedbackEffectName = `__feedback_effect_${condition}`;\n\tconst feedbackEffect = node(\n\t\t[],\n\t\t(_data, _feedbackActions) => {\n\t\t\tconst unsub = condNode.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tconst t = msg[0];\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tconst condValue = msg[1];\n\t\t\t\t\t\tif (condValue == null) return;\n\t\t\t\t\t\tbatch(() => {\n\t\t\t\t\t\t\tif (tryIncrementBounded(counter, maxIter)) {\n\t\t\t\t\t\t\t\treentryNode.down([[DATA, condValue]]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (t === COMPLETE || t === ERROR) {\n\t\t\t\t\t\tconst terminal: Message = t === ERROR && msg.length > 1 ? [ERROR, msg[1]] : [t];\n\t\t\t\t\t\tcounter.down([terminal]);\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\t{\n\t\t\tname: feedbackEffectName,\n\t\t\tdescribeKind: \"effect\",\n\t\t\tmeta: {\n\t\t\t\t...baseMeta(\"feedback_effect\", {\n\t\t\t\t\tfeedbackFrom: condition,\n\t\t\t\t\tfeedbackTo: reentry,\n\t\t\t\t}),\n\t\t\t\t_internal: true,\n\t\t\t},\n\t\t},\n\t);\n\tgraph.add(feedbackEffectName, feedbackEffect as Node<unknown>);\n\tgraph.addDisposer(keepalive(feedbackEffect));\n\n\treturn graph;\n}\n\n// ---------------------------------------------------------------------------\n// budgetGate\n// ---------------------------------------------------------------------------\n\n/** A reactive constraint for {@link budgetGate}. */\nexport type BudgetConstraint<T = unknown> = {\n\t/** Constraint node whose value is checked. */\n\tnode: Node<T>;\n\t/** Returns `true` when the constraint is satisfied (budget available). */\n\tcheck: (value: T) => boolean;\n};\n\n/** Options for {@link budgetGate}. */\nexport type BudgetGateOptions = Omit<NodeOptions<unknown>, \"describeKind\" | \"name\" | \"meta\"> & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Pass-through that respects reactive constraint nodes.\n *\n * DATA flows through when all constraints are satisfied. When any constraint\n * is exceeded, PAUSE is sent upstream and DATA is buffered. When constraints\n * relax, RESUME is sent and buffered DATA flushes.\n *\n * @param source - Input node.\n * @param constraints - Reactive constraint checks.\n * @param opts - Optional node options.\n * @returns Gated node.\n *\n * @category patterns\n */\nexport function budgetGate<T>(\n\tsource: Node<T>,\n\tconstraints: ReadonlyArray<BudgetConstraint>,\n\topts?: BudgetGateOptions,\n): Node<T> {\n\tif (constraints.length === 0) throw new RangeError(\"budgetGate requires at least one constraint\");\n\n\tconst constraintNodes = constraints.map((c) => c.node);\n\tconst allDeps = [source as Node, ...constraintNodes] as Node[];\n\n\tlet buffer: T[] = [];\n\tlet paused = false;\n\tlet pendingResolved = false;\n\tconst lockId = Symbol(\"budget-gate\");\n\n\t// Latest DATA from each constraint. Seeded at **activation time** (inside the\n\t// producer fn below) — a wiring-time boundary read, not a reactive-callback\n\t// read — so concurrent constraint updates between factory-time and\n\t// activation-time are reflected before `checkBudget()` first runs. The\n\t// subscribe handler updates this array on each constraint DATA message, so\n\t// `checkBudget` never reads `.cache` from inside a reactive callback.\n\tconst latestValues: unknown[] = new Array(constraints.length);\n\n\tfunction checkBudget(): boolean {\n\t\treturn constraints.every((c, i) => c.check(latestValues[i]));\n\t}\n\n\tfunction flushBuffer(actions: NodeActions): void {\n\t\twhile (buffer.length > 0 && checkBudget()) {\n\t\t\tconst item = buffer[0]!;\n\t\t\tbuffer = buffer.slice(1);\n\t\t\tactions.emit(item);\n\t\t}\n\t\t// Drain deferred RESOLVED once buffer is empty\n\t\tif (buffer.length === 0 && pendingResolved) {\n\t\t\tpendingResolved = false;\n\t\t\tactions.down([[RESOLVED]]);\n\t\t}\n\t}\n\n\t// Producer pattern: manually subscribe to all deps for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\treturn node<T>(\n\t\t[],\n\t\t(_data, gateActions) => {\n\t\t\t// Seed `latestValues` at activation (not factory time) so any constraint\n\t\t\t// updates between factory return and first subscribe are captured before\n\t\t\t// source's push-on-subscribe fires `checkBudget()`.\n\t\t\tfor (let i = 0; i < constraints.length; i++) {\n\t\t\t\tlatestValues[i] = constraints[i]!.node.cache;\n\t\t\t}\n\t\t\tconst unsubs: Array<() => void> = [];\n\t\t\tfor (let depIdx = 0; depIdx < allDeps.length; depIdx++) {\n\t\t\t\tconst dep = allDeps[depIdx];\n\t\t\t\tunsubs.push(\n\t\t\t\t\tdep.subscribe((msgs) => {\n\t\t\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t\t\t_handleBudgetMessage(msg, depIdx, gateActions);\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\treturn () => {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"budget_gate\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\n\tfunction _handleBudgetMessage(msg: Message, depIndex: number, actions: NodeActions): boolean {\n\t\tconst t = msg[0];\n\n\t\t// Source messages (dep 0)\n\t\tif (depIndex === 0) {\n\t\t\tif (t === DATA) {\n\t\t\t\tif (checkBudget() && buffer.length === 0) {\n\t\t\t\t\tactions.emit(msg[1] as T);\n\t\t\t\t} else {\n\t\t\t\t\tbuffer.push(msg[1] as T);\n\t\t\t\t\tif (!paused) {\n\t\t\t\t\t\tpaused = true;\n\t\t\t\t\t\tactions.up([[PAUSE, lockId]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tactions.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\tif (buffer.length === 0) {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t} else {\n\t\t\t\t\t// Buffer non-empty: defer RESOLVED until buffer drains\n\t\t\t\t\tpendingResolved = true;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\t// Force-flush all buffered items regardless of budget (terminal = done)\n\t\t\t\tfor (const item of buffer) {\n\t\t\t\t\tactions.emit(item);\n\t\t\t\t}\n\t\t\t\tbuffer = [];\n\t\t\t\tpendingResolved = false;\n\t\t\t\t// Release PAUSE lock before forwarding terminal\n\t\t\t\tif (paused) {\n\t\t\t\t\tpaused = false;\n\t\t\t\t\tactions.up([[RESUME, lockId]]);\n\t\t\t\t}\n\t\t\t\tactions.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Constraint node messages (dep 1+): capture DATA then re-check budget\n\t\tif (t === DATA) {\n\t\t\tlatestValues[depIndex - 1] = msg[1];\n\t\t}\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (checkBudget() && buffer.length > 0) {\n\t\t\t\tflushBuffer(actions);\n\t\t\t\tif (buffer.length === 0 && paused) {\n\t\t\t\t\tpaused = false;\n\t\t\t\t\tactions.up([[RESUME, lockId]]);\n\t\t\t\t}\n\t\t\t} else if (!checkBudget() && !paused && buffer.length > 0) {\n\t\t\t\tpaused = true;\n\t\t\t\tactions.up([[PAUSE, lockId]]);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (t === DIRTY) {\n\t\t\t// Don't propagate constraint DIRTY downstream\n\t\t\treturn true;\n\t\t}\n\t\tif (t === ERROR) {\n\t\t\t// Constraint error → forward downstream\n\t\t\tactions.down([msg]);\n\t\t\treturn true;\n\t\t}\n\t\tif (t === COMPLETE) {\n\t\t\t// Constraint completed — locked at last value, no-op\n\t\t\treturn true;\n\t\t}\n\t\t// Unknown constraint types → default forwarding\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// scorer\n// ---------------------------------------------------------------------------\n\n/** A scored item with full breakdown. */\nexport type ScoredItem<T = unknown> = {\n\t/** Original value. */\n\tvalue: T;\n\t/** Final weighted score. */\n\tscore: number;\n\t/** Per-signal breakdown: signal index → weighted contribution. */\n\tbreakdown: number[];\n};\n\n/** Options for {@link scorer}. */\nexport type ScorerOptions = Omit<NodeOptions<unknown>, \"describeKind\" | \"name\" | \"meta\"> & {\n\tmeta?: Record<string, unknown>;\n\t/** Custom scoring function per signal. Default: identity (signal value IS the score). */\n\tscoreFns?: ReadonlyArray<(value: unknown) => number>;\n};\n\n/**\n * Reactive multi-signal scoring with live weights.\n *\n * Each source emits items to score. Weights are reactive state nodes that\n * LLM or human can adjust live. Output is sorted scored items with full\n * breakdown.\n *\n * @param sources - Signal nodes (each emits a numeric score dimension).\n * @param weights - Reactive weight nodes (one per source).\n * @param opts - Optional node/meta options.\n * @returns Node emitting scored output.\n *\n * @category patterns\n */\nexport function scorer(\n\tsources: ReadonlyArray<Node<number>>,\n\tweights: ReadonlyArray<Node<number>>,\n\topts?: ScorerOptions,\n): Node<ScoredItem<number[]>> {\n\tif (sources.length === 0) throw new RangeError(\"scorer requires at least one source\");\n\tif (sources.length !== weights.length) {\n\t\tthrow new RangeError(\"scorer requires the same number of sources and weights\");\n\t}\n\n\tconst allDeps = [...(sources as unknown as Node[]), ...(weights as unknown as Node[])];\n\tconst n = sources.length;\n\tconst scoreFns = opts?.scoreFns;\n\n\treturn derived<ScoredItem<number[]>>(\n\t\tallDeps,\n\t\t(vals) => {\n\t\t\tconst signals = vals.slice(0, n) as number[];\n\t\t\tconst weightValues = vals.slice(n) as number[];\n\n\t\t\tconst breakdown: number[] = [];\n\t\t\tlet totalScore = 0;\n\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tconst sig = signals[i] ?? 0;\n\t\t\t\tconst wt = weightValues[i] ?? 0;\n\t\t\t\tconst rawScore = scoreFns?.[i] ? scoreFns[i](sig) : sig;\n\t\t\t\tconst weighted = (rawScore as number) * wt;\n\t\t\t\tbreakdown.push(weighted);\n\t\t\t\ttotalScore += weighted;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tvalue: signals,\n\t\t\t\tscore: totalScore,\n\t\t\t\tbreakdown,\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...(opts\n\t\t\t\t? {\n\t\t\t\t\t\tequals: opts.equals,\n\t\t\t\t\t\tresubscribable: opts.resubscribable,\n\t\t\t\t\t\tresetOnTeardown: opts.resetOnTeardown,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"scorer\", opts?.meta),\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// effectivenessTracker\n// ---------------------------------------------------------------------------\n\n/** A single effectiveness record for an action×context pair. */\nexport type EffectivenessEntry = {\n\treadonly key: string;\n\treadonly attempts: number;\n\treadonly successes: number;\n\treadonly successRate: number;\n};\n\n/** Snapshot shape for the effectiveness tracker node. */\nexport type EffectivenessSnapshot = ReadonlyMap<string, EffectivenessEntry>;\n\n/** Bundle returned by {@link effectivenessTracker}. */\nexport interface EffectivenessTrackerBundle {\n\t/** Reactive node — current effectiveness map snapshot. */\n\treadonly node: Node<EffectivenessSnapshot>;\n\n\t/** Record a completed action (success or failure). */\n\trecord(key: string, success: boolean): void;\n\n\t/** Look up effectiveness for a specific key. */\n\tlookup(key: string): EffectivenessEntry | undefined;\n\n\t/** Tear down internal keepalive subscriptions. */\n\tdispose(): void;\n}\n\n/** Options for {@link effectivenessTracker}. */\nexport type EffectivenessTrackerOptions = {\n\t/** Name for the reactive map (default \"effectiveness-entries\"). */\n\tname?: string;\n};\n\n/**\n * Generic action×context → success rate tracker.\n *\n * Generalized from the harness `strategyModel` pattern. Tracks attempts and\n * successes per string key, exposes a reactive snapshot node, and provides\n * `record()` / `lookup()` methods.\n *\n * Use cases: A/B testing, routing optimization, cache policy tuning, retry\n * strategy selection — any domain that tracks effectiveness per action.\n *\n * @param opts - Optional configuration.\n * @returns Bundle with reactive node, record(), lookup(), dispose().\n */\nexport function effectivenessTracker(\n\topts?: EffectivenessTrackerOptions,\n): EffectivenessTrackerBundle {\n\tconst _map = reactiveMap<string, EffectivenessEntry>({\n\t\tname: opts?.name ?? \"effectiveness-entries\",\n\t});\n\n\tconst snapshot = derived<EffectivenessSnapshot>(\n\t\t[_map.entries],\n\t\t([mapSnap]) => {\n\t\t\treturn new Map(mapSnap as ReadonlyMap<string, EffectivenessEntry>);\n\t\t},\n\t\t{\n\t\t\tname: `${opts?.name ?? \"effectiveness\"}-snapshot`,\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst am = a as EffectivenessSnapshot;\n\t\t\t\tconst bm = b as EffectivenessSnapshot;\n\t\t\t\tif (am.size !== bm.size) return false;\n\t\t\t\tfor (const [k, v] of am) {\n\t\t\t\t\tconst bv = bm.get(k);\n\t\t\t\t\tif (!bv || v.attempts !== bv.attempts || v.successes !== bv.successes) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\tfunction record(key: string, success: boolean): void {\n\t\tconst existing = _map.get(key);\n\t\tconst attempts = (existing?.attempts ?? 0) + 1;\n\t\tconst successes = (existing?.successes ?? 0) + (success ? 1 : 0);\n\t\t_map.set(key, {\n\t\t\tkey,\n\t\t\tattempts,\n\t\t\tsuccesses,\n\t\t\tsuccessRate: successes / attempts,\n\t\t});\n\t}\n\n\tfunction lookup(key: string): EffectivenessEntry | undefined {\n\t\treturn _map.get(key);\n\t}\n\n\tconst _unsub = keepalive(snapshot);\n\n\treturn {\n\t\tnode: snapshot,\n\t\trecord,\n\t\tlookup,\n\t\tdispose: () => _unsub(),\n\t};\n}\n","/**\n * LLM graph composition (roadmap §8.3).\n *\n * Declarative GraphSpec schema + compiler/decompiler for graph topology.\n * The LLM designs graphs as JSON; compileSpec instantiates them; decompileGraph\n * extracts them back. Templates support reusable subgraph patterns. Feedback\n * edges express bounded cycles via §8.1 feedback().\n *\n * @module\n */\n\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, producer, state } from \"../core/sugar.js\";\nimport { GRAPH_META_SEGMENT, Graph } from \"../graph/graph.js\";\nimport type { ChatMessage, LLMAdapter, LLMResponse } from \"./ai.js\";\nimport { feedback as feedbackPrimitive } from \"./reduction.js\";\n\n// ---------------------------------------------------------------------------\n// GraphSpec types\n// ---------------------------------------------------------------------------\n\n/** A single node declaration in a GraphSpec. */\nexport type GraphSpecNode = {\n\t/** Node kind: state, producer, derived, effect, operator. */\n\ttype: \"state\" | \"producer\" | \"derived\" | \"effect\" | \"operator\";\n\t/** Dependency node names (for derived/effect/operator). */\n\tdeps?: string[];\n\t/** Named function from the catalog (for derived/effect/operator/producer). */\n\tfn?: string;\n\t/** Named source from the catalog (for producer). */\n\tsource?: string;\n\t/** Freeform config passed to the catalog fn/source factory. */\n\tconfig?: Record<string, unknown>;\n\t/** Initial value (for state nodes). */\n\tinitial?: unknown;\n\t/** Human/LLM-readable metadata. */\n\tmeta?: Record<string, unknown>;\n};\n\n/** Template instantiation node — expanded at compile time. */\nexport type GraphSpecTemplateRef = {\n\ttype: \"template\";\n\t/** Name of the template to instantiate. */\n\ttemplate: string;\n\t/** Parameter bindings: template param name → node name. */\n\tbind: Record<string, string>;\n};\n\n/** A reusable subgraph pattern with parameter substitution. */\nexport type GraphSpecTemplate = {\n\t/** Parameter names (prefixed with $ in node refs). */\n\tparams: string[];\n\t/** Node declarations within the template. */\n\tnodes: Record<string, GraphSpecNode>;\n\t/** Which node's output is the template's output. */\n\toutput: string;\n};\n\n/** A feedback edge: bounded cycle from condition to reentry. */\nexport type GraphSpecFeedbackEdge = {\n\t/** Node whose DATA triggers the feedback. */\n\tfrom: string;\n\t/** State node that receives the feedback value. */\n\tto: string;\n\t/** Max iterations before stopping (default: 10). */\n\tmaxIterations?: number;\n};\n\n/** Declarative graph topology for LLM composition (§8.3). */\nexport type GraphSpec = {\n\t/** Graph name. */\n\tname: string;\n\t/** Node declarations (keyed by node name). */\n\tnodes: Record<string, GraphSpecNode | GraphSpecTemplateRef>;\n\t/** Reusable subgraph templates. */\n\ttemplates?: Record<string, GraphSpecTemplate>;\n\t/** Feedback edges (bounded cycles). */\n\tfeedback?: GraphSpecFeedbackEdge[];\n};\n\n// ---------------------------------------------------------------------------\n// Catalog types\n// ---------------------------------------------------------------------------\n\n/**\n * Factory for creating a derived/effect/operator node from catalog.\n * Receives resolved dep nodes and the config from the spec.\n */\nexport type FnFactory = (deps: Node<unknown>[], config: Record<string, unknown>) => Node<unknown>;\n\n/**\n * Factory for creating a producer node from catalog.\n * Receives the config from the spec.\n */\nexport type SourceFactory = (config: Record<string, unknown>) => Node<unknown>;\n\n// ---------------------------------------------------------------------------\n// Rich catalog entries (§9.1b — auto-prompt, catalog-aware validation)\n// ---------------------------------------------------------------------------\n\n/** Simple config field descriptor for LLM prompt generation and validation. */\nexport type ConfigFieldSchema = {\n\t/** Human-readable type: \"string\", \"number\", \"boolean\", \"string[]\", etc. */\n\ttype: string;\n\t/** Whether this field is required (default: true). */\n\trequired?: boolean;\n\t/** Allowed values (enum constraint). */\n\tenum?: readonly (string | number | boolean)[];\n\t/** Human-readable description for LLM context. */\n\tdescription?: string;\n\t/** Default value if omitted. */\n\tdefault?: unknown;\n};\n\n/**\n * Rich catalog entry: bundles a runtime factory with LLM-facing metadata.\n *\n * The metadata is used to:\n * 1. Auto-generate prompt text for {@link llmCompose} (replaces manual `catalogDescription`)\n * 2. Validate LLM output in {@link validateSpec} (catch wrong fn names, invalid config)\n * 3. Provide actionable error messages for {@link llmRefine} feedback loops\n *\n * Developers register ONE object; the library handles prompt generation and validation.\n */\nexport type CatalogFnEntry = {\n\t/** Runtime factory. */\n\tfactory: FnFactory;\n\t/** One-line description for LLM prompt (what it does, not how). */\n\tdescription: string;\n\t/** Config field schemas. Keys are config field names. */\n\tconfigSchema?: Record<string, ConfigFieldSchema>;\n\t/** Example config objects (shown in prompt for complex fns). */\n\texamples?: Record<string, unknown>[];\n\t/** Category tags for grouping in prompt (e.g., \"resilience\", \"reduction\", \"ai\"). */\n\ttags?: string[];\n};\n\n/** Rich catalog entry for producer sources. */\nexport type CatalogSourceEntry = {\n\t/** Runtime factory. */\n\tfactory: SourceFactory;\n\t/** One-line description for LLM prompt. */\n\tdescription: string;\n\t/** Config field schemas. */\n\tconfigSchema?: Record<string, ConfigFieldSchema>;\n\t/** Example config objects. */\n\texamples?: Record<string, unknown>[];\n\t/** Category tags. */\n\ttags?: string[];\n};\n\n/**\n * Fn/source lookup table passed to compileSpec and llmCompose.\n *\n * Accepts both bare factories (backward-compatible) and rich {@link CatalogFnEntry}\n * / {@link CatalogSourceEntry} objects. When rich entries are provided, the library\n * auto-generates LLM prompts and validates LLM output against the catalog.\n */\nexport type GraphSpecCatalog = {\n\tfns?: Record<string, FnFactory | CatalogFnEntry>;\n\tsources?: Record<string, SourceFactory | CatalogSourceEntry>;\n};\n\n// ---------------------------------------------------------------------------\n// Catalog helpers\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this a rich catalog fn entry (vs bare factory)? */\nexport function isRichFnEntry(entry: FnFactory | CatalogFnEntry): entry is CatalogFnEntry {\n\treturn typeof entry === \"object\" && entry !== null && \"factory\" in entry;\n}\n\n/** Type guard: is this a rich catalog source entry (vs bare factory)? */\nexport function isRichSourceEntry(\n\tentry: SourceFactory | CatalogSourceEntry,\n): entry is CatalogSourceEntry {\n\treturn typeof entry === \"object\" && entry !== null && \"factory\" in entry;\n}\n\n/** Extract the runtime factory from a catalog entry (rich or bare). */\nexport function extractFnFactory(entry: FnFactory | CatalogFnEntry): FnFactory {\n\treturn isRichFnEntry(entry) ? entry.factory : entry;\n}\n\n/** Extract the runtime factory from a catalog source entry (rich or bare). */\nexport function extractSourceFactory(entry: SourceFactory | CatalogSourceEntry): SourceFactory {\n\treturn isRichSourceEntry(entry) ? entry.factory : entry;\n}\n\n/**\n * Auto-generate catalog prompt text from rich catalog entries.\n *\n * Groups fns by tag, formats each as `- name: description. Config: { ... }`.\n * Falls back to listing names only for bare factories.\n */\nexport function generateCatalogPrompt(catalog: GraphSpecCatalog): string {\n\tconst sections: string[] = [];\n\n\tif (catalog.fns) {\n\t\t// Group by first tag (or \"Other\")\n\t\tconst groups = new Map<string, string[]>();\n\t\tfor (const [name, entry] of Object.entries(catalog.fns)) {\n\t\t\tconst tag = isRichFnEntry(entry) ? (entry.tags?.[0] ?? \"Other\") : \"Other\";\n\t\t\tif (!groups.has(tag)) groups.set(tag, []);\n\t\t\tgroups.get(tag)!.push(formatFnEntry(name, entry));\n\t\t}\n\t\tfor (const [tag, lines] of groups) {\n\t\t\tsections.push(`${tag}:\\n${lines.join(\"\\n\")}`);\n\t\t}\n\t}\n\n\tif (catalog.sources) {\n\t\tconst lines: string[] = [];\n\t\tfor (const [name, entry] of Object.entries(catalog.sources)) {\n\t\t\tlines.push(formatSourceEntry(name, entry));\n\t\t}\n\t\tif (lines.length > 0) {\n\t\t\tsections.push(`Sources:\\n${lines.join(\"\\n\")}`);\n\t\t}\n\t}\n\n\treturn sections.join(\"\\n\\n\");\n}\n\nfunction formatFnEntry(name: string, entry: FnFactory | CatalogFnEntry): string {\n\tif (!isRichFnEntry(entry)) return `- ${name}`;\n\tlet line = `- ${name}: ${entry.description}`;\n\tif (entry.configSchema) {\n\t\tconst fields = Object.entries(entry.configSchema).map(([k, v]) => {\n\t\t\tlet desc = `${k}: ${v.type}`;\n\t\t\tif (v.enum) desc += ` (${v.enum.join(\"|\")})`;\n\t\t\tif (v.required === false) desc += \"?\";\n\t\t\treturn desc;\n\t\t});\n\t\tline += `. Config: { ${fields.join(\", \")} }`;\n\t}\n\treturn line;\n}\n\nfunction formatSourceEntry(name: string, entry: SourceFactory | CatalogSourceEntry): string {\n\tif (!isRichSourceEntry(entry)) return `- ${name}`;\n\tlet line = `- ${name}: ${entry.description}`;\n\tif (entry.configSchema) {\n\t\tconst fields = Object.entries(entry.configSchema).map(([k, v]) => {\n\t\t\tlet desc = `${k}: ${v.type}`;\n\t\t\tif (v.required === false) desc += \"?\";\n\t\t\treturn desc;\n\t\t});\n\t\tline += `. Config: { ${fields.join(\", \")} }`;\n\t}\n\treturn line;\n}\n\n/**\n * Validate a GraphSpec against a catalog.\n *\n * Checks that fn/source names reference actual catalog entries, and validates\n * config fields against configSchema when rich entries are available.\n * Returns additional errors beyond structural {@link validateSpec} checks.\n */\nexport function validateSpecAgainstCatalog(\n\tspec: GraphSpec,\n\tcatalog: GraphSpecCatalog,\n): GraphSpecValidation {\n\tconst errors: string[] = [];\n\tconst fnNames = new Set(Object.keys(catalog.fns ?? {}));\n\tconst sourceNames = new Set(Object.keys(catalog.sources ?? {}));\n\n\tfor (const [nodeName, nodeRaw] of Object.entries(spec.nodes)) {\n\t\tif (nodeRaw.type === \"template\") continue;\n\t\tconst node = nodeRaw as GraphSpecNode;\n\n\t\t// Check fn name exists in catalog\n\t\tif (node.fn && fnNames.size > 0 && !fnNames.has(node.fn)) {\n\t\t\t// Check if they used a source name as fn\n\t\t\tif (sourceNames.has(node.fn)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": fn \"${node.fn}\" is a source, not a function. ` +\n\t\t\t\t\t\t`Use it as a producer source instead, or use a function from: ${[...fnNames].join(\", \")}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst suggestion = findClosest(node.fn, fnNames);\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": fn \"${node.fn}\" not found in catalog` +\n\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Check source name exists in catalog\n\t\tif (node.source && sourceNames.size > 0 && !sourceNames.has(node.source)) {\n\t\t\tif (fnNames.has(node.source)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": source \"${node.source}\" is a function, not a source. ` +\n\t\t\t\t\t\t`Use it as fn instead, or use a source from: ${[...sourceNames].join(\", \")}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst suggestion = findClosest(node.source, sourceNames);\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": source \"${node.source}\" not found in catalog` +\n\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Validate config against schema (if rich entry)\n\t\tif (node.fn && node.config && catalog.fns?.[node.fn]) {\n\t\t\tconst entry = catalog.fns[node.fn];\n\t\t\tif (isRichFnEntry(entry) && entry.configSchema) {\n\t\t\t\tfor (const [field, schema] of Object.entries(entry.configSchema)) {\n\t\t\t\t\tif (schema.required !== false && !(field in node.config)) {\n\t\t\t\t\t\terrors.push(`Node \"${nodeName}\": config missing required field \"${field}\"`);\n\t\t\t\t\t}\n\t\t\t\t\tif (field in node.config && schema.enum) {\n\t\t\t\t\t\tconst val = node.config[field];\n\t\t\t\t\t\tif (!schema.enum.includes(val as string | number | boolean)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${nodeName}\": config.${field} = ${JSON.stringify(val)}, ` +\n\t\t\t\t\t\t\t\t\t`expected one of: ${schema.enum.join(\", \")}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Also check template inner nodes\n\tif (spec.templates) {\n\t\tfor (const [tName, template] of Object.entries(spec.templates)) {\n\t\t\tfor (const [nodeName, node] of Object.entries(template.nodes)) {\n\t\t\t\tif (node.fn && fnNames.size > 0 && !fnNames.has(node.fn)) {\n\t\t\t\t\tconst suggestion = findClosest(node.fn, fnNames);\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Template \"${tName}\" node \"${nodeName}\": fn \"${node.fn}\" not found in catalog` +\n\t\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n/** Simple Levenshtein-based closest match for \"did you mean?\" suggestions. */\nfunction findClosest(input: string, candidates: Set<string>): string | null {\n\tlet best: string | null = null;\n\tlet bestDist = Infinity;\n\tconst lower = input.toLowerCase();\n\tfor (const c of candidates) {\n\t\tconst dist = levenshtein(lower, c.toLowerCase());\n\t\tif (dist < bestDist && dist <= Math.max(3, Math.floor(input.length / 2))) {\n\t\t\tbestDist = dist;\n\t\t\tbest = c;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction levenshtein(a: string, b: string): number {\n\tconst m = a.length;\n\tconst n = b.length;\n\tconst dp: number[][] = Array.from({ length: m + 1 }, (_, i) =>\n\t\tArray.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n\t);\n\tfor (let i = 1; i <= m; i++) {\n\t\tfor (let j = 1; j <= n; j++) {\n\t\t\tdp[i][j] =\n\t\t\t\ta[i - 1] === b[j - 1]\n\t\t\t\t\t? dp[i - 1][j - 1]\n\t\t\t\t\t: 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);\n\t\t}\n\t}\n\treturn dp[m][n];\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\n/** Validation result from {@link validateSpec}. */\nexport type GraphSpecValidation = {\n\tvalid: boolean;\n\terrors: string[];\n};\n\nconst VALID_NODE_TYPES = new Set([\n\t\"state\",\n\t\"producer\",\n\t\"derived\",\n\t\"effect\",\n\t\"operator\",\n\t\"template\",\n]);\n\nconst INNER_NODE_TYPES = new Set([\"state\", \"producer\", \"derived\", \"effect\", \"operator\"]);\n\n/**\n * Validate a GraphSpec JSON object.\n *\n * Checks structural validity: required fields, node types, dep references,\n * template references, feedback edge targets, self-cycles, and bind completeness.\n */\nexport function validateSpec(spec: unknown): GraphSpecValidation {\n\tconst errors: string[] = [];\n\n\tif (spec == null || typeof spec !== \"object\") {\n\t\treturn { valid: false, errors: [\"GraphSpec must be a non-null object\"] };\n\t}\n\n\tconst s = spec as Record<string, unknown>;\n\n\tif (typeof s.name !== \"string\" || s.name.length === 0) {\n\t\terrors.push(\"Missing or empty 'name' field\");\n\t}\n\n\tif (s.nodes == null || typeof s.nodes !== \"object\" || Array.isArray(s.nodes)) {\n\t\terrors.push(\"Missing or invalid 'nodes' field (must be an object)\");\n\t\treturn { valid: false, errors };\n\t}\n\n\tconst nodeNames = new Set(Object.keys(s.nodes as object));\n\tconst nodeTypes = new Map<string, string>();\n\tconst templateDefs = new Map<string, { params: string[] }>();\n\n\t// Pre-scan template definitions for param validation\n\tif (s.templates != null && typeof s.templates === \"object\" && !Array.isArray(s.templates)) {\n\t\tfor (const [tName, tRaw] of Object.entries(s.templates as Record<string, unknown>)) {\n\t\t\tif (tRaw != null && typeof tRaw === \"object\") {\n\t\t\t\tconst t = tRaw as Record<string, unknown>;\n\t\t\t\ttemplateDefs.set(tName, {\n\t\t\t\t\tparams: Array.isArray(t.params) ? (t.params as string[]) : [],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate templates\n\tif (s.templates != null) {\n\t\tif (typeof s.templates !== \"object\" || Array.isArray(s.templates)) {\n\t\t\terrors.push(\"'templates' must be an object\");\n\t\t} else {\n\t\t\tfor (const [tName, tRaw] of Object.entries(s.templates as Record<string, unknown>)) {\n\t\t\t\tif (tRaw == null || typeof tRaw !== \"object\") {\n\t\t\t\t\terrors.push(`Template \"${tName}\": must be an object`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst t = tRaw as Record<string, unknown>;\n\t\t\t\tif (!Array.isArray(t.params)) {\n\t\t\t\t\terrors.push(`Template \"${tName}\": missing 'params' array`);\n\t\t\t\t}\n\t\t\t\tif (t.nodes == null || typeof t.nodes !== \"object\" || Array.isArray(t.nodes)) {\n\t\t\t\t\terrors.push(`Template \"${tName}\": missing or invalid 'nodes' object`);\n\t\t\t\t} else {\n\t\t\t\t\tconst paramSet = new Set(Array.isArray(t.params) ? (t.params as string[]) : []);\n\t\t\t\t\tconst innerNames = new Set(Object.keys(t.nodes as object));\n\t\t\t\t\tfor (const [nName, nRaw] of Object.entries(t.nodes as Record<string, unknown>)) {\n\t\t\t\t\t\tif (nRaw == null || typeof nRaw !== \"object\") {\n\t\t\t\t\t\t\terrors.push(`Template \"${tName}\" node \"${nName}\": must be an object`);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst n = nRaw as Record<string, unknown>;\n\t\t\t\t\t\tif (typeof n.type !== \"string\" || !INNER_NODE_TYPES.has(n.type)) {\n\t\t\t\t\t\t\terrors.push(`Template \"${tName}\" node \"${nName}\": invalid type`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (Array.isArray(n.deps)) {\n\t\t\t\t\t\t\tfor (const dep of n.deps as string[]) {\n\t\t\t\t\t\t\t\tif (!innerNames.has(dep) && !paramSet.has(dep)) {\n\t\t\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t\t\t`Template \"${tName}\" node \"${nName}\": dep \"${dep}\" is not an inner node or param`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof t.output !== \"string\") {\n\t\t\t\t\t\terrors.push(`Template \"${tName}\": missing 'output' string`);\n\t\t\t\t\t} else if (!(t.nodes as Record<string, unknown>)[t.output as string]) {\n\t\t\t\t\t\terrors.push(`Template \"${tName}\": output \"${t.output}\" is not a declared node`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate nodes\n\tfor (const [name, raw] of Object.entries(s.nodes as Record<string, unknown>)) {\n\t\tif (raw == null || typeof raw !== \"object\") {\n\t\t\terrors.push(`Node \"${name}\": must be an object`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst n = raw as Record<string, unknown>;\n\t\tif (typeof n.type !== \"string\" || !VALID_NODE_TYPES.has(n.type)) {\n\t\t\terrors.push(\n\t\t\t\t`Node \"${name}\": invalid type \"${String(n.type)}\" (expected: ${[...VALID_NODE_TYPES].join(\", \")})`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tnodeTypes.set(name, n.type);\n\n\t\tif (n.type === \"template\") {\n\t\t\tif (typeof n.template !== \"string\" || !templateDefs.has(n.template)) {\n\t\t\t\terrors.push(`Node \"${name}\": template \"${String(n.template)}\" not found in templates`);\n\t\t\t} else {\n\t\t\t\t// Check bind completeness: all template params must be bound\n\t\t\t\tif (n.bind == null || typeof n.bind !== \"object\" || Array.isArray(n.bind)) {\n\t\t\t\t\terrors.push(`Node \"${name}\": template ref requires 'bind' object`);\n\t\t\t\t} else {\n\t\t\t\t\tconst tmpl = templateDefs.get(n.template as string)!;\n\t\t\t\t\tconst bind = n.bind as Record<string, string>;\n\t\t\t\t\tfor (const param of tmpl.params) {\n\t\t\t\t\t\tif (!(param in bind)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${name}\": template param \"${param}\" is not bound (template \"${n.template}\")`,\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\tfor (const [, target] of Object.entries(bind)) {\n\t\t\t\t\t\tif (typeof target === \"string\" && !nodeNames.has(target)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${name}\": bind target \"${target}\" does not reference an existing node`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (Array.isArray(n.deps)) {\n\t\t\t\tfor (const dep of n.deps as string[]) {\n\t\t\t\t\t// Self-referencing dep\n\t\t\t\t\tif (dep === name) {\n\t\t\t\t\t\terrors.push(`Node \"${name}\": self-referencing dep`);\n\t\t\t\t\t} else if (!nodeNames.has(dep)) {\n\t\t\t\t\t\terrors.push(`Node \"${name}\": dep \"${dep}\" does not reference an existing node`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Warn: derived/effect/operator without deps\n\t\t\tif (\n\t\t\t\t(n.type === \"derived\" || n.type === \"effect\" || n.type === \"operator\") &&\n\t\t\t\t!Array.isArray(n.deps)\n\t\t\t) {\n\t\t\t\terrors.push(`Node \"${name}\": ${n.type} node should have a 'deps' array`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate feedback edges\n\tif (s.feedback != null) {\n\t\tif (!Array.isArray(s.feedback)) {\n\t\t\terrors.push(\"'feedback' must be an array\");\n\t\t} else {\n\t\t\tfor (let i = 0; i < (s.feedback as unknown[]).length; i++) {\n\t\t\t\tconst edge = (s.feedback as unknown[])[i];\n\t\t\t\tif (edge == null || typeof edge !== \"object\") {\n\t\t\t\t\terrors.push(`Feedback [${i}]: must be an object`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst e = edge as Record<string, unknown>;\n\t\t\t\tif (typeof e.from !== \"string\" || !nodeNames.has(e.from)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'from' \"${String(e.from)}\" does not reference an existing node`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (typeof e.from === \"string\" && e.from === e.to) {\n\t\t\t\t\terrors.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`);\n\t\t\t\t}\n\t\t\t\tif (typeof e.to !== \"string\" || !nodeNames.has(e.to)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'to' \"${String(e.to)}\" does not reference an existing node`,\n\t\t\t\t\t);\n\t\t\t\t} else if (typeof e.to === \"string\" && nodeTypes.get(e.to) !== \"state\") {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'to' node \"${e.to}\" must be a state node (got \"${nodeTypes.get(e.to) ?? \"unknown\"}\")`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// compileSpec\n// ---------------------------------------------------------------------------\n\n/** Options for {@link compileSpec}. */\nexport type CompileSpecOptions = {\n\t/** Fn/source catalog for resolving named factories. */\n\tcatalog?: GraphSpecCatalog;\n};\n\n/**\n * Instantiate a Graph from a GraphSpec.\n *\n * Handles template expansion (mounted subgraphs), feedback wiring via §8.1\n * feedback(), node factory lookup from the catalog, and topology validation.\n *\n * @param spec - Declarative graph topology.\n * @param opts - Catalog and compile options.\n * @returns A running Graph.\n * @throws On validation failure, missing catalog entries, or unresolvable deps.\n *\n * @category patterns\n */\nexport function compileSpec(spec: GraphSpec, opts?: CompileSpecOptions): Graph {\n\tconst validation = validateSpec(spec);\n\tif (!validation.valid) {\n\t\tthrow new Error(`compileSpec: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tconst catalog = opts?.catalog ?? {};\n\tconst g = new Graph(spec.name);\n\tconst templates = spec.templates ?? {};\n\n\t// Catalog-aware validation (when rich entries are available)\n\tconst catalogValidation = validateSpecAgainstCatalog(spec, catalog);\n\tif (!catalogValidation.valid) {\n\t\tthrow new Error(\n\t\t\t`compileSpec: catalog validation errors:\\n${catalogValidation.errors.join(\"\\n\")}`,\n\t\t);\n\t}\n\n\t// Helper: resolve fn/source factories from catalog (handles rich + bare entries)\n\tconst resolveFn = (fnName: string): FnFactory | undefined => {\n\t\tconst entry = catalog.fns?.[fnName];\n\t\treturn entry ? extractFnFactory(entry) : undefined;\n\t};\n\tconst resolveSource = (sourceName: string): SourceFactory | undefined => {\n\t\tconst entry = catalog.sources?.[sourceName];\n\t\treturn entry ? extractSourceFactory(entry) : undefined;\n\t};\n\n\t// Phase 1: Create non-template nodes (state/producer first, then derived/effect/operator)\n\tconst created = new Map<string, Node<unknown>>();\n\tconst deferred: [string, GraphSpecNode][] = [];\n\n\tfor (const [name, raw] of Object.entries(spec.nodes)) {\n\t\tif (raw.type === \"template\") continue; // handled in Phase 2\n\n\t\tconst n = raw as GraphSpecNode;\n\t\tif (n.type === \"state\") {\n\t\t\tconst nd = state(n.initial, {\n\t\t\t\tname,\n\t\t\t\tmeta: n.meta ? { ...n.meta } : undefined,\n\t\t\t});\n\t\t\tg.add(name, nd);\n\t\t\tcreated.set(name, nd);\n\t\t} else if (n.type === \"producer\") {\n\t\t\tconst sourceFactory = n.source ? resolveSource(n.source) : undefined;\n\t\t\tconst fnFactory = n.fn ? resolveFn(n.fn) : undefined;\n\t\t\tif (sourceFactory) {\n\t\t\t\tconst nd = sourceFactory(n.config ?? {});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t} else if (fnFactory) {\n\t\t\t\tconst nd = fnFactory([], n.config ?? {});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t} else {\n\t\t\t\t// No catalog entry — create a bare producer placeholder\n\t\t\t\tconst nd = producer(() => {}, {\n\t\t\t\t\tname,\n\t\t\t\t\tmeta: { ...n.meta, _specFn: n.fn, _specSource: n.source },\n\t\t\t\t});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t}\n\t\t} else {\n\t\t\tdeferred.push([name, n]);\n\t\t}\n\t}\n\n\t// Resolve deferred nodes (derived/effect/operator) in dependency order\n\tlet progressed = true;\n\tconst pending = new Map(deferred);\n\twhile (pending.size > 0 && progressed) {\n\t\tprogressed = false;\n\t\tfor (const [name, n] of [...pending.entries()]) {\n\t\t\tconst deps = n.deps ?? [];\n\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\n\t\t\tconst resolvedDeps = deps.map((dep) => created.get(dep)!);\n\t\t\tconst fnFactory = n.fn ? resolveFn(n.fn) : undefined;\n\n\t\t\tlet nd: Node<unknown>;\n\t\t\tif (fnFactory) {\n\t\t\t\tnd = fnFactory(resolvedDeps, n.config ?? {});\n\t\t\t} else if (n.type === \"effect\") {\n\t\t\t\tnd = effect(resolvedDeps, () => {});\n\t\t\t} else {\n\t\t\t\t// derived/operator without catalog fn — identity passthrough\n\t\t\t\tnd = derived(resolvedDeps, (vals: readonly unknown[]) => vals[0]);\n\t\t\t}\n\t\t\tg.add(name, nd);\n\t\t\tcreated.set(name, nd);\n\t\t\tpending.delete(name);\n\t\t\tprogressed = true;\n\t\t}\n\t}\n\tif (pending.size > 0) {\n\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\tthrow new Error(`compileSpec: unresolvable deps for nodes: ${unresolved}`);\n\t}\n\n\t// Phase 2: Expand template instantiations as mounted subgraphs\n\tfor (const [name, raw] of Object.entries(spec.nodes)) {\n\t\tif (raw.type !== \"template\") continue;\n\t\tconst ref = raw as GraphSpecTemplateRef;\n\t\tconst tmpl = templates[ref.template]!;\n\n\t\tconst sub = new Graph(name);\n\t\tconst subCreated = new Map<string, Node<unknown>>();\n\t\tconst subDeferred: [string, GraphSpecNode][] = [];\n\n\t\t// Create inner nodes, resolving $params to bound nodes\n\t\tfor (const [nName, nSpec] of Object.entries(tmpl.nodes)) {\n\t\t\tconst resolvedDeps = (nSpec.deps ?? []).map((dep) => {\n\t\t\t\tif (dep.startsWith(\"$\") && ref.bind[dep]) {\n\t\t\t\t\treturn ref.bind[dep];\n\t\t\t\t}\n\t\t\t\treturn dep;\n\t\t\t});\n\t\t\tconst specWithResolvedDeps = { ...nSpec, deps: resolvedDeps };\n\n\t\t\tif (nSpec.type === \"state\") {\n\t\t\t\tconst nd = state(nSpec.initial, {\n\t\t\t\t\tname: nName,\n\t\t\t\t\tmeta: nSpec.meta ? { ...nSpec.meta } : undefined,\n\t\t\t\t});\n\t\t\t\tsub.add(nName, nd);\n\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t} else if (nSpec.type === \"producer\") {\n\t\t\t\t// Handle producer nodes inside templates\n\t\t\t\tconst sourceFactory = nSpec.source ? resolveSource(nSpec.source) : undefined;\n\t\t\t\tconst fnFactory = nSpec.fn ? resolveFn(nSpec.fn) : undefined;\n\t\t\t\tif (sourceFactory) {\n\t\t\t\t\tconst nd = sourceFactory(nSpec.config ?? {});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t} else if (fnFactory) {\n\t\t\t\t\tconst nd = fnFactory([], nSpec.config ?? {});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t} else {\n\t\t\t\t\tconst nd = producer(() => {}, {\n\t\t\t\t\t\tname: nName,\n\t\t\t\t\t\tmeta: { ...nSpec.meta, _specFn: nSpec.fn, _specSource: nSpec.source },\n\t\t\t\t\t});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsubDeferred.push([nName, specWithResolvedDeps]);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve deferred inner nodes\n\t\tlet subProgressed = true;\n\t\tconst subPending = new Map(subDeferred);\n\t\twhile (subPending.size > 0 && subProgressed) {\n\t\t\tsubProgressed = false;\n\t\t\tfor (const [nName, nSpec] of [...subPending.entries()]) {\n\t\t\t\tconst deps = nSpec.deps ?? [];\n\t\t\t\tconst allReady = deps.every((dep) => subCreated.has(dep) || created.has(dep));\n\t\t\t\tif (!allReady) continue;\n\n\t\t\t\tconst resolvedDeps = deps.map((dep) => subCreated.get(dep) ?? created.get(dep)!);\n\t\t\t\tconst fnFactory = nSpec.fn ? resolveFn(nSpec.fn) : undefined;\n\n\t\t\t\tlet nd: Node<unknown>;\n\t\t\t\tif (fnFactory) {\n\t\t\t\t\tnd = fnFactory(resolvedDeps, nSpec.config ?? {});\n\t\t\t\t} else if (nSpec.type === \"effect\") {\n\t\t\t\t\tnd = effect(resolvedDeps, () => {});\n\t\t\t\t} else {\n\t\t\t\t\tnd = derived(resolvedDeps, (vals: readonly unknown[]) => vals[0]);\n\t\t\t\t}\n\t\t\t\tsub.add(nName, nd);\n\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\tsubPending.delete(nName);\n\t\t\t\tsubProgressed = true;\n\t\t\t}\n\t\t}\n\t\tif (subPending.size > 0) {\n\t\t\tconst unresolved = [...subPending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`compileSpec: template \"${ref.template}\" has unresolvable deps: ${unresolved}`,\n\t\t\t);\n\t\t}\n\n\t\tg.mount(name, sub);\n\t\t// Register template output as a reachable node path\n\t\tconst outputPath = `${name}::${tmpl.output}`;\n\t\tcreated.set(name, g.resolve(outputPath));\n\n\t\t// Store template origin meta on the mounted subgraph's first node\n\t\t// so decompileGraph can recover it without structural fingerprinting.\n\t\ttry {\n\t\t\tconst outputNode = g.resolve(outputPath);\n\t\t\toutputNode.meta._templateName?.down([[DATA, ref.template]]);\n\t\t\toutputNode.meta._templateBind?.down([[DATA, ref.bind]]);\n\t\t} catch {\n\t\t\t/* meta nodes may not exist; template origin is best-effort */\n\t\t}\n\t}\n\n\t// Edges are derived from node `_deps` (Unit 7) — no explicit edge wiring step.\n\n\t// Phase 4: Wire feedback edges via §8.1 feedback()\n\tfor (const fb of spec.feedback ?? []) {\n\t\tfeedbackPrimitive(g, fb.from, fb.to, {\n\t\t\tmaxIterations: fb.maxIterations,\n\t\t});\n\t}\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// decompileGraph\n// ---------------------------------------------------------------------------\n\n/** Internal meta keys used by compileSpec/feedback — stripped from output. */\nconst INTERNAL_META_KEYS = new Set([\n\t\"reduction\",\n\t\"reduction_type\",\n\t\"_specFn\",\n\t\"_specSource\",\n\t\"_templateName\",\n\t\"_templateBind\",\n\t\"feedbackFrom\",\n\t\"feedbackTo\",\n\t\"_internal\",\n]);\n\n/**\n * Extract a GraphSpec from a running graph.\n *\n * Uses `describe({ detail: \"standard\" })` as a starting point, then enriches:\n * - Feedback edges recovered from counter node meta (`feedbackFrom`/`feedbackTo`)\n * - Template refs recovered from output node meta (`_templateName`/`_templateBind`)\n * - Structural fingerprinting as fallback for 2+ identical mounted subgraphs\n *\n * @param graph - Running graph to decompile.\n * @returns A GraphSpec representation.\n *\n * @category patterns\n */\nexport function decompileGraph(graph: Graph): GraphSpec {\n\tconst desc = graph.describe({ detail: \"standard\" });\n\tconst nodes: Record<string, GraphSpecNode> = {};\n\tconst feedbackEdges: GraphSpecFeedbackEdge[] = [];\n\tconst metaSegment = `::${GRAPH_META_SEGMENT}::`;\n\n\t// Detect feedback counter nodes and extract feedback edges from meta\n\tconst feedbackCounterPattern = /^__feedback_(?!effect_)(.+)$/;\n\tconst feedbackConditions = new Set<string>();\n\n\tfor (const path of Object.keys(desc.nodes)) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\tconst match = feedbackCounterPattern.exec(path);\n\t\tif (match) {\n\t\t\tfeedbackConditions.add(match[1]!);\n\t\t\tconst meta = desc.nodes[path]?.meta as Record<string, unknown> | undefined;\n\t\t\tif (meta?.feedbackFrom && meta?.feedbackTo) {\n\t\t\t\tfeedbackEdges.push({\n\t\t\t\t\tfrom: meta.feedbackFrom as string,\n\t\t\t\t\tto: meta.feedbackTo as string,\n\t\t\t\t\t...(meta.maxIterations ? { maxIterations: meta.maxIterations as number } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build nodes map, skipping meta, feedback internals, and bridge nodes\n\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\tif (feedbackCounterPattern.test(path)) continue;\n\t\t// Skip internal infrastructure nodes (bridge, feedback effect) via meta tag\n\t\tif (nodeDesc.meta?._internal) continue;\n\t\t// Legacy fallback: skip by naming convention\n\t\tif (path.startsWith(\"__feedback_effect_\")) continue;\n\t\tif (path.startsWith(\"__bridge_\")) continue;\n\t\t// Skip subgraph-internal nodes (they belong to templates)\n\t\tif (path.includes(\"::\")) continue;\n\n\t\tconst specNode: GraphSpecNode = {\n\t\t\ttype: nodeDesc.type as GraphSpecNode[\"type\"],\n\t\t};\n\n\t\tif (nodeDesc.deps.length > 0) {\n\t\t\tspecNode.deps = nodeDesc.deps.filter((d) => !d.includes(\"::\"));\n\t\t}\n\n\t\tif (nodeDesc.type === \"state\" && nodeDesc.value !== undefined) {\n\t\t\tspecNode.initial = nodeDesc.value;\n\t\t}\n\n\t\tif (nodeDesc.meta && Object.keys(nodeDesc.meta).length > 0) {\n\t\t\tconst meta: Record<string, unknown> = {};\n\t\t\tfor (const [k, v] of Object.entries(nodeDesc.meta as Record<string, unknown>)) {\n\t\t\t\tif (!INTERNAL_META_KEYS.has(k)) meta[k] = v;\n\t\t\t}\n\t\t\tif (Object.keys(meta).length > 0) {\n\t\t\t\tspecNode.meta = meta;\n\t\t\t}\n\t\t}\n\n\t\tnodes[path] = specNode;\n\t}\n\n\t// Detect templates: first from compile-time meta (option B), then structural fallback\n\tconst templates: Record<string, GraphSpecTemplate> = {};\n\tconst templateRefs: Record<string, GraphSpecTemplateRef> = {};\n\tconst metaDetectedSubgraphs = new Set<string>();\n\n\t// Option B: recover template origin from meta stored by compileSpec\n\tfor (const subName of desc.subgraphs) {\n\t\tconst prefix = `${subName}::`;\n\t\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\t\tif (!path.startsWith(prefix)) continue;\n\t\t\tif (path.includes(metaSegment)) continue;\n\t\t\tconst meta = nodeDesc.meta as Record<string, unknown> | undefined;\n\t\t\tif (meta?._templateName && meta?._templateBind) {\n\t\t\t\tconst templateName = meta._templateName as string;\n\t\t\t\tconst bind = meta._templateBind as Record<string, string>;\n\n\t\t\t\t// Reconstruct template definition from the subgraph's nodes\n\t\t\t\tif (!templates[templateName]) {\n\t\t\t\t\tconst tmplNodes: Record<string, GraphSpecNode> = {};\n\t\t\t\t\tconst tmplInnerNames = new Set<string>();\n\t\t\t\t\tconst tmplPrefix = `${subName}::`;\n\t\t\t\t\tfor (const [p, nd] of Object.entries(desc.nodes)) {\n\t\t\t\t\t\tif (!p.startsWith(tmplPrefix) || p.includes(metaSegment)) continue;\n\t\t\t\t\t\tconst localName = p.slice(tmplPrefix.length);\n\t\t\t\t\t\tif (localName.includes(\"::\")) continue;\n\t\t\t\t\t\ttmplInnerNames.add(localName);\n\t\t\t\t\t\ttmplNodes[localName] = {\n\t\t\t\t\t\t\ttype: nd.type as GraphSpecNode[\"type\"],\n\t\t\t\t\t\t\t...(nd.deps.length > 0\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tdeps: nd.deps.map((d) =>\n\t\t\t\t\t\t\t\t\t\t\td.startsWith(tmplPrefix) ? d.slice(tmplPrefix.length) : d,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\t// Detect params (external deps) and output\n\t\t\t\t\tconst tmplParams: string[] = [];\n\t\t\t\t\tconst tmplParamMap = new Map<string, string>();\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\t\t\tif (!tmplInnerNames.has(dep) && !tmplParamMap.has(dep)) {\n\t\t\t\t\t\t\t\tconst param = `$${dep}`;\n\t\t\t\t\t\t\t\ttmplParams.push(param);\n\t\t\t\t\t\t\t\ttmplParamMap.set(dep, param);\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\t// Substitute external deps with $params\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tif (n.deps) n.deps = n.deps.map((d) => tmplParamMap.get(d) ?? d);\n\t\t\t\t\t}\n\t\t\t\t\t// Find output\n\t\t\t\t\tconst depended = new Set<string>();\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\t\t\tif (tmplInnerNames.has(dep)) depended.add(dep);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst outputCandidates = [...tmplInnerNames].filter((n) => !depended.has(n));\n\t\t\t\t\tconst tmplOutput = outputCandidates[0] ?? [...tmplInnerNames].pop()!;\n\n\t\t\t\t\ttemplates[templateName] = { params: tmplParams, nodes: tmplNodes, output: tmplOutput };\n\t\t\t\t}\n\n\t\t\t\tdelete nodes[subName];\n\t\t\t\ttemplateRefs[subName] = { type: \"template\", template: templateName, bind };\n\t\t\t\tmetaDetectedSubgraphs.add(subName);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Structural fallback: group remaining mounted subgraphs by fingerprint\n\tconst structureMap = new Map<string, { name: string; nodes: Record<string, GraphSpecNode> }[]>();\n\tfor (const subName of desc.subgraphs) {\n\t\tif (metaDetectedSubgraphs.has(subName)) continue;\n\t\tconst subNodes: Record<string, GraphSpecNode> = {};\n\t\tconst prefix = `${subName}::`;\n\t\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\t\tif (path.includes(metaSegment)) continue;\n\t\t\tif (!path.startsWith(prefix)) continue;\n\t\t\tconst localName = path.slice(prefix.length);\n\t\t\tif (localName.includes(\"::\")) continue;\n\t\t\tsubNodes[localName] = {\n\t\t\t\ttype: nodeDesc.type as GraphSpecNode[\"type\"],\n\t\t\t\t...(nodeDesc.deps.length > 0\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdeps: nodeDesc.deps.map((d) => (d.startsWith(prefix) ? d.slice(prefix.length) : d)),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t\tconst fingerprint = JSON.stringify(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(subNodes)\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([k, v]) => [k, { type: v.type, deps: v.deps ?? [] }]),\n\t\t\t),\n\t\t);\n\t\tif (!structureMap.has(fingerprint)) {\n\t\t\tstructureMap.set(fingerprint, []);\n\t\t}\n\t\tstructureMap.get(fingerprint)!.push({ name: subName, nodes: subNodes });\n\t}\n\n\t// Subgraphs with identical structure (2+ instances) → templates\n\tfor (const [, group] of structureMap) {\n\t\tif (group.length < 2) continue;\n\t\tconst templateName = `${group[0]!.name}_template`;\n\t\tconst refNodes = group[0]!.nodes;\n\t\tconst innerNames = new Set(Object.keys(refNodes));\n\n\t\t// Detect external deps as params (from first member)\n\t\tconst params: string[] = [];\n\t\tconst baseParamMap = new Map<string, string>();\n\t\tfor (const n of Object.values(refNodes)) {\n\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\tif (!innerNames.has(dep) && !baseParamMap.has(dep)) {\n\t\t\t\t\tconst param = `$${dep}`;\n\t\t\t\t\tparams.push(param);\n\t\t\t\t\tbaseParamMap.set(dep, param);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Find output node\n\t\tconst depended = new Set<string>();\n\t\tfor (const n of Object.values(refNodes)) {\n\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\tif (innerNames.has(dep)) depended.add(dep);\n\t\t\t}\n\t\t}\n\t\tconst outputCandidates = [...innerNames].filter((n) => !depended.has(n));\n\t\tconst output = outputCandidates[0] ?? [...innerNames].pop()!;\n\n\t\t// Build template nodes with param-substituted deps\n\t\tconst tmplNodes: Record<string, GraphSpecNode> = {};\n\t\tfor (const [nName, nSpec] of Object.entries(refNodes)) {\n\t\t\ttmplNodes[nName] = {\n\t\t\t\t...nSpec,\n\t\t\t\tdeps: nSpec.deps?.map((d) => baseParamMap.get(d) ?? d),\n\t\t\t};\n\t\t}\n\n\t\ttemplates[templateName] = { params, nodes: tmplNodes, output };\n\n\t\t// Build per-member bind maps (each member may bind to different external nodes)\n\t\tfor (const member of group) {\n\t\t\tdelete nodes[member.name];\n\t\t\t// Build this member's own bind map by scanning its external deps\n\t\t\tconst memberBind: Record<string, string> = {};\n\t\t\tconst memberInnerNames = new Set(Object.keys(member.nodes));\n\t\t\tfor (const n of Object.values(member.nodes)) {\n\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\tif (!memberInnerNames.has(dep)) {\n\t\t\t\t\t\t// Find which param this external dep maps to\n\t\t\t\t\t\tconst param = baseParamMap.get(dep) ?? `$${dep}`;\n\t\t\t\t\t\tmemberBind[param] = dep;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplateRefs[member.name] = {\n\t\t\t\ttype: \"template\",\n\t\t\t\ttemplate: templateName,\n\t\t\t\tbind: memberBind,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst allNodes: Record<string, GraphSpecNode | GraphSpecTemplateRef> = {\n\t\t...nodes,\n\t\t...templateRefs,\n\t};\n\n\tconst result: GraphSpec = { name: desc.name, nodes: allNodes };\n\tif (Object.keys(templates).length > 0) result.templates = templates;\n\tif (feedbackEdges.length > 0) result.feedback = feedbackEdges;\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// specDiff\n// ---------------------------------------------------------------------------\n\n/** A single change in a spec diff. */\nexport type SpecDiffEntry = {\n\ttype: \"added\" | \"removed\" | \"changed\";\n\tpath: string;\n\tdetail?: string;\n};\n\n/** Structural diff between two GraphSpecs. */\nexport type SpecDiffResult = {\n\tentries: SpecDiffEntry[];\n\tsummary: string;\n};\n\n/**\n * Compute a structural diff between two GraphSpecs.\n *\n * Template-aware: reports \"changed template definition\" vs \"changed\n * instantiation bindings.\" No runtime needed — pure JSON comparison.\n *\n * @param specA - The \"before\" spec.\n * @param specB - The \"after\" spec.\n * @returns Diff entries and a human-readable summary.\n *\n * @category patterns\n */\nexport function specDiff(specA: GraphSpec, specB: GraphSpec): SpecDiffResult {\n\tconst entries: SpecDiffEntry[] = [];\n\n\t// Diff name\n\tif (specA.name !== specB.name) {\n\t\tentries.push({\n\t\t\ttype: \"changed\",\n\t\t\tpath: \"name\",\n\t\t\tdetail: `\"${specA.name}\" → \"${specB.name}\"`,\n\t\t});\n\t}\n\n\t// Diff nodes\n\tconst nodesA = new Set(Object.keys(specA.nodes));\n\tconst nodesB = new Set(Object.keys(specB.nodes));\n\n\tfor (const name of nodesB) {\n\t\tif (!nodesA.has(name)) {\n\t\t\tconst n = specB.nodes[name]!;\n\t\t\tentries.push({\n\t\t\t\ttype: \"added\",\n\t\t\t\tpath: `nodes.${name}`,\n\t\t\t\tdetail: `type: ${n.type}`,\n\t\t\t});\n\t\t}\n\t}\n\tfor (const name of nodesA) {\n\t\tif (!nodesB.has(name)) {\n\t\t\tentries.push({ type: \"removed\", path: `nodes.${name}` });\n\t\t}\n\t}\n\tfor (const name of nodesA) {\n\t\tif (!nodesB.has(name)) continue;\n\t\tconst a = specA.nodes[name]!;\n\t\tconst b = specB.nodes[name]!;\n\t\tif (JSON.stringify(a) !== JSON.stringify(b)) {\n\t\t\tconst details: string[] = [];\n\t\t\tif (a.type !== b.type) details.push(`type: ${a.type} → ${b.type}`);\n\t\t\tif (JSON.stringify((a as GraphSpecNode).deps) !== JSON.stringify((b as GraphSpecNode).deps)) {\n\t\t\t\tdetails.push(\"deps changed\");\n\t\t\t}\n\t\t\tif ((a as GraphSpecNode).fn !== (b as GraphSpecNode).fn) {\n\t\t\t\tdetails.push(`fn: ${(a as GraphSpecNode).fn} → ${(b as GraphSpecNode).fn}`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tJSON.stringify((a as GraphSpecNode).config) !== JSON.stringify((b as GraphSpecNode).config)\n\t\t\t) {\n\t\t\t\tdetails.push(\"config changed\");\n\t\t\t}\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `nodes.${name}`,\n\t\t\t\tdetail: details.join(\"; \") || \"modified\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// Diff templates\n\tconst tmplA = specA.templates ?? {};\n\tconst tmplB = specB.templates ?? {};\n\tconst tmplNamesA = new Set(Object.keys(tmplA));\n\tconst tmplNamesB = new Set(Object.keys(tmplB));\n\n\tfor (const name of tmplNamesB) {\n\t\tif (!tmplNamesA.has(name)) {\n\t\t\tentries.push({ type: \"added\", path: `templates.${name}` });\n\t\t}\n\t}\n\tfor (const name of tmplNamesA) {\n\t\tif (!tmplNamesB.has(name)) {\n\t\t\tentries.push({ type: \"removed\", path: `templates.${name}` });\n\t\t}\n\t}\n\tfor (const name of tmplNamesA) {\n\t\tif (!tmplNamesB.has(name)) continue;\n\t\tif (JSON.stringify(tmplA[name]) !== JSON.stringify(tmplB[name])) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `templates.${name}`,\n\t\t\t\tdetail: \"template definition changed\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// Diff feedback\n\tconst fbA = specA.feedback ?? [];\n\tconst fbB = specB.feedback ?? [];\n\tconst fbKeyA = new Set(fbA.map((e) => `${e.from}->${e.to}`));\n\tconst fbKeyB = new Set(fbB.map((e) => `${e.from}->${e.to}`));\n\n\tfor (const fb of fbB) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tif (!fbKeyA.has(key)) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"added\",\n\t\t\t\tpath: `feedback.${key}`,\n\t\t\t\tdetail: `maxIterations: ${fb.maxIterations ?? 10}`,\n\t\t\t});\n\t\t}\n\t}\n\tfor (const fb of fbA) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tif (!fbKeyB.has(key)) {\n\t\t\tentries.push({ type: \"removed\", path: `feedback.${key}` });\n\t\t}\n\t}\n\tfor (const fb of fbA) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tconst counterpart = fbB.find((b) => b.from === fb.from && b.to === fb.to);\n\t\tif (counterpart && JSON.stringify(fb) !== JSON.stringify(counterpart)) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `feedback.${key}`,\n\t\t\t\tdetail: `maxIterations: ${fb.maxIterations ?? 10} → ${counterpart.maxIterations ?? 10}`,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Build summary\n\tconst added = entries.filter((e) => e.type === \"added\").length;\n\tconst removed = entries.filter((e) => e.type === \"removed\").length;\n\tconst changed = entries.filter((e) => e.type === \"changed\").length;\n\tconst parts: string[] = [];\n\tif (added) parts.push(`${added} added`);\n\tif (removed) parts.push(`${removed} removed`);\n\tif (changed) parts.push(`${changed} changed`);\n\tconst summary = parts.length > 0 ? parts.join(\", \") : \"no changes\";\n\n\treturn { entries, summary };\n}\n\n// ---------------------------------------------------------------------------\n// llmCompose\n// ---------------------------------------------------------------------------\n\n/** Options for {@link llmCompose}. */\nexport type LLMComposeOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Extra instructions appended to the system prompt. */\n\tsystemPromptExtra?: string;\n\t/**\n\t * Available fn/source catalog names for the LLM to reference.\n\t * When omitted and `catalog` contains rich {@link CatalogFnEntry} entries,\n\t * the prompt is auto-generated via {@link generateCatalogPrompt}.\n\t */\n\tcatalogDescription?: string;\n\t/**\n\t * Catalog for auto-prompt generation and catalog-aware validation.\n\t * When rich entries are provided, the catalog prompt is auto-generated\n\t * and LLM output is validated against fn/source names and config schemas.\n\t */\n\tcatalog?: GraphSpecCatalog;\n\t/**\n\t * Max auto-refine attempts when the LLM output fails catalog validation.\n\t * Each attempt feeds the validation errors back to the LLM via llmRefine.\n\t * Default: 0 (no auto-refine). Set to 2-3 for production use.\n\t */\n\tmaxAutoRefine?: number;\n};\n\nconst LLM_COMPOSE_SYSTEM_PROMPT = `You are a graph architect for GraphReFly, a reactive graph protocol.\n\nGiven a natural-language description, produce a JSON GraphSpec with this structure:\n\n{\n \"name\": \"<graph_name>\",\n \"nodes\": {\n \"<node_name>\": {\n \"type\": \"state\" | \"derived\" | \"producer\" | \"effect\" | \"operator\",\n \"deps\": [\"<dep_node_name>\", ...],\n \"fn\": \"<catalog_function_name>\",\n \"source\": \"<catalog_source_name>\",\n \"config\": { ... },\n \"initial\": <value>,\n \"meta\": { \"description\": \"<purpose>\" }\n },\n \"<template_instance>\": {\n \"type\": \"template\",\n \"template\": \"<template_name>\",\n \"bind\": { \"$param\": \"node_name\" }\n }\n },\n \"templates\": {\n \"<template_name>\": {\n \"params\": [\"$param1\", \"$param2\"],\n \"nodes\": { ... },\n \"output\": \"<output_node>\"\n }\n },\n \"feedback\": [\n { \"from\": \"<condition_node>\", \"to\": \"<state_node>\", \"maxIterations\": 10 }\n ]\n}\n\nRules:\n- \"state\" nodes hold user/LLM-writable values (knobs). Use \"initial\" for default values.\n- \"derived\" nodes compute from deps using a named \"fn\".\n- \"effect\" nodes produce side effects from deps.\n- \"producer\" nodes generate values from a named \"source\".\n- Use \"templates\" when the same subgraph pattern repeats (e.g., per-source resilience).\n- Use \"feedback\" for bounded cycles where a derived value writes back to a state node.\n- meta.description is required for every node.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/** Strip markdown code fences. */\nfunction stripFences(text: string): string {\n\tconst match = text.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```[\\s\\S]*$/);\n\treturn match ? match[1]! : text;\n}\n\n/**\n * Ask an LLM to compose a GraphSpec from a natural-language problem description.\n *\n * The LLM generates a GraphSpec (with templates + feedback), validated before\n * returning. The spec is for human review before compilation via compileSpec().\n *\n * @param problem - Natural language problem description.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options and catalog description.\n * @returns A validated GraphSpec.\n * @throws On invalid LLM output or validation failure.\n *\n * @category patterns\n */\nexport async function llmCompose(\n\tproblem: string,\n\tadapter: LLMAdapter,\n\topts?: LLMComposeOptions,\n): Promise<GraphSpec> {\n\tlet systemPrompt = LLM_COMPOSE_SYSTEM_PROMPT;\n\n\t// Auto-generate catalog prompt from rich entries, or use manual description\n\tconst catalogPrompt =\n\t\topts?.catalogDescription ?? (opts?.catalog ? generateCatalogPrompt(opts.catalog) : undefined);\n\tif (catalogPrompt) {\n\t\tsystemPrompt += `\\n\\nAvailable catalog (use ONLY these names):\\n${catalogPrompt}`;\n\t}\n\tif (opts?.systemPromptExtra) {\n\t\tsystemPrompt += `\\n\\n${opts.systemPromptExtra}`;\n\t}\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{ role: \"user\", content: problem },\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\t// System boundary: await the adapter's response (Promise, plain value).\n\tconst response = (await rawResult) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`llmCompose: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateSpec(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`llmCompose: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tlet spec = parsed as GraphSpec;\n\n\t// Catalog-aware validation + auto-refine loop\n\tif (opts?.catalog) {\n\t\tconst maxRefine = opts.maxAutoRefine ?? 0;\n\t\tfor (let attempt = 0; attempt <= maxRefine; attempt++) {\n\t\t\tconst catalogValidation = validateSpecAgainstCatalog(spec, opts.catalog);\n\t\t\tif (catalogValidation.valid) break;\n\n\t\t\tif (attempt === maxRefine) {\n\t\t\t\t// Last attempt failed — return with errors attached as meta\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`llmCompose: catalog validation failed after ${maxRefine} refine attempts:\\n${catalogValidation.errors.join(\"\\n\")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Auto-refine: feed catalog errors back to LLM\n\t\t\tspec = await llmRefine(\n\t\t\t\tspec,\n\t\t\t\t`Fix these catalog errors:\\n${catalogValidation.errors.join(\"\\n\")}\\n\\nUse ONLY functions and sources from the catalog.`,\n\t\t\t\tadapter,\n\t\t\t\t{ ...opts, catalogDescription: catalogPrompt },\n\t\t\t);\n\t\t}\n\t}\n\n\treturn spec;\n}\n\n// ---------------------------------------------------------------------------\n// llmRefine\n// ---------------------------------------------------------------------------\n\n/** Options for {@link llmRefine}. */\nexport type LLMRefineOptions = LLMComposeOptions;\n\n/**\n * Ask an LLM to modify an existing GraphSpec based on feedback or changed requirements.\n *\n * @param currentSpec - The current GraphSpec to modify.\n * @param feedback - Natural language feedback or changed requirements.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options.\n * @returns A new GraphSpec incorporating the feedback.\n * @throws On invalid LLM output or validation failure.\n *\n * @category patterns\n */\nexport async function llmRefine(\n\tcurrentSpec: GraphSpec,\n\tfeedback: string,\n\tadapter: LLMAdapter,\n\topts?: LLMRefineOptions,\n): Promise<GraphSpec> {\n\tlet systemPrompt = LLM_COMPOSE_SYSTEM_PROMPT;\n\tif (opts?.catalogDescription) {\n\t\tsystemPrompt += `\\n\\nAvailable catalog:\\n${opts.catalogDescription}`;\n\t}\n\tif (opts?.systemPromptExtra) {\n\t\tsystemPrompt += `\\n\\n${opts.systemPromptExtra}`;\n\t}\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{\n\t\t\trole: \"user\",\n\t\t\tcontent: `Current GraphSpec:\\n${JSON.stringify(currentSpec, null, 2)}\\n\\nModification request: ${feedback}\\n\\nReturn the complete modified GraphSpec as JSON.`,\n\t\t},\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\t// System boundary: await the adapter's response.\n\tconst response = (await rawResult) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`llmRefine: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateSpec(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`llmRefine: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\treturn parsed as GraphSpec;\n}\n","/**\n * Harness wiring (roadmap §9.0).\n *\n * Reactive collaboration loop: static-topology, flowing data.\n * Composes orchestration (gate), AI (promptNode), reduction (scorer/stratify),\n * and messaging (TopicGraph/bridge) into a 7-stage loop.\n *\n * @module\n */\n\nexport * from \"./bridge.js\";\nexport * from \"./loop.js\";\nexport * from \"./profile.js\";\nexport * from \"./strategy.js\";\nexport * from \"./trace.js\";\nexport * from \"./types.js\";\n","/**\n * Harness bridge factories (roadmap §9.0).\n *\n * Intake bridges, eval source wrapper, before/after comparison,\n * affected-task filter, code-change bridge, and notification effect.\n * All are compositions of existing primitives — no new abstractions.\n *\n * @module\n */\n\nimport type { Node } from \"../../core/node.js\";\nimport { derived, effect, state } from \"../../core/sugar.js\";\nimport { switchMap } from \"../../extra/operators.js\";\nimport { fromAny } from \"../../extra/sources.js\";\nimport type { TopicGraph } from \"../messaging.js\";\n\nimport type { IntakeItem, Severity, TriagedItem } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Generic intake bridge\n// ---------------------------------------------------------------------------\n\n/** Options for {@link createIntakeBridge}. */\nexport interface IntakeBridgeOptions {\n\t/** Name for the effect node (default \"intake-bridge\"). */\n\tname?: string;\n}\n\n/**\n * Generic source→intake bridge factory.\n *\n * Watches a source node for new values, passes each through a user-supplied\n * `parser` that produces zero or more `IntakeItem`s, and publishes them to\n * the given intake topic.\n *\n * This is the generalized pattern behind {@link evalIntakeBridge}. Use it for\n * CI results, test failures, Slack messages, monitoring alerts, or any domain\n * where structured results should flow into a harness loop.\n *\n * @param source - Reactive node emitting domain-specific data.\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param parser - Converts source data into IntakeItem[]. Return empty array to skip.\n * @param opts - Optional configuration.\n * @returns The effect node (for lifecycle management).\n */\nexport function createIntakeBridge<T>(\n\tsource: Node<T>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\tparser: (value: T) => IntakeItem[],\n\topts?: IntakeBridgeOptions,\n): Node<unknown> {\n\treturn effect(\n\t\t[source as Node<unknown>],\n\t\t([value]) => {\n\t\t\tif (value == null) return;\n\t\t\tconst items = parser(value as T);\n\t\t\tfor (const item of items) {\n\t\t\t\tintakeTopic.publish(item);\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"intake-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Generic eval result shape\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal eval result shape accepted by the bridge.\n *\n * TS eval runner uses `EvalRun` from `evals/lib/types.ts` which is a superset\n * of this shape. The bridge only reads what it needs.\n */\nexport interface EvalResult {\n\trun_id: string;\n\tmodel: string;\n\ttasks: EvalTaskResult[];\n}\n\nexport interface EvalTaskResult {\n\ttask_id: string;\n\tvalid: boolean;\n\tjudge_scores?: EvalJudgeScore[];\n}\n\nexport interface EvalJudgeScore {\n\tclaim: string;\n\tpass: boolean;\n\treasoning: string;\n}\n\n// ---------------------------------------------------------------------------\n// Bridge factory\n// ---------------------------------------------------------------------------\n\nexport interface EvalIntakeBridgeOptions {\n\t/** Name for the effect node (default \"eval-intake-bridge\"). */\n\tname?: string;\n\t/** Minimum severity for eval-sourced items (default \"medium\"). */\n\tdefaultSeverity?: Severity;\n}\n\n/**\n * Create an effect node that watches an eval results source and publishes\n * per-criterion findings to an intake topic.\n *\n * Each failing judge criterion produces a separate IntakeItem — not one\n * item per task. This gives the triage stage granular findings to classify.\n *\n * @param evalSource - Node emitting EvalResult (or EvalResult[]).\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param opts - Optional configuration.\n * @returns The effect node (for lifecycle management).\n */\nexport function evalIntakeBridge(\n\tevalSource: Node<EvalResult | EvalResult[]>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\topts?: EvalIntakeBridgeOptions,\n): Node<unknown> {\n\tconst defaultSeverity = opts?.defaultSeverity ?? \"medium\";\n\n\treturn effect(\n\t\t[evalSource],\n\t\t([results]) => {\n\t\t\tif (results == null) return;\n\t\t\tconst runs = Array.isArray(results) ? (results as EvalResult[]) : [results as EvalResult];\n\n\t\t\tfor (const run of runs) {\n\t\t\t\tfor (const task of run.tasks) {\n\t\t\t\t\t// Only process tasks with failures\n\t\t\t\t\tif (task.valid && task.judge_scores?.every((s) => s.pass)) continue;\n\n\t\t\t\t\t// Task-level validity failure (no judge scores or overall invalid)\n\t\t\t\t\tif (!task.valid && (!task.judge_scores || task.judge_scores.length === 0)) {\n\t\t\t\t\t\tintakeTopic.publish({\n\t\t\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\t\t\tsummary: `Task ${task.task_id} invalid (model: ${run.model})`,\n\t\t\t\t\t\t\tevidence: `Run ${run.run_id}: task produced invalid output`,\n\t\t\t\t\t\t\taffectsAreas: [\"graphspec\"],\n\t\t\t\t\t\t\taffectsEvalTasks: [task.task_id],\n\t\t\t\t\t\t\tseverity: defaultSeverity,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Per-criterion findings\n\t\t\t\t\tif (task.judge_scores) {\n\t\t\t\t\t\tfor (const score of task.judge_scores) {\n\t\t\t\t\t\t\tif (score.pass) continue;\n\t\t\t\t\t\t\tintakeTopic.publish({\n\t\t\t\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\t\t\t\tsummary: `${task.task_id}: ${score.claim} (model: ${run.model})`,\n\t\t\t\t\t\t\t\tevidence: score.reasoning,\n\t\t\t\t\t\t\t\taffectsAreas: [\"graphspec\"],\n\t\t\t\t\t\t\t\taffectsEvalTasks: [task.task_id],\n\t\t\t\t\t\t\t\tseverity: defaultSeverity,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"eval-intake-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition A: Eval-driven improvement loop\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap any eval runner as a reactive producer node.\n *\n * When `trigger` emits, calls `runner()` and emits the result downstream.\n * Uses `switchMap` + `fromAny` — the async boundary stays in the source\n * layer (spec §5.10). A new trigger cancels any in-flight run.\n *\n * ```ts\n * const trigger = state(0); // bump to trigger a new run\n * const results = evalSource(trigger, () => runEvals(config));\n * results.subscribe(msgs => { ... });\n * trigger.down([[DATA, 1]]); // fires the runner\n * ```\n *\n * @param trigger - Any node; each new DATA emission fires the runner.\n * @param runner - Returns an EvalResult (or promise of one).\n */\nexport function evalSource<T extends EvalResult>(\n\ttrigger: Node<unknown>,\n\trunner: () => T | Promise<T>,\n): Node<T> {\n\treturn switchMap(trigger, () => fromAny(runner()) as Node<T>);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Per-task delta produced by {@link beforeAfterCompare}. */\nexport interface EvalTaskDelta {\n\ttaskId: string;\n\tbefore: boolean;\n\tafter: boolean;\n\t/** Score-level diff (after − before), undefined if no scores present. */\n\tscoreDiff?: number;\n}\n\n/** Output of {@link beforeAfterCompare}. */\nexport interface EvalDelta {\n\t/** Task IDs that newly fail in `after` (were passing in `before`). */\n\tnewFailures: string[];\n\t/** Task IDs that now pass in `after` (were failing in `before`). */\n\tresolved: string[];\n\t/** Full per-task breakdown. */\n\ttaskDeltas: EvalTaskDelta[];\n\t/** True when net resolutions > net failures. */\n\toverallImproved: boolean;\n}\n\n/**\n * Derived node that computes before/after eval deltas.\n *\n * Pure computation: no LLM, no async. Compares per-task validity and\n * pass counts between two `EvalResult` snapshots.\n *\n * @param before - Node holding the baseline eval result.\n * @param after - Node holding the new eval result.\n */\nexport function beforeAfterCompare(\n\tbefore: Node<EvalResult>,\n\tafter: Node<EvalResult>,\n): Node<EvalDelta> {\n\treturn derived<EvalDelta>(\n\t\t[before as Node<unknown>, after as Node<unknown>],\n\t\t([b, a]) => {\n\t\t\tconst bRes = b as EvalResult;\n\t\t\tconst aRes = a as EvalResult;\n\n\t\t\tconst beforeMap = new Map<string, EvalTaskResult>(bRes.tasks.map((t) => [t.task_id, t]));\n\t\t\tconst afterMap = new Map<string, EvalTaskResult>(aRes.tasks.map((t) => [t.task_id, t]));\n\n\t\t\tconst allIds = new Set([...beforeMap.keys(), ...afterMap.keys()]);\n\t\t\tconst taskDeltas: EvalTaskDelta[] = [];\n\t\t\tconst newFailures: string[] = [];\n\t\t\tconst resolved: string[] = [];\n\n\t\t\tfor (const id of allIds) {\n\t\t\t\tconst bt = beforeMap.get(id);\n\t\t\t\tconst at = afterMap.get(id);\n\t\t\t\tconst beforeValid = bt?.valid ?? false;\n\t\t\t\tconst afterValid = at?.valid ?? false;\n\n\t\t\t\tconst beforeScore = bt?.judge_scores\n\t\t\t\t\t? bt.judge_scores.filter((s) => s.pass).length\n\t\t\t\t\t: undefined;\n\t\t\t\tconst afterScore = at?.judge_scores\n\t\t\t\t\t? at.judge_scores.filter((s) => s.pass).length\n\t\t\t\t\t: undefined;\n\t\t\t\tconst scoreDiff =\n\t\t\t\t\tbeforeScore !== undefined && afterScore !== undefined\n\t\t\t\t\t\t? afterScore - beforeScore\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\ttaskDeltas.push({ taskId: id, before: beforeValid, after: afterValid, scoreDiff });\n\t\t\t\tif (beforeValid && !afterValid) newFailures.push(id);\n\t\t\t\tif (!beforeValid && afterValid) resolved.push(id);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tnewFailures,\n\t\t\t\tresolved,\n\t\t\t\ttaskDeltas,\n\t\t\t\toverallImproved: resolved.length > newFailures.length,\n\t\t\t};\n\t\t},\n\t\t{ name: \"eval-delta\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/**\n * Derived node that selects which eval task IDs to re-run.\n *\n * Collects `affectsEvalTasks` from all triaged items, deduplicates, then\n * optionally intersects with `fullTaskSet`. Returns a sorted array of IDs.\n *\n * Use this to avoid re-running the full eval suite after each fix: only the\n * tasks that the triaged items claim to affect are returned.\n *\n * @param issues - Node holding the current list of triaged items.\n * @param fullTaskSet - Optional node (or plain array) of all known task IDs.\n * When provided, output is the intersection.\n */\nexport function affectedTaskFilter(\n\tissues: Node<readonly TriagedItem[]>,\n\tfullTaskSet?: Node<readonly string[]> | readonly string[],\n): Node<string[]> {\n\tconst taskSetNode: Node<unknown> | null =\n\t\tfullTaskSet == null\n\t\t\t? null\n\t\t\t: Array.isArray(fullTaskSet)\n\t\t\t\t? (state(fullTaskSet as readonly string[]) as Node<unknown>)\n\t\t\t\t: (fullTaskSet as Node<unknown>);\n\n\tconst deps: Node<unknown>[] = [issues as Node<unknown>];\n\tif (taskSetNode) deps.push(taskSetNode);\n\n\treturn derived<string[]>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst items = values[0] as readonly TriagedItem[];\n\t\t\tconst all = taskSetNode ? new Set(values[1] as readonly string[]) : null;\n\n\t\t\tconst affected = new Set<string>();\n\t\t\tfor (const item of items) {\n\t\t\t\tfor (const id of item.affectsEvalTasks ?? []) {\n\t\t\t\t\tif (all == null || all.has(id)) affected.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn [...affected].sort();\n\t\t},\n\t\t{ name: \"affected-task-filter\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition D: Quality gate (CI/CD)\n// ---------------------------------------------------------------------------\n\n/** A single lint error emitted by a CI tool. */\nexport interface LintError {\n\tfile: string;\n\tline: number;\n\tcol: number;\n\trule: string;\n\tmessage: string;\n}\n\n/** A single test failure emitted by a test runner. */\nexport interface TestFailure {\n\ttestId: string;\n\tfile: string;\n\tmessage: string;\n}\n\n/** Structured code-change / CI event. */\nexport interface CodeChange {\n\t/** Files touched by the change. */\n\tfiles: string[];\n\tlintErrors?: LintError[];\n\ttestFailures?: TestFailure[];\n}\n\n/** Options for {@link codeChangeBridge}. */\nexport interface CodeChangeBridgeOptions {\n\t/** Name for the effect node (default \"code-change-bridge\"). */\n\tname?: string;\n\t/** Default severity for generated IntakeItems (default \"high\"). */\n\tdefaultSeverity?: Severity;\n}\n\n/**\n * Intake bridge for code-change / CI events.\n *\n * Watches a source node for `CodeChange` events and publishes one\n * `IntakeItem` per lint error and per test failure to the intake topic.\n * Pass a custom `parser` to override the default mapping.\n *\n * @param source - Node emitting CodeChange events.\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param parser - Optional custom parser (overrides default).\n * @param opts - Optional configuration.\n */\nexport function codeChangeBridge(\n\tsource: Node<CodeChange>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\tparser?: (change: CodeChange) => IntakeItem[],\n\topts?: CodeChangeBridgeOptions,\n): Node<unknown> {\n\tconst defaultSeverity = opts?.defaultSeverity ?? \"high\";\n\n\tfunction defaultParser(change: CodeChange): IntakeItem[] {\n\t\tconst items: IntakeItem[] = [];\n\t\tfor (const err of change.lintErrors ?? []) {\n\t\t\titems.push({\n\t\t\t\tsource: \"code-change\",\n\t\t\t\tsummary: `Lint: ${err.rule} in ${err.file}:${err.line}`,\n\t\t\t\tevidence: err.message,\n\t\t\t\taffectsAreas: [err.file],\n\t\t\t\tseverity: defaultSeverity,\n\t\t\t});\n\t\t}\n\t\tfor (const fail of change.testFailures ?? []) {\n\t\t\titems.push({\n\t\t\t\tsource: \"test\",\n\t\t\t\tsummary: `Test failure: ${fail.testId}`,\n\t\t\t\tevidence: fail.message,\n\t\t\t\taffectsAreas: [fail.file],\n\t\t\t\taffectsEvalTasks: [fail.testId],\n\t\t\t\tseverity: defaultSeverity,\n\t\t\t});\n\t\t}\n\t\treturn items;\n\t}\n\n\tconst resolve = parser ?? defaultParser;\n\n\treturn effect(\n\t\t[source as Node<unknown>],\n\t\t([change]) => {\n\t\t\tif (change == null) return;\n\t\t\tfor (const item of resolve(change as CodeChange)) {\n\t\t\t\tintakeTopic.publish(item);\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"code-change-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Transport function for {@link notifyEffect}. Sync or async. */\nexport type NotifyTransport<T> = (item: T) => void | Promise<void>;\n\n/** Options for {@link notifyEffect}. */\nexport interface NotifyEffectOptions {\n\t/** Name for the effect node (default \"notify-effect\"). */\n\tname?: string;\n}\n\n/**\n * Effect node that sends each new topic entry to an external channel.\n *\n * The `transport` function is called for every item published to `topic`.\n * Async transports are bridged via `fromAny` (spec §5.10 compliant).\n *\n * Typical use: Slack webhook, GitHub PR comment, email notification, etc.\n * The factory provides reactive wiring; the transport supplies domain logic.\n *\n * ```ts\n * notifyEffect(alertQueue, async (item) => {\n * await fetch(SLACK_WEBHOOK, { method: 'POST', body: JSON.stringify({ text: item.summary }) });\n * });\n * ```\n *\n * @param topic - TopicGraph whose latest entry triggers the notification.\n * @param transport - Called with each new item. May return a Promise.\n * @param opts - Optional configuration.\n */\nexport function notifyEffect<T>(\n\ttopic: TopicGraph<T>,\n\ttransport: NotifyTransport<T>,\n\topts?: NotifyEffectOptions,\n): Node<unknown> {\n\treturn effect(\n\t\t[topic.latest as Node<unknown>],\n\t\t([item]) => {\n\t\t\tif (item == null) return;\n\t\t\t// transport is a side effect (webhook, Slack, email). Async transports\n\t\t\t// are fire-and-forget — the Promise result does not feed back into the\n\t\t\t// graph. Suppress unhandled-rejection noise by voiding the return.\n\t\t\tvoid transport(item as T);\n\t\t},\n\t\t{ name: opts?.name ?? \"notify-effect\" },\n\t);\n}\n","/**\n * Harness wiring types (roadmap §9.0).\n *\n * Shared types for the reactive collaboration loop: intake, triage, queue,\n * gate, execute, verify, reflect. These types are intentionally domain-agnostic\n * — the harness loop is not specific to eval workflows.\n *\n * @module\n */\n\n// ---------------------------------------------------------------------------\n// Intake\n// ---------------------------------------------------------------------------\n\n/** Sources that can produce intake items. */\nexport type IntakeSource = \"eval\" | \"test\" | \"human\" | \"code-change\" | \"hypothesis\" | \"parity\";\n\n/** Severity levels for intake items. */\nexport type Severity = \"critical\" | \"high\" | \"medium\" | \"low\";\n\n/** Root cause categories for triage classification. */\nexport type RootCause =\n\t| \"composition\"\n\t| \"missing-fn\"\n\t| \"bad-docs\"\n\t| \"schema-gap\"\n\t| \"regression\"\n\t| \"unknown\";\n\n/** Intervention types that address root causes. */\nexport type Intervention =\n\t| \"template\"\n\t| \"catalog-fn\"\n\t| \"docs\"\n\t| \"wrapper\"\n\t| \"schema-change\"\n\t| \"investigate\";\n\n/** Routing destinations after triage. */\nexport type QueueRoute = \"auto-fix\" | \"needs-decision\" | \"investigation\" | \"backlog\";\n\n/** Ordered queue route names for iteration. */\nexport const QUEUE_NAMES: readonly QueueRoute[] = [\n\t\"auto-fix\",\n\t\"needs-decision\",\n\t\"investigation\",\n\t\"backlog\",\n];\n\n/**\n * An item entering the harness loop via the INTAKE stage.\n *\n * All intake sources produce this uniform shape — the intake topic\n * doesn't care where items came from.\n */\nexport interface IntakeItem {\n\tsource: IntakeSource;\n\tsummary: string;\n\tevidence: string;\n\taffectsAreas: string[];\n\taffectsEvalTasks?: string[];\n\tseverity?: Severity;\n\trelatedTo?: string[];\n\t/** Item-carried reingestion count. Incremented on each full-loop reingestion. */\n\t_reingestions?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Triage output\n// ---------------------------------------------------------------------------\n\n/** Output of the TRIAGE stage — enriched intake item with classification. */\nexport interface TriagedItem extends IntakeItem {\n\trootCause: RootCause;\n\tintervention: Intervention;\n\troute: QueueRoute;\n\tpriority: number;\n\ttriageReasoning?: string;\n\t/** Item-carried retry count. Incremented on each fast-retry pass. */\n\t_retries?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Strategy model\n// ---------------------------------------------------------------------------\n\n/** Effectiveness record for a rootCause→intervention pair. */\nexport interface StrategyEntry {\n\trootCause: RootCause;\n\tintervention: Intervention;\n\tattempts: number;\n\tsuccesses: number;\n\tsuccessRate: number;\n}\n\n/** Key format: `${rootCause}→${intervention}`. */\nexport type StrategyKey = `${RootCause}→${Intervention}`;\n\nexport function strategyKey(rootCause: RootCause, intervention: Intervention): StrategyKey {\n\treturn `${rootCause}→${intervention}`;\n}\n\n// ---------------------------------------------------------------------------\n// Execution & verification\n// ---------------------------------------------------------------------------\n\n/** LLM output shape from the EXECUTE stage (partial — lacks `item`). */\nexport type ExecuteOutput = {\n\toutcome: \"success\" | \"failure\" | \"partial\";\n\tdetail: string;\n};\n\n/** Full execution result assembled downstream (LLM output + context). */\nexport interface ExecutionResult {\n\titem: TriagedItem;\n\toutcome: \"success\" | \"failure\" | \"partial\";\n\tdetail: string;\n}\n\n/** Whether an error is self-correctable (fast-retry) or structural (full loop). */\nexport type ErrorClass = \"self-correctable\" | \"structural\";\n\n/** Classifier for fast-retry path. */\nexport type ErrorClassifier = (result: ExecutionResult) => ErrorClass;\n\n/** Default error classifier: parse/config errors are self-correctable. */\nexport function defaultErrorClassifier(result: ExecutionResult): ErrorClass {\n\tconst d = result.detail.toLowerCase();\n\tif (\n\t\td.includes(\"parse\") ||\n\t\td.includes(\"json\") ||\n\t\td.includes(\"config\") ||\n\t\td.includes(\"validation\") ||\n\t\td.includes(\"syntax\")\n\t) {\n\t\treturn \"self-correctable\";\n\t}\n\treturn \"structural\";\n}\n\n// ---------------------------------------------------------------------------\n// Verification output\n// ---------------------------------------------------------------------------\n\n/** Result of the VERIFY stage. */\nexport interface VerifyResult {\n\titem: TriagedItem;\n\texecution: ExecutionResult;\n\tverified: boolean;\n\tfindings: string[];\n\terrorClass?: ErrorClass;\n}\n\n// ---------------------------------------------------------------------------\n// Priority scoring\n// ---------------------------------------------------------------------------\n\n/** Configurable signals for priority scoring. */\nexport interface PrioritySignals {\n\t/** Per-severity base weight (default: critical=100, high=70, medium=40, low=10). */\n\tseverityWeights?: Partial<Record<Severity, number>>;\n\t/** Decay rate per second for attention decay (default ~1.15e-6 ≈ 7-day half-life). */\n\tdecayRate?: number;\n\t/** Strategy model effectiveness boost threshold (default 0.7). */\n\teffectivenessThreshold?: number;\n\t/** Strategy model effectiveness boost amount (default 15). */\n\teffectivenessBoost?: number;\n}\n\n/** Default severity weights. */\nexport const DEFAULT_SEVERITY_WEIGHTS: Record<Severity, number> = {\n\tcritical: 100,\n\thigh: 70,\n\tmedium: 40,\n\tlow: 10,\n};\n\n/** Default decay rate: ~7-day half-life. */\nexport const DEFAULT_DECAY_RATE = Math.LN2 / (7 * 24 * 3600);\n\n// ---------------------------------------------------------------------------\n// Harness loop configuration\n// ---------------------------------------------------------------------------\n\n/** Per-queue configuration in the harness loop. */\nexport interface QueueConfig {\n\t/** Whether this queue is gated (requires human approval). */\n\tgated: boolean;\n\t/** Maximum pending items in the gate (default Infinity). */\n\tmaxPending?: number;\n\t/** Start the gate in open (auto-approve) mode? */\n\tstartOpen?: boolean;\n}\n\n/** Default queue configurations. */\nexport const DEFAULT_QUEUE_CONFIGS: Record<QueueRoute, QueueConfig> = {\n\t\"auto-fix\": { gated: false },\n\t\"needs-decision\": { gated: true },\n\tinvestigation: { gated: true },\n\tbacklog: { gated: false, startOpen: false },\n};\n\n/** Options for {@link harnessLoop}. */\nexport interface HarnessLoopOptions {\n\t/** LLM adapter for promptNode-based stages (triage, execute, verify, reflect). */\n\tadapter: unknown; // LLMAdapter — kept as unknown to avoid circular dep\n\n\t/** Custom triage prompt (receives IntakeItem + strategy model as context). */\n\ttriagePrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Custom execute prompt. */\n\texecutePrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Custom verify prompt. */\n\tverifyPrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Per-queue configuration overrides. */\n\tqueues?: Partial<Record<QueueRoute, QueueConfig>>;\n\n\t/** Priority scoring signals. */\n\tpriority?: PrioritySignals;\n\n\t/** Error classifier for fast-retry path. */\n\terrorClassifier?: ErrorClassifier;\n\n\t/** Max fast-retries per item before routing to full intake (default 2). */\n\tmaxRetries?: number;\n\n\t/** Global retry cap across all items — circuit breaker (default maxRetries × 10). */\n\tmaxTotalRetries?: number;\n\n\t/** Max re-ingestions from verify→intake before giving up (default 1). */\n\tmaxReingestions?: number;\n\n\t/** Global reingestion cap across all items — circuit breaker (default maxReingestions × 10). */\n\tmaxTotalReingestions?: number;\n\n\t/** Retained limit for topic logs (default 1000). */\n\tretainedLimit?: number;\n}\n","/**\n * Strategy model and priority scoring (roadmap §9.0).\n *\n * Pure-computation derived nodes — no LLM, no async.\n *\n * @module\n */\n\nimport { monotonicNs } from \"../../core/clock.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { derived } from \"../../core/sugar.js\";\nimport { reactiveMap } from \"../../extra/reactive-map.js\";\nimport { decay } from \"../memory.js\";\n\nimport {\n\tDEFAULT_DECAY_RATE,\n\tDEFAULT_SEVERITY_WEIGHTS,\n\ttype Intervention,\n\ttype PrioritySignals,\n\ttype RootCause,\n\ttype StrategyEntry,\n\ttype StrategyKey,\n\tstrategyKey,\n\ttype TriagedItem,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Strategy model\n// ---------------------------------------------------------------------------\n\n/** Snapshot shape for the strategy model node. */\nexport type StrategySnapshot = ReadonlyMap<StrategyKey, StrategyEntry>;\n\n/** Bundle returned by {@link strategyModel}. */\nexport interface StrategyModelBundle {\n\t/** Reactive node — current strategy map. */\n\treadonly node: Node<StrategySnapshot>;\n\n\t/** Record a completed issue (success or failure). */\n\trecord(rootCause: RootCause, intervention: Intervention, success: boolean): void;\n\n\t/** Look up effectiveness for a specific pair. */\n\tlookup(rootCause: RootCause, intervention: Intervention): StrategyEntry | undefined;\n\n\t/** Tear down internal keepalive subscriptions. */\n\tdispose(): void;\n}\n\n/**\n * Create a strategy model that tracks `rootCause × intervention → successRate`\n * over completed issues. Pure derived computation — no LLM.\n *\n * The model feeds back into TRIAGE for routing hints.\n */\nexport function strategyModel(): StrategyModelBundle {\n\tconst _map = reactiveMap<StrategyKey, StrategyEntry>({ name: \"strategy-entries\" });\n\n\t// Derived node that projects the reactive map into a plain Map snapshot.\n\tconst snapshot = derived<StrategySnapshot>(\n\t\t[_map.entries],\n\t\t([mapSnap]) => {\n\t\t\tconst raw = mapSnap as ReadonlyMap<StrategyKey, StrategyEntry>;\n\t\t\t// Return a fresh frozen copy so consumers see a stable reference.\n\t\t\treturn new Map(raw);\n\t\t},\n\t\t{\n\t\t\tname: \"strategy-model\",\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst am = a as StrategySnapshot;\n\t\t\t\tconst bm = b as StrategySnapshot;\n\t\t\t\tif (am.size !== bm.size) return false;\n\t\t\t\tfor (const [k, v] of am) {\n\t\t\t\t\tconst bv = bm.get(k);\n\t\t\t\t\tif (!bv || v.attempts !== bv.attempts || v.successes !== bv.successes) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\tfunction record(rootCause: RootCause, intervention: Intervention, success: boolean): void {\n\t\tconst key = strategyKey(rootCause, intervention);\n\t\tconst existing = _map.get(key);\n\t\tconst attempts = (existing?.attempts ?? 0) + 1;\n\t\tconst successes = (existing?.successes ?? 0) + (success ? 1 : 0);\n\t\t_map.set(key, {\n\t\t\trootCause,\n\t\t\tintervention,\n\t\t\tattempts,\n\t\t\tsuccesses,\n\t\t\tsuccessRate: successes / attempts,\n\t\t});\n\t}\n\n\tfunction lookup(rootCause: RootCause, intervention: Intervention): StrategyEntry | undefined {\n\t\treturn _map.get(strategyKey(rootCause, intervention));\n\t}\n\n\t// Keep the derived alive so get() works without an external subscriber.\n\tconst _unsub = snapshot.subscribe(() => {});\n\n\tfunction dispose(): void {\n\t\t_unsub();\n\t}\n\n\treturn { node: snapshot, record, lookup, dispose };\n}\n\n// ---------------------------------------------------------------------------\n// Priority scoring\n// ---------------------------------------------------------------------------\n\n/**\n * Create a priority scoring derived node for a single triaged item.\n *\n * Combines severity weight, attention decay, strategy model effectiveness,\n * and an optional external urgency signal.\n *\n * @param item - Node holding the triaged item.\n * @param strategy - Strategy model node.\n * @param lastInteractionNs - Node holding the monotonic timestamp (ns) of last human interaction.\n * @param urgency - Optional external urgency signal node (0–1 scale).\n * @param signals - Configurable scoring parameters.\n */\nexport function priorityScore(\n\titem: Node<TriagedItem>,\n\tstrategy: Node<StrategySnapshot>,\n\tlastInteractionNs: Node<number>,\n\turgency?: Node<number>,\n\tsignals?: PrioritySignals,\n): Node<number> {\n\tconst severityWeights = { ...DEFAULT_SEVERITY_WEIGHTS, ...signals?.severityWeights };\n\tconst decayRate = signals?.decayRate ?? DEFAULT_DECAY_RATE;\n\tconst effectivenessThreshold = signals?.effectivenessThreshold ?? 0.7;\n\tconst effectivenessBoost = signals?.effectivenessBoost ?? 15;\n\n\tconst deps: Node<unknown>[] = [item, strategy, lastInteractionNs];\n\tif (urgency) deps.push(urgency);\n\n\treturn derived<number>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst itm = values[0] as TriagedItem;\n\t\t\tconst strat = values[1] as StrategySnapshot;\n\t\t\tconst lastNs = values[2] as number;\n\t\t\tconst urg = urgency ? (values[3] as number) : 0;\n\n\t\t\t// Base score from severity\n\t\t\tconst baseWeight = severityWeights[itm.severity ?? \"medium\"];\n\t\t\tconst ageSeconds = (monotonicNs() - lastNs) / 1e9;\n\t\t\tlet score = decay(baseWeight, ageSeconds, decayRate, 0);\n\n\t\t\t// Strategy model boost\n\t\t\tconst key = strategyKey(itm.rootCause, itm.intervention);\n\t\t\tconst entry = strat.get(key);\n\t\t\tif (entry && entry.successRate >= effectivenessThreshold) {\n\t\t\t\tscore += effectivenessBoost;\n\t\t\t}\n\n\t\t\t// External urgency boost (0–1 scale → 0–20 points)\n\t\t\tscore += urg * 20;\n\n\t\t\treturn score;\n\t\t},\n\t\t{ name: \"priority-score\" },\n\t);\n}\n","/**\n * harnessLoop() factory (roadmap §9.0).\n *\n * Wires the static 7-stage topology: INTAKE → TRIAGE → QUEUE → GATE →\n * EXECUTE → VERIFY → REFLECT. Static topology, flowing data — the Kafka\n * insight applied to human+LLM collaboration.\n *\n * @module\n */\n\nimport type { Node } from \"../../core/node.js\";\nimport { node } from \"../../core/node.js\";\nimport { effect, state } from \"../../core/sugar.js\";\nimport { merge, withLatestFrom } from \"../../extra/operators.js\";\nimport { Graph } from \"../../graph/graph.js\";\nimport { trackingKey, tryIncrementBounded } from \"../_internal.js\";\nimport type { LLMAdapter } from \"../ai.js\";\nimport { promptNode } from \"../ai.js\";\nimport { TopicGraph } from \"../messaging.js\";\nimport { type GateController, gate } from \"../orchestration.js\";\nimport { type StrategyModelBundle, type StrategySnapshot, strategyModel } from \"./strategy.js\";\nimport {\n\tDEFAULT_QUEUE_CONFIGS,\n\tdefaultErrorClassifier,\n\ttype ErrorClass,\n\ttype ErrorClassifier,\n\ttype ExecuteOutput,\n\ttype ExecutionResult,\n\ttype HarnessLoopOptions,\n\ttype IntakeItem,\n\tQUEUE_NAMES,\n\ttype QueueConfig,\n\ttype QueueRoute,\n\ttype TriagedItem,\n\ttype VerifyResult,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Default prompts\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_TRIAGE_PROMPT = `You are a triage classifier for a reactive collaboration harness.\n\nGiven an intake item, classify it and output JSON:\n{\n \"rootCause\": \"composition\" | \"missing-fn\" | \"bad-docs\" | \"schema-gap\" | \"regression\" | \"unknown\",\n \"intervention\": \"template\" | \"catalog-fn\" | \"docs\" | \"wrapper\" | \"schema-change\" | \"investigate\",\n \"route\": \"auto-fix\" | \"needs-decision\" | \"investigation\" | \"backlog\",\n \"priority\": <number 0-100>,\n \"triageReasoning\": \"<one sentence>\"\n}\n\nStrategy model (past effectiveness):\n{{strategy}}\n\nIntake item:\n{{item}}`;\n\nconst DEFAULT_EXECUTE_PROMPT = `You are an implementation agent.\n\nGiven a triaged issue with root cause and intervention type, produce a fix.\n\nIssue:\n{{item}}\n\nOutput JSON:\n{\n \"outcome\": \"success\" | \"failure\" | \"partial\",\n \"detail\": \"<description of what was done or what failed>\"\n}`;\n\nconst DEFAULT_VERIFY_PROMPT = `You are a QA reviewer.\n\nGiven an execution result, verify whether the fix is correct.\n\nExecution:\n{{execution}}\n\nOriginal issue:\n{{item}}\n\nOutput JSON:\n{\n \"verified\": true/false,\n \"findings\": [\"<finding1>\", ...],\n \"errorClass\": \"self-correctable\" | \"structural\" // only if verified=false\n}`;\n\n// ---------------------------------------------------------------------------\n// HarnessGraph\n// ---------------------------------------------------------------------------\n\n/** The graph returned by {@link harnessLoop}. */\nexport class HarnessGraph extends Graph {\n\t/** Intake topic — publish items here to enter the loop. */\n\treadonly intake: TopicGraph<IntakeItem>;\n\n\t/** Per-route queue topics. */\n\treadonly queues: ReadonlyMap<QueueRoute, TopicGraph<TriagedItem>>;\n\n\t/** Per-route gate controllers (only for gated queues). */\n\treadonly gates: ReadonlyMap<QueueRoute, GateController<TriagedItem>>;\n\n\t/** Strategy model bundle — record outcomes, lookup effectiveness. */\n\treadonly strategy: StrategyModelBundle;\n\n\t/** Verify results topic — subscribe to see verification outcomes. */\n\treadonly verifyResults: TopicGraph<VerifyResult>;\n\n\t/** Global retry count across all items (circuit breaker). Reactive — subscribable. */\n\treadonly totalRetries: Node<number>;\n\n\t/** Global reingestion count across all items (circuit breaker). Reactive — subscribable. */\n\treadonly totalReingestions: Node<number>;\n\n\tconstructor(\n\t\tname: string,\n\t\tintake: TopicGraph<IntakeItem>,\n\t\tqueues: Map<QueueRoute, TopicGraph<TriagedItem>>,\n\t\tgates: Map<QueueRoute, GateController<TriagedItem>>,\n\t\tstrategy: StrategyModelBundle,\n\t\tverifyResults: TopicGraph<VerifyResult>,\n\t\ttotalRetries: Node<number>,\n\t\ttotalReingestions: Node<number>,\n\t) {\n\t\tsuper(name);\n\t\tthis.intake = intake;\n\t\tthis.queues = queues;\n\t\tthis.gates = gates;\n\t\tthis.strategy = strategy;\n\t\tthis.verifyResults = verifyResults;\n\t\tthis.totalRetries = totalRetries;\n\t\tthis.totalReingestions = totalReingestions;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// harnessLoop factory\n// ---------------------------------------------------------------------------\n\n/**\n * Wire the reactive collaboration loop as a static-topology graph.\n *\n * The loop has 7 stages:\n * 1. **INTAKE** — items arrive from multiple sources via `intake.publish()`\n * 2. **TRIAGE** — promptNode classifies, routes, and prioritizes\n * 3. **QUEUE** — 4 priority-ordered TopicGraphs (auto-fix, needs-decision, investigation, backlog)\n * 4. **GATE** — human approval on configurable queues\n * 5. **EXECUTE** — promptNode or human implements the fix\n * 6. **VERIFY** — promptNode reviews + optional fast-retry\n * 7. **REFLECT** — strategy model records outcomes\n *\n * @param name - Graph name.\n * @param opts - Configuration.\n * @returns HarnessGraph with controller accessors.\n */\nexport function harnessLoop(name: string, opts: HarnessLoopOptions): HarnessGraph {\n\tconst adapter = opts.adapter as LLMAdapter;\n\tconst maxRetries = opts.maxRetries ?? 2;\n\tconst retainedLimit = opts.retainedLimit ?? 1000;\n\tconst errorClassifier: ErrorClassifier = opts.errorClassifier ?? defaultErrorClassifier;\n\n\t// Merge queue configs with defaults\n\tconst queueConfigs = new Map<QueueRoute, QueueConfig>();\n\tfor (const route of QUEUE_NAMES) {\n\t\tqueueConfigs.set(route, {\n\t\t\t...DEFAULT_QUEUE_CONFIGS[route],\n\t\t\t...opts.queues?.[route],\n\t\t});\n\t}\n\n\t// --- Stage 1: INTAKE ---\n\tconst intake = new TopicGraph<IntakeItem>(\"intake\", { retainedLimit });\n\n\t// --- Strategy model (used by triage + reflect) ---\n\tconst strategy = strategyModel();\n\n\t// --- Stage 2: TRIAGE ---\n\t// Strategy context uses withLatestFrom: intake.latest is the reactive trigger,\n\t// strategy.node is sampled without being a trigger. This breaks the feedback\n\t// cycle (verify → strategy.record() → strategy.node) reactively — strategy\n\t// changes don't re-fire triage, only new intake items do.\n\tconst triageInput = withLatestFrom(\n\t\tintake.latest as Node<unknown>,\n\t\tstrategy.node as Node<unknown>,\n\t);\n\n\tconst triageNode = promptNode<TriagedItem>(\n\t\tadapter,\n\t\t[triageInput as Node<unknown>],\n\t\topts.triagePrompt ??\n\t\t\t((pair: unknown) => {\n\t\t\t\tconst [item, strat] = pair as [unknown, StrategySnapshot];\n\t\t\t\t// Empty text → promptNode's SENTINEL gate skips the LLM call.\n\t\t\t\tif (!item) return \"\";\n\t\t\t\treturn DEFAULT_TRIAGE_PROMPT.replace(\n\t\t\t\t\t\"{{strategy}}\",\n\t\t\t\t\tJSON.stringify(Array.from(strat.entries())),\n\t\t\t\t).replace(\"{{item}}\", JSON.stringify(item));\n\t\t\t}),\n\t\t{\n\t\t\tname: \"triage\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Stage 3: QUEUE ---\n\tconst queueTopics = new Map<QueueRoute, TopicGraph<TriagedItem>>();\n\tfor (const route of QUEUE_NAMES) {\n\t\tqueueTopics.set(route, new TopicGraph<TriagedItem>(`queue/${route}`, { retainedLimit }));\n\t}\n\n\t// Router: merge intake fields into triage classification before routing to queue.\n\t// The LLM only returns {rootCause, intervention, route, priority} — the router\n\t// pairs it with the original intake item (summary, evidence, etc.).\n\t// Sample triageInput (not intake.latest) — triageInput holds the [item, strategy]\n\t// pair that *triggered* this specific triage, so we get the correct item even if\n\t// a newer intake item has arrived since. triageNode triggers; triageInput sampled.\n\tconst routerInput = withLatestFrom(triageNode as Node<unknown>, triageInput as Node<unknown>);\n\tconst router = effect([routerInput as Node<unknown>], ([pair]) => {\n\t\tif (pair == null) return;\n\t\tconst [classification, triagePair] = pair as [\n\t\t\tTriagedItem | null,\n\t\t\t[IntakeItem | null, StrategySnapshot] | null,\n\t\t];\n\t\tif (!classification || !classification.route) return;\n\t\tconst intakeItem = triagePair?.[0];\n\t\tconst merged: TriagedItem = { ...intakeItem, ...classification };\n\t\tconst topic = queueTopics.get(merged.route);\n\t\tif (topic) topic.publish(merged);\n\t});\n\tconst routerUnsub = router.subscribe(() => {});\n\n\t// --- Stage 4: GATE ---\n\t// Create a container graph for gates (gate() requires a Graph to register nodes in)\n\tconst gateGraph = new Graph(\"gates\");\n\tconst gateControllers = new Map<QueueRoute, GateController<TriagedItem>>();\n\n\tfor (const route of QUEUE_NAMES) {\n\t\tconst config = queueConfigs.get(route)!;\n\t\tconst topic = queueTopics.get(route)!;\n\n\t\tif (config.gated) {\n\t\t\t// Register the topic's latest node in the gate graph so gate() can resolve it\n\t\t\tgateGraph.add(`${route}/source`, topic.latest as Node<unknown>);\n\t\t\tconst ctrl = gate<TriagedItem>(gateGraph, `${route}/gate`, `${route}/source`, {\n\t\t\t\tmaxPending: config.maxPending,\n\t\t\t\tstartOpen: config.startOpen,\n\t\t\t});\n\t\t\tgateControllers.set(route, ctrl);\n\t\t}\n\t}\n\n\t// --- Stage 5: EXECUTE ---\n\t// Merge all gate outputs + ungated queue latests + retry feedback into a\n\t// single execute input using the merge() operator (no imperative .down()).\n\tconst retryTopic = new TopicGraph<TriagedItem>(\"retry-input\", { retainedLimit });\n\n\tconst queueOutputs: Node<TriagedItem | null>[] = [];\n\tfor (const route of QUEUE_NAMES) {\n\t\tconst config = queueConfigs.get(route)!;\n\t\tif (config.gated && gateControllers.has(route)) {\n\t\t\tqueueOutputs.push(gateControllers.get(route)!.node as Node<TriagedItem | null>);\n\t\t} else {\n\t\t\tqueueOutputs.push(queueTopics.get(route)!.latest as Node<TriagedItem | null>);\n\t\t}\n\t}\n\tqueueOutputs.push(retryTopic.latest as Node<TriagedItem | null>);\n\n\tconst executeInput = merge<TriagedItem | null>(...queueOutputs);\n\n\tconst executeNode = promptNode<ExecuteOutput>(\n\t\tadapter,\n\t\t[executeInput as Node<unknown>],\n\t\topts.executePrompt ??\n\t\t\t((item: unknown) => DEFAULT_EXECUTE_PROMPT.replace(\"{{item}}\", JSON.stringify(item))),\n\t\t{\n\t\t\tname: \"execute\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Execute context: [execOutput, item] captured once per execute-wave ---\n\t//\n\t// executeInput feeds into executeNode (dep) AND later into verifyNode (dep).\n\t// Without this node, verifyNode would fire twice per wave in the retry path:\n\t// once when executeNode settles (with stale item from prevData), and once when\n\t// executeInput delivers the retry item directly. The second fire would pair the\n\t// correct item with a verify output that was computed using the wrong item.\n\t//\n\t// withLatestFrom(executeNode, executeInput) fires exactly once per execute-wave:\n\t// executeInput notifies executeNode first (depth-first), executeNode runs fn and\n\t// settles in executeContextNode.dep[0], then executeInput settles in dep[1].\n\t// dirtyDepCount reaches 0 only after both settle → fn runs once with correct data.\n\tconst executeContextNode = withLatestFrom(\n\t\texecuteNode as Node<unknown>,\n\t\texecuteInput as Node<unknown>,\n\t);\n\n\t// --- Stage 6: VERIFY ---\n\tconst verifyResults = new TopicGraph<VerifyResult>(\"verify-results\", { retainedLimit });\n\n\t// The LLM returns only {verified, findings, errorClass?}. We type the promptNode\n\t// output as the partial shape and assemble the full VerifyResult downstream.\n\ttype VerifyOutput = { verified: boolean; findings: string[]; errorClass?: ErrorClass };\n\n\t// verifyNode depends on executeContextNode ([execOutput, item]) — single dep.\n\t// This ensures verifyNode fires once per execute-wave with the correct item.\n\tconst verifyNode = promptNode<VerifyOutput>(\n\t\tadapter,\n\t\t[executeContextNode as Node<unknown>],\n\t\topts.verifyPrompt ??\n\t\t\t((ctxPair: unknown) => {\n\t\t\t\tconst [execution, item] = ctxPair as [ExecuteOutput | null, unknown];\n\t\t\t\treturn DEFAULT_VERIFY_PROMPT.replace(\"{{execution}}\", JSON.stringify(execution)).replace(\n\t\t\t\t\t\"{{item}}\",\n\t\t\t\t\tJSON.stringify(item),\n\t\t\t\t);\n\t\t\t}),\n\t\t{\n\t\t\tname: \"verify\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Fast-retry path ---\n\t// verifyContext = withLatestFrom(verifyNode, executeContextNode):\n\t// [verifyOutput, [execOutput, item]]\n\t// Fires once when verifyNode settles; executeContextNode is sampled as secondary.\n\tconst verifyContext = withLatestFrom(\n\t\tverifyNode as Node<unknown>,\n\t\texecuteContextNode as Node<unknown>,\n\t);\n\n\tconst maxReingestions = opts.maxReingestions ?? 1;\n\tconst maxTotalRetries = Math.min(opts.maxTotalRetries ?? maxRetries * 10, 100);\n\tconst maxTotalReingestions = Math.min(opts.maxTotalReingestions ?? maxReingestions * 10, 100);\n\tconst totalRetries = state(0);\n\tconst totalReingestions = state(0);\n\n\t// Uses shared `tryIncrementBounded` (patterns/_internal.ts) — documented\n\t// P3 exception for self-owned counters read+written from a single call\n\t// site (`fastRetry` effect below).\n\n\t// Use raw node() so we can check batchData[0] directly — effect() falls back\n\t// to ctx.prevData[0] when verifyContext emits RESOLVED (secondary-only wave),\n\t// which would re-fire with stale context and create phantom retries.\n\tconst fastRetry = node([verifyContext as Node<unknown>], (batchData, _actions) => {\n\t\tconst batch = batchData[0];\n\t\tif (batch == null || batch.length === 0) return; // RESOLVED or not involved — skip\n\t\tconst ctxVal = batch[batch.length - 1];\n\t\tif (ctxVal == null) return;\n\t\t// verifyContext shape: [verifyOutput, [execOutput, item]]\n\t\tconst [vo, execCtx] = ctxVal as [\n\t\t\tVerifyOutput | null,\n\t\t\t[ExecuteOutput | null, TriagedItem | null] | null,\n\t\t];\n\t\tconst [execRaw, item] = execCtx ?? [null, null];\n\t\tif (!vo || !item) return;\n\n\t\t// Assemble full ExecutionResult + VerifyResult from LLM outputs + context\n\t\tconst exec: ExecutionResult = {\n\t\t\titem,\n\t\t\toutcome: execRaw?.outcome ?? \"failure\",\n\t\t\tdetail: execRaw?.detail ?? \"unknown\",\n\t\t};\n\t\tconst vr: VerifyResult = {\n\t\t\titem,\n\t\t\texecution: exec,\n\t\t\tverified: vo.verified,\n\t\t\tfindings: vo.findings ?? [],\n\t\t\terrorClass: vo.errorClass,\n\t\t};\n\n\t\tif (vr.verified) {\n\t\t\tstrategy.record(item.rootCause, item.intervention, true);\n\t\t\tverifyResults.publish(vr);\n\t\t\treturn;\n\t\t}\n\n\t\t// Failed verification\n\t\tconst errClass =\n\t\t\tvr.errorClass ??\n\t\t\terrorClassifier({\n\t\t\t\titem,\n\t\t\t\toutcome: \"failure\",\n\t\t\t\tdetail: vr.findings.join(\"; \"),\n\t\t\t});\n\n\t\tconst itemRetries = item._retries ?? 0;\n\n\t\tif (\n\t\t\terrClass === \"self-correctable\" &&\n\t\t\titemRetries < maxRetries &&\n\t\t\ttryIncrementBounded(totalRetries, maxTotalRetries)\n\t\t) {\n\t\t\tconst key = trackingKey(item);\n\t\t\tconst retryItem: TriagedItem = {\n\t\t\t\t...item,\n\t\t\t\t_retries: itemRetries + 1,\n\t\t\t\tsummary: `[RETRY ${itemRetries + 1}/${maxRetries}] ${key} — Previous attempt failed: ${vr.findings.join(\"; \")}`,\n\t\t\t\trelatedTo: [key],\n\t\t\t};\n\t\t\tretryTopic.publish(retryItem);\n\t\t} else {\n\t\t\t// Structural failure or max retries exceeded → full loop via INTAKE\n\t\t\tstrategy.record(item.rootCause, item.intervention, false);\n\t\t\tverifyResults.publish(vr);\n\n\t\t\tconst key = trackingKey(item);\n\t\t\tconst itemReingestions = item._reingestions ?? 0;\n\t\t\tif (\n\t\t\t\titemReingestions < maxReingestions &&\n\t\t\t\ttryIncrementBounded(totalReingestions, maxTotalReingestions)\n\t\t\t) {\n\t\t\t\tintake.publish({\n\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\tsummary: `Verification failed for: ${key}`,\n\t\t\t\t\tevidence: vr.findings.join(\"\\n\"),\n\t\t\t\t\taffectsAreas: item.affectsAreas,\n\t\t\t\t\taffectsEvalTasks: item.affectsEvalTasks,\n\t\t\t\t\tseverity: \"high\",\n\t\t\t\t\trelatedTo: [key],\n\t\t\t\t\t_reingestions: itemReingestions + 1,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\n\tconst fastRetryUnsub = fastRetry.subscribe(() => {}); // keepalive (COMPOSITION-GUIDE §1)\n\n\t// --- Stage 7: REFLECT ---\n\t// Strategy model is already updated in the fast-retry/verify effect above.\n\t// Hypothesis generation and memory distillation are pluggable extensions\n\t// wired externally via verifyResults topic subscription — not hardcoded here.\n\n\t// --- Assemble HarnessGraph ---\n\tconst harness = new HarnessGraph(\n\t\tname,\n\t\tintake,\n\t\tqueueTopics,\n\t\tgateControllers,\n\t\tstrategy,\n\t\tverifyResults,\n\t\ttotalRetries,\n\t\ttotalReingestions,\n\t);\n\n\t// Register disposers for unregistered internal nodes (D1/D2 fix)\n\tharness.addDisposer(routerUnsub);\n\tharness.addDisposer(fastRetryUnsub);\n\tharness.addDisposer(strategy.dispose);\n\n\t// Register stage nodes for introspection (harnessTrace, describe, observe)\n\tharness.add(\"triage\", triageNode as Node<unknown>);\n\tharness.add(\"execute\", executeNode as Node<unknown>);\n\tharness.add(\"verify\", verifyNode as Node<unknown>);\n\tharness.add(\"strategy\", strategy.node as Node<unknown>);\n\n\t// Mount subgraphs\n\tharness.mount(\"intake\", intake);\n\tfor (const [route, topic] of queueTopics) {\n\t\tharness.mount(`queue/${route}`, topic);\n\t}\n\tharness.mount(\"gates\", gateGraph);\n\tharness.mount(\"retry-input\", retryTopic);\n\tharness.mount(\"verify-results\", verifyResults);\n\n\treturn harness;\n}\n","/**\n * Harness-specific graph profiling (roadmap §9.0).\n *\n * Extends {@link graphProfile} with harness domain counters:\n * queue depths, strategy entries, retry/reingestion tracker sizes.\n *\n * @module\n */\n\nimport {\n\ttype GraphProfileOptions,\n\ttype GraphProfileResult,\n\tgraphProfile,\n} from \"../../graph/profile.js\";\nimport type { HarnessGraph } from \"./loop.js\";\nimport type { QueueRoute } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Harness-specific profile extending the base graph profile. */\nexport interface HarnessProfileResult extends GraphProfileResult {\n\t/** Per-queue retained item counts. */\n\tqueueDepths: Record<QueueRoute, number>;\n\t/** Number of rootCause→intervention entries in the strategy model. */\n\tstrategyEntries: number;\n\t/** Global retry count across all items. */\n\ttotalRetries: number;\n\t/** Global reingestion count across all items. */\n\ttotalReingestions: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Profile a harness graph with domain-specific counters.\n *\n * @param harness - The HarnessGraph to profile.\n * @param opts - Optional base profile options.\n * @returns Harness profile with queue depths, strategy stats, and tracker sizes.\n */\nexport function harnessProfile(\n\tharness: HarnessGraph,\n\topts?: GraphProfileOptions,\n): HarnessProfileResult {\n\tconst base = graphProfile(harness, opts);\n\n\tconst queueDepths: Record<string, number> = {};\n\tfor (const [route, topic] of harness.queues) {\n\t\tqueueDepths[route] = topic.retained().length;\n\t}\n\n\treturn {\n\t\t...base,\n\t\tqueueDepths: queueDepths as Record<QueueRoute, number>,\n\t\tstrategyEntries: harness.strategy.node.cache?.size ?? 0,\n\t\ttotalRetries: harness.totalRetries.cache ?? 0,\n\t\ttotalReingestions: harness.totalReingestions.cache ?? 0,\n\t};\n}\n","/**\n * Harness pipeline trace (roadmap §9.0 — Inspection Tool Consolidation).\n *\n * Attaches reactive observers (via `observe()`) to all harness stages.\n * One call gives full pipeline visibility with stage labels and elapsed\n * timestamps relative to the `harnessTrace()` invocation time.\n *\n * Supports two output modes:\n * - **String logger** (default): rendered lines to `console.log` or a custom sink.\n * - **Structured events**: programmatic `TraceEvent[]` list for test assertions\n * and tooling. Access via `handle.events`.\n *\n * Supports configurable detail levels (`\"summary\"`, `\"standard\"`, `\"full\"`)\n * to control output verbosity without composing different tool calls.\n *\n * @module\n */\n\nimport { monotonicNs } from \"../../core/clock.js\";\nimport type { ObserveResult } from \"../../graph/graph.js\";\nimport type { HarnessGraph } from \"./loop.js\";\nimport { QUEUE_NAMES } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Event type captured by structured trace. */\nexport type TraceEventType = \"data\" | \"error\" | \"complete\";\n\n/** A single structured trace event. */\nexport interface TraceEvent {\n\t/** Elapsed seconds since trace was created. */\n\telapsed: number;\n\t/** Pipeline stage label (INTAKE, TRIAGE, QUEUE, GATE, EXECUTE, VERIFY, STRATEGY). */\n\tstage: string;\n\t/** Event type. */\n\ttype: TraceEventType;\n\t/** Data payload (present for \"data\" and \"error\" events). Omitted at \"summary\" detail. */\n\tdata?: unknown;\n\t/** Human-readable summary of the data. Present at \"standard\" and \"full\" detail. */\n\tsummary?: string;\n}\n\n/** Detail level for trace output. */\nexport type TraceDetail =\n\t/** Stage + elapsed only. No data preview. Lowest overhead. */\n\t| \"summary\"\n\t/** Stage + elapsed + truncated data preview. Default. */\n\t| \"standard\"\n\t/** Stage + elapsed + full raw data. Use for debugging, not production. */\n\t| \"full\";\n\n/** Handle returned by {@link harnessTrace}. Call `dispose()` to stop tracing. */\nexport interface HarnessTraceHandle {\n\t/** Stop tracing and detach all observers. Safe to call multiple times. */\n\tdispose(): void;\n\t/**\n\t * Structured trace events collected since creation. Plain array — no\n\t * subscription needed (COMPOSITION-GUIDE §1: avoid lazy-activation\n\t * friction for inspection tools). Populated reactively via observe().\n\t */\n\treadonly events: readonly TraceEvent[];\n}\n\n/** Options for {@link harnessTrace}. */\nexport interface HarnessTraceOptions {\n\t/** Sink for rendered trace lines. Default: `console.log`. */\n\tlogger?: (line: string) => void;\n\t/** Detail level for both string and structured output. Default: `\"summary\"`. */\n\tdetail?: TraceDetail;\n}\n\n// ---------------------------------------------------------------------------\n// Stage labels\n// ---------------------------------------------------------------------------\n\n/** Observe paths → stage labels for the 7 harness stages. */\nconst STAGE_LABELS: Record<string, string> = {\n\t\"intake::latest\": \"INTAKE\",\n\ttriage: \"TRIAGE\",\n\texecute: \"EXECUTE\",\n\t\"verify-results::latest\": \"VERIFY\",\n\tstrategy: \"STRATEGY\",\n};\n\nfor (const route of QUEUE_NAMES) {\n\tSTAGE_LABELS[`queue/${route}::latest`] = \"QUEUE\";\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Attach reactive trace observers to all harness pipeline stages.\n *\n * Wires `graph.observe(path, { format: \"json\" })` to each stage node,\n * intercepting the logger callback to emit stage-labeled lines with\n * elapsed timestamps. Surfaces DATA, ERROR, and COMPLETE events.\n *\n * **Structured events:** Every trace event is also pushed to\n * `handle.events` — a plain array (not a reactive node) that tests and\n * tooling can inspect programmatically. To use structured events alone\n * without string output, pass `{ logger: null }`.\n *\n * **Detail levels:**\n * - `\"summary\"` — stage + elapsed only. Minimal overhead.\n * - `\"standard\"` (default) — stage + elapsed + truncated data preview.\n * - `\"full\"` — stage + elapsed + full raw data object in events.\n *\n * Elapsed timestamps are relative to the `harnessTrace()` invocation time,\n * not the first event.\n *\n * @param harness - The HarnessGraph to trace.\n * @param opts - Optional configuration.\n * @returns Handle with `dispose()` to stop tracing and `events` for structured access.\n */\nexport function harnessTrace(\n\tharness: HarnessGraph,\n\topts?: HarnessTraceOptions,\n): HarnessTraceHandle {\n\tconst logger = opts?.logger ?? console.log;\n\tconst detail: TraceDetail = opts?.detail ?? \"summary\";\n\tconst startNs = monotonicNs();\n\tconst observations: ObserveResult[] = [];\n\tconst events: TraceEvent[] = [];\n\n\tfunction elapsedSecs(): number {\n\t\treturn (monotonicNs() - startNs) / 1e9;\n\t}\n\n\tfunction elapsedStr(): string {\n\t\treturn elapsedSecs().toFixed(3);\n\t}\n\n\tfunction recordEvent(stage: string, type: TraceEventType, rawData: unknown): void {\n\t\tconst e = elapsedSecs();\n\t\tconst ev: TraceEvent = { elapsed: e, stage, type };\n\n\t\tif (detail !== \"summary\") {\n\t\t\tev.summary = summarize(rawData);\n\t\t}\n\t\tif (detail === \"full\") {\n\t\t\tev.data = rawData;\n\t\t}\n\n\t\tevents.push(ev);\n\t}\n\n\tfunction wireStage(path: string, stage: string): void {\n\t\ttry {\n\t\t\tconst obs = harness.observe(path, {\n\t\t\t\tformat: \"json\",\n\t\t\t\tlogger: (_line, event) => {\n\t\t\t\t\tif (event.type === \"data\") {\n\t\t\t\t\t\trecordEvent(stage, \"data\", event.data);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tif (detail === \"summary\") {\n\t\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ←`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst dataStr = event.data !== undefined ? ` ${summarize(event.data)}` : \"\";\n\t\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ←${dataStr}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\t\trecordEvent(stage, \"error\", event.data);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tconst errStr = event.data !== undefined ? ` ${summarize(event.data)}` : \"\";\n\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ✗${errStr}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.type === \"complete\") {\n\t\t\t\t\t\trecordEvent(stage, \"complete\", undefined);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ■ complete`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tincludeTypes: [\"data\", \"error\", \"complete\"],\n\t\t\t});\n\t\t\tobservations.push(obs);\n\t\t} catch {\n\t\t\t// Node may not exist (e.g., queue route not mounted) — skip silently\n\t\t}\n\t}\n\n\t// Wire stage nodes (COMPOSITION-GUIDE §5: sinks before sources)\n\tfor (const [path, stage] of Object.entries(STAGE_LABELS)) {\n\t\twireStage(path, stage);\n\t}\n\n\t// Wire gate outputs per gated queue\n\tfor (const [gatedRoute] of harness.gates) {\n\t\twireStage(`gates::${gatedRoute}/gate`, \"GATE\");\n\t}\n\n\treturn {\n\t\tget events(): readonly TraceEvent[] {\n\t\t\treturn events;\n\t\t},\n\t\tdispose() {\n\t\t\tfor (const obs of observations) obs.dispose();\n\t\t\tobservations.length = 0;\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction summarize(value: unknown): string {\n\tif (value == null) return \"null\";\n\tif (typeof value === \"string\") return truncate(value, 80);\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (typeof value === \"bigint\") return String(value);\n\ttry {\n\t\tconst json = JSON.stringify(value);\n\t\treturn truncate(json, 120);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction truncate(s: string, max: number): string {\n\treturn s.length > max ? `${s.slice(0, max - 1)}…` : s;\n}\n","/**\n * GraphRefly — public API surface.\n */\nexport const version = \"0.0.0\";\n\nexport * from \"./compat/index.js\";\nexport * as compat from \"./compat/index.js\";\n// Named re-exports enable finer-grained tree-shaking for consumers.\nexport * from \"./core/index.js\";\n// Keep namespace exports for ergonomic grouped imports.\nexport * as core from \"./core/index.js\";\nexport * from \"./extra/index.js\";\nexport * as extra from \"./extra/index.js\";\nexport * from \"./graph/index.js\";\nexport * as graph from \"./graph/index.js\";\nexport * from \"./patterns/index.js\";\nexport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AY,OAAO,UAAU,UAAW,QAAO,OAAO,KAAK;AAChF,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK;AAClD,MAAI;AACH,UAAM,OAAO,KAAK,UAAU,KAAK;AACjC,WAAO,SAAS,MAAM,GAAG;AAAA,EAC1B,QAAQ;AACP,WAAO,OAAO,KAAK;AAAA,EACpB;AACD;AAEA,SAAS,SAAS,GAAW,KAAqB;AACjD,SAAO,EAAE,SAAS,MAAM,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC,WAAM;AACrD;;;AC/NO,IAAM,UAAU;","names":["initial","atom","map","node","map","pull","atom","node","pull","useStore","useSubscribe","useSubscribeRecord","useSubscribe","node","useStore","useSubscribeRecord","useStore","useSubscribe","useSubscribeRecord","useSubscribe","node","useStore","useSubscribeRecord","useStore","useSubscribe","useSubscribeRecord","computed","useSubscribe","node","useStore","computed","useSubscribeRecord","node","policy","out","forEach","valve","batch","valve","forEach","filter","interval","node","baseMeta","buffer","baseMeta","policy","node","_","VALID_NODE_TYPES","stripFences","feedback","DEFAULT_DECAY_RATE","evalSource","task","trigger","topic","DEFAULT_DECAY_RATE","DEFAULT_DECAY_RATE","topic","batch","topic"]}
|
|
1
|
+
{"version":3,"sources":["../src/compat/index.ts","../src/compat/jotai/index.ts","../src/compat/nanostores/index.ts","../src/compat/react/index.ts","../src/compat/signals/index.ts","../src/compat/solid/index.ts","../src/compat/svelte/index.ts","../src/compat/vue/index.ts","../src/compat/zustand/index.ts","../src/patterns/index.ts","../src/patterns/ai.ts","../src/patterns/memory.ts","../src/patterns/messaging.ts","../src/patterns/orchestration.ts","../src/patterns/demo-shell.ts","../src/patterns/domain-templates.ts","../src/patterns/reduction.ts","../src/patterns/graphspec.ts","../src/patterns/harness/index.ts","../src/patterns/harness/bridge.ts","../src/patterns/harness/types.ts","../src/patterns/harness/strategy.ts","../src/patterns/harness/loop.ts","../src/patterns/harness/profile.ts","../src/patterns/harness/trace.ts","../src/index.ts"],"sourcesContent":["/**\n * Compat layer: compatibility wrappers for other state management libraries (Phase 5.1b).\n *\n * Framework adapters are optional peers. Install only what you use:\n * - `@graphrefly/graphrefly-ts/compat/react` -> `react`, `react-dom`\n * - `@graphrefly/graphrefly-ts/compat/vue` -> `vue`\n * - `@graphrefly/graphrefly-ts/compat/svelte` -> `svelte`\n * - `@graphrefly/graphrefly-ts/compat/solid` -> `solid-js`\n */\nexport * as jotai from \"./jotai/index.js\";\nexport * as nanostores from \"./nanostores/index.js\";\nexport * as nestjs from \"./nestjs/index.js\";\nexport * as react from \"./react/index.js\";\nexport * as signals from \"./signals/index.js\";\nexport * as solid from \"./solid/index.js\";\nexport * as svelte from \"./svelte/index.js\";\nexport * as vue from \"./vue/index.js\";\nexport * as zustand from \"./zustand/index.js\";\n","import { DATA, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { autoTrackNode, state } from \"../../core/sugar.js\";\n\n/**\n * Options for creating an atom.\n *\n * @category compat\n */\nexport interface AtomOptions {\n\t/** Optional identifier for the underlying node. */\n\tname?: string;\n\t/** Optional companion meta nodes. */\n\tmeta?: Record<string, unknown>;\n}\n\n/**\n * A read-only Jotai-compatible atom.\n *\n * @category compat\n */\nexport interface ReadableAtom<T> {\n\t/** Returns the current cached value. */\n\tget(): T;\n\t/** Subscribes to value changes. Returns an unsubscribe function. */\n\tsubscribe(callback: (value: T) => void): () => void;\n\t/** Access to companion meta nodes. */\n\treadonly meta: Record<string, Node>;\n\t/** @internal The underlying GraphReFly node. */\n\t_node: Node<T>;\n}\n\n/**\n * A writable Jotai-compatible atom.\n *\n * @category compat\n */\nexport interface WritableAtom<T> extends ReadableAtom<T> {\n\t/** Sets a new value. */\n\tset(value: T): void;\n\t/** Updates the value using a transformation function. */\n\tupdate(fn: (current: T) => T): void;\n}\n\n/** Function type for reading other atoms inside a derived atom. */\nexport type GetFn = <V>(a: ReadableAtom<V>) => V;\n/** Function type for writing to other atoms inside a writable derived atom. */\nexport type SetFn = <V>(a: WritableAtom<V>, value: V) => void;\n\n/** Function that computes the atom's value. */\nexport type ReadFn<T> = (get: GetFn) => T;\n/** Function that handles writes to the atom. */\nexport type WriteFn<T> = (get: GetFn, set: SetFn, value: T) => void;\n\n/**\n * Creates a Jotai-compatible atom built on GraphReFly primitives.\n *\n * Supports three overloads:\n * 1. `atom(initial)` — Writable primitive atom (wraps `state()`).\n * 2. `atom(read)` — Read-only derived atom (wraps `dynamicNode()`).\n * 3. `atom(read, write)` — Writable derived atom.\n *\n * @param initialOrRead - Initial value or a read function.\n * @param writeOrOptions - Write function or options object.\n * @param options - Optional configuration.\n * @returns WritableAtom or ReadableAtom.\n *\n * @example\n * ```ts\n * const count = atom(0);\n * count.set(1);\n * const doubled = atom((get) => get(count)! * 2);\n * ```\n *\n * @category compat\n */\nexport function atom<T>(initial: T, options?: AtomOptions): WritableAtom<T>;\nexport function atom<T>(read: ReadFn<T>, options?: AtomOptions): ReadableAtom<T>;\nexport function atom<T>(read: ReadFn<T>, write: WriteFn<T>, options?: AtomOptions): WritableAtom<T>;\nexport function atom<T>(\n\tinitialOrRead: T | ReadFn<T>,\n\twriteOrOptions?: WriteFn<T> | AtomOptions,\n\toptions?: AtomOptions,\n): ReadableAtom<T> | WritableAtom<T> {\n\tif (typeof initialOrRead === \"function\") {\n\t\tconst read = initialOrRead as ReadFn<T>;\n\t\tif (typeof writeOrOptions === \"function\") {\n\t\t\treturn createDerivedAtom(read, writeOrOptions as WriteFn<T>, options);\n\t\t}\n\t\treturn createDerivedAtom(read, undefined, writeOrOptions as AtomOptions);\n\t}\n\n\treturn createPrimitiveAtom(initialOrRead as T, writeOrOptions as AtomOptions);\n}\n\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined | null = n.cache;\n\tlet err: any;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t\tif (t === ERROR) err = v;\n\t\t}\n\t});\n\tunsub();\n\tif (err) throw err;\n\treturn val as T;\n}\n\nfunction createPrimitiveAtom<T>(initial: T, options?: AtomOptions): WritableAtom<T> {\n\tconst n = state(initial, {\n\t\t...options,\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t});\n\treturn {\n\t\tget: () => {\n\t\t\tif (n.status === \"sentinel\") {\n\t\t\t\treturn pull(n);\n\t\t\t}\n\t\t\treturn n.cache as T;\n\t\t},\n\t\t// Use `n.emit` (not raw `n.down`) so writes go through the framed\n\t\t// emit pipeline: bundle() auto-prefixes DIRTY (diamond-safe wave\n\t\t// coordination) and the equals check folds same-value writes to\n\t\t// RESOLVED (no spurious subscriber fires).\n\t\tset: (value: T) => n.emit(value),\n\t\tupdate: (fn: (current: T) => T) => {\n\t\t\tconst current = n.status === \"sentinel\" ? pull(n) : (n.cache as T);\n\t\t\tn.emit(fn(current));\n\t\t},\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\t// Skip the initial push-on-subscribe DATA — jotai subscribe fires on changes only.\n\t\t\tlet initial = true;\n\t\t\treturn n.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcb(v as T);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tmeta: n.meta,\n\t\t_node: n,\n\t};\n}\n\nfunction createDerivedAtom<T>(\n\tread: ReadFn<T>,\n\twrite?: WriteFn<T>,\n\toptions?: AtomOptions,\n): ReadableAtom<T> | WritableAtom<T> {\n\tconst n = autoTrackNode(\n\t\t(track) =>\n\t\t\tread(<V>(a: ReadableAtom<V>) => {\n\t\t\t\tconst dn = a._node;\n\t\t\t\tif (dn.status === \"sentinel\") {\n\t\t\t\t\tpull(dn);\n\t\t\t\t}\n\t\t\t\treturn track(dn) as V;\n\t\t\t}),\n\t\t{\n\t\t\t...options,\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t},\n\t);\n\n\tconst result: ReadableAtom<T> = {\n\t\tget: () => {\n\t\t\tif (n.status === \"sentinel\") {\n\t\t\t\treturn pull(n);\n\t\t\t}\n\t\t\treturn n.cache as T;\n\t\t},\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\t// Skip the initial push-on-subscribe DATA — jotai subscribe fires on changes only.\n\t\t\tlet initial = true;\n\t\t\treturn n.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcb(v as T);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tmeta: n.meta,\n\t\t_node: n,\n\t};\n\n\tif (write) {\n\t\tconst getFn: GetFn = <V>(a: ReadableAtom<V>) => a.get();\n\t\tconst setFn: SetFn = <V>(a: WritableAtom<V>, value: V) => a.set(value);\n\n\t\tconst writable = result as WritableAtom<T>;\n\t\twritable.set = (value: T) => write(getFn, setFn, value);\n\t\twritable.update = (fn: (current: T) => T) => {\n\t\t\tconst current = n.status === \"sentinel\" ? pull(n) : (n.cache as T);\n\t\t\treturn write(getFn, setFn, fn(current));\n\t\t};\n\t\treturn writable;\n\t}\n\n\treturn result;\n}\n","import { batch } from \"../../core/batch.js\";\nimport { DATA, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { dynamicNode, state, type TrackFn } from \"../../core/sugar.js\";\n\n/**\n * A Nanostores-compatible atom.\n *\n * @category compat\n */\nexport interface NanoAtom<T> {\n\t/** Get current value. */\n\tget(): T;\n\t/** Set a new value (writable atoms only). */\n\tset(value: T): void;\n\t/** Subscribe to value changes. Callback receives the new value.\n\t * Returns unsubscribe function. Called immediately with current value. */\n\tsubscribe(cb: (value: T) => void): () => void;\n\t/** Listen to value changes (no immediate call). Returns unsubscribe. */\n\tlisten(cb: (value: T) => void): () => void;\n\t/** The underlying GraphReFly node. */\n\treadonly _node: Node<T>;\n}\n\n/**\n * A Nanostores-compatible computed store.\n *\n * @category compat\n */\nexport interface NanoComputed<T> {\n\t/** Get current value. */\n\tget(): T;\n\t/** Subscribe to value changes. Called immediately with current value.\n\t * Returns unsubscribe function. */\n\tsubscribe(cb: (value: T) => void): () => void;\n\t/** Listen to value changes (no immediate call). Returns unsubscribe. */\n\tlisten(cb: (value: T) => void): () => void;\n\t/** The underlying GraphReFly node. */\n\treadonly _node: Node<T>;\n}\n\n/**\n * A Nanostores-compatible map.\n *\n * @category compat\n */\nexport interface NanoMap<T extends Record<string, unknown>> extends NanoAtom<T> {\n\t/** Set a single key. */\n\tsetKey<K extends keyof T>(key: K, value: T[K]): void;\n}\n\nconst START_LISTENERS = new WeakMap<Node<any>, Set<() => void>>();\nconst STOP_LISTENERS = new WeakMap<Node<any>, Set<() => void>>();\n\nfunction trigger(node: Node<any>, map: WeakMap<Node<any>, Set<() => void>>) {\n\tconst callbacks = map.get(node);\n\tif (callbacks) {\n\t\tfor (const cb of callbacks) cb();\n\t}\n}\n\nfunction createStore<T>(node: Node<T>, extra: any = {}): any {\n\tlet listeners = 0;\n\tconst store = {\n\t\t...extra,\n\t\tget: () => getVal(node),\n\t\tsubscribe: (cb: (value: T) => void) => {\n\t\t\tif (listeners === 0) trigger(node, START_LISTENERS);\n\t\t\tlisteners++;\n\t\t\t// Push-on-subscribe delivers the initial value via DATA — no explicit cb() needed.\n\t\t\tconst sub = node.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) cb(v as T);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsub();\n\t\t\t\tlisteners--;\n\t\t\t\tif (listeners === 0) trigger(node, STOP_LISTENERS);\n\t\t\t};\n\t\t},\n\t\tlisten: (cb: (value: T) => void) => {\n\t\t\tif (listeners === 0) trigger(node, START_LISTENERS);\n\t\t\tlisteners++;\n\t\t\t// Skip the initial push-on-subscribe DATA — listen() fires on changes only.\n\t\t\tlet initial = true;\n\t\t\tconst sub = node.subscribe((msgs: Messages) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcb(v as T);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsub();\n\t\t\t\tlisteners--;\n\t\t\t\tif (listeners === 0) trigger(node, STOP_LISTENERS);\n\t\t\t};\n\t\t},\n\t\t_node: node,\n\t};\n\treturn store;\n}\n\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined | null = n.cache;\n\tlet err: any;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t\tif (t === ERROR) err = v;\n\t\t}\n\t});\n\tunsub();\n\tif (err) throw err;\n\treturn val as T;\n}\n\nfunction getVal<T>(n: Node<T>): T {\n\tif (n.status === \"sentinel\") {\n\t\treturn pull(n);\n\t}\n\treturn n.cache as T;\n}\n\n/**\n * Creates a nanostores-compatible atom.\n *\n * @param initial - Initial value.\n * @returns `NanoAtom<T>`\n *\n * @category compat\n */\nexport function atom<T>(initial: T): NanoAtom<T> {\n\tconst n = state<T>(initial, {\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t});\n\n\treturn createStore(n, {\n\t\t// `n.emit` routes through the framed pipeline: `bundle()` auto-\n\t\t// prefixes `[DIRTY]` (diamond-safe wave coordination) and the\n\t\t// node's `equals` (default `Object.is`) folds same-value writes\n\t\t// into `RESOLVED`. Matches nanostores' documented Object.is\n\t\t// dedup semantics without any custom check.\n\t\tset: (value: T) => n.emit(value),\n\t});\n}\n\n/**\n * Creates a nanostores-compatible computed store.\n *\n * @param stores - One or more atoms/computed stores.\n * @param fn - Compute function.\n * @returns `NanoComputed<T>`\n *\n * @category compat\n */\nexport function computed<T, A>(\n\tstoreA: NanoAtom<A> | NanoComputed<A>,\n\tfn: (a: A) => T,\n): NanoComputed<T>;\nexport function computed<T, A, B>(\n\tstores: [NanoAtom<A> | NanoComputed<A>, NanoAtom<B> | NanoComputed<B>],\n\tfn: (a: A, b: B) => T,\n): NanoComputed<T>;\nexport function computed<T, A, B, C>(\n\tstores: [\n\t\tNanoAtom<A> | NanoComputed<A>,\n\t\tNanoAtom<B> | NanoComputed<B>,\n\t\tNanoAtom<C> | NanoComputed<C>,\n\t],\n\tfn: (a: A, b: B, c: C) => T,\n): NanoComputed<T>;\nexport function computed<T>(stores: any, fn: (...args: any[]) => T): NanoComputed<T> {\n\tconst storeArray: Array<NanoAtom<any> | NanoComputed<any>> = Array.isArray(stores)\n\t\t? stores\n\t\t: [stores];\n\n\tconst depNodes = storeArray.map((s) => s._node);\n\tconst n = dynamicNode(\n\t\tdepNodes,\n\t\t(track: TrackFn) => {\n\t\t\tconst vals = storeArray.map((s) => {\n\t\t\t\tconst node = s._node;\n\t\t\t\tif (node.status === \"sentinel\") {\n\t\t\t\t\tpull(node);\n\t\t\t\t}\n\t\t\t\treturn track(node);\n\t\t\t});\n\t\t\treturn fn(...vals);\n\t\t},\n\t\t{\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t\tequals: Object.is as any,\n\t\t},\n\t);\n\n\treturn createStore(n);\n}\n\n/**\n * Creates a nanostores-compatible map.\n *\n * @param initial - Initial object value.\n * @returns `NanoMap<T>`\n *\n * @category compat\n */\nexport function map<T extends Record<string, unknown>>(initial: T): NanoMap<T> {\n\tconst n = state<T>(initial, {\n\t\tresubscribable: true,\n\t\tresetOnTeardown: true,\n\t\tequals: () => false,\n\t});\n\n\treturn createStore(n, {\n\t\t// `map`'s state node is configured with `equals: () => false`\n\t\t// above, so every `emit` produces DATA (even for same-key same-\n\t\t// value sets). The `emit` path is still required for diamond\n\t\t// coordination (`[DIRTY]` auto-prefix via `bundle()`).\n\t\tset: (value: T) => n.emit(value),\n\t\tsetKey: <K extends keyof T>(key: K, value: T[K]) => {\n\t\t\tconst current = getVal(n);\n\t\t\tn.emit({ ...current, [key]: value });\n\t\t},\n\t});\n}\n\n/**\n * Returns the current value of the store.\n *\n * @category compat\n */\nexport function getValue<T>(store: NanoAtom<T> | NanoComputed<T>): T {\n\treturn store.get();\n}\n\n/**\n * Adds a listener for the store start (first listener connected).\n *\n * @category compat\n */\nexport function onStart(store: NanoAtom<any> | NanoComputed<any>, cb: () => void): void {\n\tconst node = store._node;\n\tlet callbacks = START_LISTENERS.get(node);\n\tif (!callbacks) {\n\t\tcallbacks = new Set();\n\t\tSTART_LISTENERS.set(node, callbacks);\n\t}\n\tcallbacks.add(cb);\n}\n\n/**\n * Adds a listener for the store stop (last listener disconnected).\n *\n * @category compat\n */\nexport function onStop(store: NanoAtom<any> | NanoComputed<any>, cb: () => void): void {\n\tconst node = store._node;\n\tlet callbacks = STOP_LISTENERS.get(node);\n\tif (!callbacks) {\n\t\tcallbacks = new Set();\n\t\tSTOP_LISTENERS.set(node, callbacks);\n\t}\n\tcallbacks.add(cb);\n}\n\n/**\n * Adds a listener for the store mount (first listener connected).\n *\n * @returns A cleanup function called when the last listener is removed.\n * @category compat\n */\nexport function onMount(\n\tstore: NanoAtom<any> | NanoComputed<any>,\n\tcb: () => (() => void) | undefined,\n): void {\n\tonStart(store, () => {\n\t\tconst stop = cb();\n\t\tif (typeof stop === \"function\") onStop(store, stop);\n\t});\n}\n\n/**\n * Batches multiple store updates.\n *\n * @category compat\n */\nexport function action<Args extends any[], Return>(\n\t_store: NanoAtom<any> | NanoComputed<any>,\n\t_name: string,\n\tfn: (...args: Args) => Return,\n): (...args: Args) => Return {\n\treturn (...args: Args) => {\n\t\tlet result: any;\n\t\tbatch(() => {\n\t\t\tresult = fn(...args);\n\t\t});\n\t\treturn result as Return;\n\t};\n}\n","// ---------------------------------------------------------------------------\n// React bindings — useStore / useSubscribe\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into React via useSyncExternalStore.\n// Works with any Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useStore, useSubscribe } from '@graphrefly/graphrefly-ts/compat/react';\n// // Optional peer install (only for this adapter): pnpm add react react-dom\n// const value = useSubscribe(myNode); // T | undefined (read-only)\n// const [count, setCount] = useStore(counter); // [T | undefined, setter]\n// ---------------------------------------------------------------------------\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport { DATA, DIRTY, type Messages, RESOLVED } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/**\n * Subscribe to a read-only `Node<T>` as a React value. Re-renders on node value settlement.\n * Subscription lifecycle is tied to React mount/unmount (not node terminal messages).\n *\n * @param node - Any `Node<T>`.\n * @returns `T | undefined` — the current node value, kept in sync via `useSyncExternalStore`.\n */\nexport function useSubscribe<T>(node: Node<T>): T | undefined | null {\n\treturn useSyncExternalStore(\n\t\t(onStoreChange) => {\n\t\t\tlet disposed = false;\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tdisposed = true;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t},\n\t\t() => node.cache,\n\t\t() => node.cache, // Server snapshot\n\t);\n}\n\n/**\n * Bind a writable `Node<T>` as a React `[value, setter]` tuple.\n * Setting the value always pushes `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to React mount/unmount (not node terminal messages).\n *\n * @param node - A `Node<T>` (e.g. state node).\n * @returns `[T | undefined, (value: T) => void]` — current value and setter function.\n */\nexport function useStore<T>(node: Node<T>): [T | undefined | null, (value: T) => void] {\n\tconst value = useSubscribe(node);\n\tconst setter = useCallback(\n\t\t(v: T) => {\n\t\t\tnode.down([[DIRTY], [DATA, v]]);\n\t\t},\n\t\t[node],\n\t);\n\treturn [value, setter];\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records.\n * Re-subscribes all per-key fields whenever `keysNode` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 3`) to avoid DIRTY-phase churn.\n * Guaranteed to clean up strictly with React hook lifecycle, utilizing no global mappings.\n *\n * @param keysNode - Node of current keys (e.g. node IDs)\n * @param factory - Function returning `{ [field]: Node<V> }` for each key.\n * @returns `Record<K, R>` — snapshot of resolved values for all keys.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): Record<K, R> {\n\tconst factoryRef = useRef(factory);\n\tfactoryRef.current = factory;\n\n\tconst store = useMemo(() => {\n\t\tconst computeSnap = () => {\n\t\t\tconst snap = {} as Record<K, R>;\n\t\t\tconst keys = keysNode.cache ?? [];\n\t\t\tfor (const key of keys) {\n\t\t\t\tconst nodes = factoryRef.current(key);\n\t\t\t\tconst values = {} as R;\n\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t\t}\n\t\t\t\tsnap[key] = values;\n\t\t\t}\n\t\t\treturn snap;\n\t\t};\n\n\t\tlet currentSnapshot = computeSnap();\n\n\t\treturn {\n\t\t\tsubscribe: (onStoreChange: () => void) => {\n\t\t\t\tlet disposed = false;\n\t\t\t\tlet entrySubs: Array<() => void> = [];\n\n\t\t\t\tconst cleanupEntries = () => {\n\t\t\t\t\tfor (const unsub of entrySubs) unsub();\n\t\t\t\t\tentrySubs = [];\n\t\t\t\t};\n\n\t\t\t\tconst sync = (nextKeys: K[]) => {\n\t\t\t\t\tcleanupEntries();\n\t\t\t\t\tfor (const key of nextKeys) {\n\t\t\t\t\t\tconst nodes = factoryRef.current(key);\n\t\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\t\t\t\tcurrentSnapshot = computeSnap();\n\t\t\t\t\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tentrySubs.push(unsub);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcurrentSnapshot = computeSnap();\n\t\t\t\t\tif (!disposed) onStoreChange();\n\t\t\t\t};\n\n\t\t\t\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\t\t\t\tconst hasSettled = msgs.some((m) => m[0] === DATA || m[0] === RESOLVED);\n\t\t\t\t\tif (!disposed && hasSettled) sync(keysNode.cache ?? []);\n\t\t\t\t});\n\t\t\t\tsync(keysNode.cache ?? []);\n\n\t\t\t\treturn () => {\n\t\t\t\t\tdisposed = true;\n\t\t\t\t\tkeysUnsub();\n\t\t\t\t\tcleanupEntries();\n\t\t\t\t};\n\t\t\t},\n\t\t\tgetSnapshot: () => currentSnapshot,\n\t\t};\n\t}, [keysNode]);\n\n\treturn useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n}\n","import { batch } from \"../../core/batch.js\";\nimport { COMPLETE, DATA, DIRTY, ERROR, type Messages } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { autoTrackNode, state, type TrackFn } from \"../../core/sugar.js\";\n\n/**\n * Options for creating signals.\n *\n * @category compat\n */\nexport interface SignalOptions {\n\t/** Optional identifier for the underlying node. */\n\tname?: string;\n\t/** Custom equality function for change detection. */\n\tequals?: (a: any, b: any) => boolean;\n}\n\n/**\n * Common interface for all reactive signals.\n *\n * @category compat\n */\nexport interface AnySignal<T> {\n\t/** Returns the current value of the signal. */\n\tget(): T;\n\t/** @internal The underlying GraphReFly node. */\n\t_node: Node<T>;\n}\n\n/**\n * Global stack of active tracking contexts.\n * Since computation evaluation is fully synchronous, we push the tracking `get`\n * function before execution and pop it after. This prevents memory leaks without\n * needing WeakRefs, as the stack is always empty when idle.\n */\nconst trackingStack: TrackFn[] = [];\n\n/**\n * Helper to pull a disconnected node, forcing a synchronous resolution\n * cycle so that `get()` returns a fresh value even if the signal is unmounted.\n */\nfunction pull<T>(n: Node<T>): T {\n\tlet val: T | undefined | null = n.cache;\n\tconst unsub = n.subscribe((msgs: Messages) => {\n\t\tfor (const [t, v] of msgs) {\n\t\t\tif (t === DATA) val = v as T;\n\t\t}\n\t});\n\tunsub();\n\treturn val as T;\n}\n\n/**\n * TC39 `Signal.State` — a writable signal backed by a GraphReFly `state` node.\n * Automatically registers itself as a dependency if read inside a `Computed`.\n *\n * @example\n * ```ts\n * const count = new Signal.State(0);\n * count.get(); // 0\n * count.set(1);\n * count.get(); // 1\n * ```\n */\nclass SignalState<T> implements AnySignal<T> {\n\t/** @internal */\n\t_node: Node<T>;\n\tprivate readonly _equals: (a: T, b: T) => boolean;\n\n\tconstructor(initial: T, opts?: SignalOptions) {\n\t\tthis._equals = (opts?.equals ?? Object.is) as (a: T, b: T) => boolean;\n\t\tthis._node = state<T>(initial, {\n\t\t\t...opts,\n\t\t\tresubscribable: true,\n\t\t\tresetOnTeardown: true,\n\t\t});\n\t}\n\n\tget(): T {\n\t\t// If we are evaluating inside a computed node, track this read!\n\t\tconst tracker = trackingStack[trackingStack.length - 1];\n\t\tif (tracker) {\n\t\t\tif (this._node.status === \"sentinel\") {\n\t\t\t\tpull(this._node);\n\t\t\t}\n\t\t\treturn tracker(this._node) as T;\n\t\t}\n\n\t\tif (this._node.status === \"sentinel\") {\n\t\t\treturn pull(this._node);\n\t\t}\n\t\treturn this._node.cache as T;\n\t}\n\n\tset(value: T): void {\n\t\tif (this._equals(this.get(), value)) return;\n\t\tbatch(() => {\n\t\t\tthis._node.down([[DIRTY], [DATA, value]]);\n\t\t});\n\t}\n}\n\n/**\n * TC39 `Signal.Computed` — a read-only signal backed by `dynamicNode`.\n * Automatically tracks dependencies when `get()` is called on other signals\n * during its computation.\n *\n * @example\n * ```ts\n * const count = new Signal.State(0);\n * const doubled = new Signal.Computed(() => count.get() * 2);\n * ```\n */\nclass SignalComputed<T> implements AnySignal<T> {\n\t/** @internal */\n\t_node: Node<T>;\n\n\tconstructor(computation: () => T, opts?: SignalOptions) {\n\t\tthis._node = autoTrackNode<T>(\n\t\t\t(track) => {\n\t\t\t\ttrackingStack.push(track);\n\t\t\t\ttry {\n\t\t\t\t\treturn computation();\n\t\t\t\t} finally {\n\t\t\t\t\ttrackingStack.pop();\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\t...opts,\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tresubscribable: true,\n\t\t\t\tresetOnTeardown: true,\n\t\t\t},\n\t\t);\n\t}\n\n\tget(): T {\n\t\t// Computed nodes can themselves be dependencies of other Computed nodes.\n\t\tconst tracker = trackingStack[trackingStack.length - 1];\n\t\tif (tracker) {\n\t\t\tif (this._node.status === \"sentinel\") {\n\t\t\t\tpull(this._node);\n\t\t\t}\n\t\t\treturn tracker(this._node) as T;\n\t\t}\n\n\t\tif (this._node.status === \"sentinel\") {\n\t\t\treturn pull(this._node);\n\t\t}\n\t\treturn this._node.cache as T;\n\t}\n}\n\n/**\n * TC39 Signals-compatible namespace. Wraps GraphReFly primitives.\n * Provides auto-tracking conforming to the TS39 signals proposal.\n *\n * @category compat\n */\nexport const Signal = {\n\tState: SignalState,\n\tComputed: SignalComputed,\n\n\t/**\n\t * Subscribes to changes on a signal.\n\t * Returns an unsubscribe callback.\n\t *\n\t * @example\n\t * ```ts\n\t * const count = new Signal.State(0);\n\t * const unsub = Signal.sub(count, v => console.log(v));\n\t * ```\n\t */\n\tsub: <T>(\n\t\tsignal: AnySignal<T>,\n\t\tcallback:\n\t\t\t| ((value: T) => void)\n\t\t\t| {\n\t\t\t\t\tdata?: (value: T) => void;\n\t\t\t\t\terror?: (err: unknown) => void;\n\t\t\t\t\tcomplete?: () => void;\n\t\t\t },\n\t): (() => void) => {\n\t\tconst handlers =\n\t\t\ttypeof callback === \"function\"\n\t\t\t\t? { data: callback as (value: T) => void, error: undefined, complete: undefined }\n\t\t\t\t: callback;\n\t\t// Skip the initial push-on-subscribe DATA — Signal.sub fires on changes only.\n\t\tlet initial = true;\n\t\treturn signal._node.subscribe((msgs) => {\n\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tif (initial) {\n\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\thandlers.data?.(v as T);\n\t\t\t\t}\n\t\t\t\tif (t === ERROR) handlers.error?.(v);\n\t\t\t\tif (t === COMPLETE) handlers.complete?.();\n\t\t\t}\n\t\t});\n\t},\n} as const;\n\nexport type { SignalComputed, SignalState };\n","// ---------------------------------------------------------------------------\n// Solid bindings — useSubscribe / useStore\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Solid reactivity via createSignal.\n// Works with any Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useSubscribe, useStore } from '@graphrefly/graphrefly-ts/compat/solid';\n// // Optional peer install (only for this adapter): pnpm add solid-js\n// const status = useSubscribe(wsStatusNode); // Accessor<string | undefined>\n// const [count, setCount] = useStore(countNode); // [Accessor<number | undefined>, Setter]\n// ---------------------------------------------------------------------------\n\nimport { createSignal, getOwner, onCleanup } from \"solid-js\";\nimport { DATA, DIRTY, type Messages, RESOLVED } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/** Solid accessor function — returns current value when called. */\nexport type Accessor<T> = () => T;\n\n/**\n * Subscribe to a `Node<T>` as a Solid signal. Auto-cleans up with the owning scope.\n * Subscription lifecycle is tied to Solid scope cleanup (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): Accessor<T | undefined | null> {\n\tconst [value, setValue] = createSignal(node.cache, { equals: false });\n\n\tconst unsub = node.subscribe(() => {\n\t\tsetValue(() => node.cache);\n\t});\n\n\tif (getOwner()) {\n\t\tonCleanup(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribe called outside a Solid reactive owner — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn value;\n}\n\n/**\n * Bind a writable `Node<T>` as a Solid resource tuple `[accessor, setter]`.\n * Setter always forwards `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Solid scope cleanup (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): [Accessor<T | undefined | null>, (v: T) => void] {\n\tconst value = useSubscribe(node);\n\tconst setter = (v: T) => {\n\t\tnode.down([[DIRTY], [DATA, v]]);\n\t};\n\treturn [value, setter];\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records as a Solid accessor.\n * Re-subscribes all per-key fields whenever `keys` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 3`) to avoid DIRTY-phase churn.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): Accessor<Record<K, R>> {\n\tconst [value, setValue] = createSignal({} as Record<K, R>, { equals: false });\n\tlet entrySubs: Array<() => void> = [];\n\n\tconst cleanupEntries = () => {\n\t\tfor (const unsub of entrySubs) unsub();\n\t\tentrySubs = [];\n\t};\n\n\tconst buildSnapshot = (): Record<K, R> => {\n\t\tconst snap = {} as Record<K, R>;\n\t\tfor (const key of keysNode.cache ?? []) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst values = {} as R;\n\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t}\n\t\t\tsnap[key] = values;\n\t\t}\n\t\treturn snap;\n\t};\n\n\tconst sync = (nextKeys: K[]) => {\n\t\tcleanupEntries();\n\t\tfor (const key of nextKeys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\tsetValue(() => buildSnapshot());\n\t\t\t\t});\n\t\t\t\tentrySubs.push(unsub);\n\t\t\t}\n\t\t}\n\t\tsetValue(() => buildSnapshot());\n\t};\n\n\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\tif (msgs.some((m) => m[0] === DATA || m[0] === RESOLVED)) {\n\t\t\tsync(keysNode.cache ?? []);\n\t\t}\n\t});\n\tsync(keysNode.cache ?? []);\n\n\tif (getOwner()) {\n\t\tonCleanup(() => {\n\t\t\tkeysUnsub();\n\t\t\tcleanupEntries();\n\t\t});\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn value;\n}\n","// ---------------------------------------------------------------------------\n// Svelte bindings — useSubscribe / useStore\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Svelte's store contract. Works with any\n// Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useSubscribe, useStore } from '@graphrefly/graphrefly-ts/compat/svelte';\n// // Optional peer install (only for this adapter): pnpm add svelte\n// const status = useSubscribe(wsStatusNode); // Svelte readable store\n// const count = useStore(countNode); // Svelte writable store\n// // In template: $status, $count\n// // $count = 42\n// ---------------------------------------------------------------------------\n\nimport { DATA, DIRTY, type Messages, RESOLVED } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/** Svelte store contract — implements the minimal `subscribe` method. */\nexport interface SvelteReadable<T> {\n\tsubscribe(run: (value: T) => void): () => void;\n}\n\n/** Svelte writable store contract. */\nexport interface SvelteWritable<T> extends SvelteReadable<T> {\n\tset(value: T): void;\n\tupdate(updater: (value: T) => T): void;\n}\n\n/**\n * Subscribe to a `Node<T>` as a Svelte readable store (implements Svelte store contract).\n * Subscription lifecycle is tied to Svelte store unsubscription (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): SvelteReadable<T | undefined | null> {\n\treturn {\n\t\tsubscribe(run: (value: T | undefined | null) => void): () => void {\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\trun(node.cache);\n\t\t\t});\n\t\t\trun(node.cache);\n\t\t\treturn unsub;\n\t\t},\n\t};\n}\n\n/**\n * Bind a writable `Node<T>` as a Svelte writable store.\n * Reads and writes adapt seamlessly.\n * Setter/update always forward `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Svelte store unsubscription (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): SvelteWritable<T | undefined | null> {\n\treturn {\n\t\tsubscribe(run: (value: T | undefined | null) => void): () => void {\n\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\trun(node.cache);\n\t\t\t});\n\t\t\trun(node.cache);\n\t\t\treturn unsub;\n\t\t},\n\t\tset(value: T | undefined | null) {\n\t\t\tnode.down([[DIRTY], [DATA, value]]);\n\t\t},\n\t\tupdate(updater: (value: T | undefined | null) => T | undefined | null) {\n\t\t\tconst next = updater(node.cache);\n\t\t\tnode.down([[DIRTY], [DATA, next]]);\n\t\t},\n\t};\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord`. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic keyed record of nodes as a Svelte readable store.\n * Re-subscribes all per-key fields whenever `keysNode` changes.\n * Key re-sync is gated to settled batches (`messageTier >= 3`) to avoid DIRTY-phase churn.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeysNode: Node<K[]>,\n\tfactory: NodeFactory<K, R>,\n): SvelteReadable<Record<K, R>> {\n\treturn {\n\t\tsubscribe(run: (value: Record<K, R>) => void): () => void {\n\t\t\tlet entrySubs: Array<() => void> = [];\n\n\t\t\tconst cleanupEntries = () => {\n\t\t\t\tfor (const unsub of entrySubs) unsub();\n\t\t\t\tentrySubs = [];\n\t\t\t};\n\n\t\t\tconst buildSnapshot = (): Record<K, R> => {\n\t\t\t\tconst snap = {} as Record<K, R>;\n\t\t\t\tfor (const key of keysNode.cache ?? []) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tconst values = {} as R;\n\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t\t\t}\n\t\t\t\t\tsnap[key] = values;\n\t\t\t\t}\n\t\t\t\treturn snap;\n\t\t\t};\n\n\t\t\tconst sync = (nextKeys: K[]) => {\n\t\t\t\tcleanupEntries();\n\t\t\t\tfor (const key of nextKeys) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tfor (const field of Object.keys(nodes) as (keyof R)[]) {\n\t\t\t\t\t\tconst unsub = nodes[field].subscribe(() => {\n\t\t\t\t\t\t\trun(buildSnapshot());\n\t\t\t\t\t\t});\n\t\t\t\t\t\tentrySubs.push(unsub);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trun(buildSnapshot());\n\t\t\t};\n\n\t\t\tconst keysUnsub = keysNode.subscribe((msgs: Messages) => {\n\t\t\t\tif (msgs.some((m) => m[0] === DATA || m[0] === RESOLVED)) {\n\t\t\t\t\tsync(keysNode.cache ?? []);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsync(keysNode.cache ?? []);\n\n\t\t\treturn () => {\n\t\t\t\tkeysUnsub();\n\t\t\t\tcleanupEntries();\n\t\t\t};\n\t\t},\n\t};\n}\n","// ---------------------------------------------------------------------------\n// Vue bindings — useStore / useSubscribe\n// ---------------------------------------------------------------------------\n// Bridges GraphReFly nodes into Vue reactivity. Works with any\n// Node<T>, including companion nodes (node.meta.status).\n//\n// Usage:\n// import { useStore, useSubscribe } from '@graphrefly/graphrefly-ts/compat/vue';\n// // Optional peer install (only for this adapter): pnpm add vue\n// const count = useStore(counterNode); // Ref<number | undefined> (read + write)\n// const status = useSubscribe(wsStatusNode); // Readonly<Ref<string | undefined>>\n// ---------------------------------------------------------------------------\n\nimport {\n\tcomputed,\n\tgetCurrentScope,\n\tisRef,\n\tonScopeDispose,\n\ttype Ref,\n\treadonly,\n\tshallowRef,\n\ttype WatchSource,\n\twatch,\n} from \"vue\";\nimport { DATA, DIRTY } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\n\n/**\n * Subscribe to a read-only `Node<T>` as a Vue `Ref<T>`. Auto-unsubscribes on scope disposal.\n * Subscription lifecycle is tied to Vue scope disposal (not node terminal messages).\n */\nexport function useSubscribe<T>(node: Node<T>): Readonly<Ref<T | undefined | null>> {\n\tconst ref = shallowRef(node.cache) as Ref<T | undefined | null>;\n\n\tconst unsub = node.subscribe(() => {\n\t\tref.value = node.cache;\n\t});\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribe called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn readonly(ref) as Readonly<Ref<T | undefined | null>>;\n}\n\n/**\n * Bind a writable `Node<T>` as a Vue `Ref<T>`. Reads and writes are bidirectional.\n * Value sets always dispatch `[[DIRTY], [DATA, value]]`, including `value === undefined`.\n * Subscription lifecycle is tied to Vue scope disposal (not node terminal messages).\n */\nexport function useStore<T>(node: Node<T>): Ref<T | undefined | null> {\n\tconst inner = shallowRef(node.cache) as Ref<T | undefined | null>;\n\n\tconst unsub = node.subscribe(() => {\n\t\tinner.value = node.cache;\n\t});\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => unsub());\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useStore called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn computed({\n\t\tget: () => inner.value,\n\t\tset: (v: T | undefined | null) => {\n\t\t\tnode.down([[DIRTY], [DATA, v]]);\n\t\t},\n\t});\n}\n\n/** Maps a key to an object of nodes. Used by `useSubscribeRecord` factory. */\nexport type NodeFactory<K, R extends Record<string, any>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/**\n * Subscribe to a dynamic set of keyed node records. When keys change,\n * old subscriptions are torn down and new ones created automatically.\n * Must be called during Vue `setup()`.\n */\nexport function useSubscribeRecord<K extends string, R extends Record<string, any>>(\n\tkeys: WatchSource<K[] | undefined>,\n\tfactory: NodeFactory<K, R>,\n): Readonly<Ref<Record<K, R>>> {\n\tconst result = shallowRef<Record<K, R>>({} as Record<K, R>);\n\n\t// Track active subscriptions per key (strictly enclosed memory mapping)\n\tconst activeSubs = new Map<K, { subs: Array<() => void>; values: R }>();\n\tlet disposed = false;\n\n\tlet batchPending = false;\n\tfunction scheduleBatch() {\n\t\tif (batchPending) return;\n\t\tbatchPending = true;\n\t\tqueueMicrotask(() => {\n\t\t\tif (disposed) return;\n\t\t\tbatchPending = false;\n\t\t\tconst snap = {} as Record<K, R>;\n\t\t\tfor (const [key, entry] of activeSubs) {\n\t\t\t\tsnap[key] = { ...entry.values };\n\t\t\t}\n\t\t\tresult.value = snap;\n\t\t});\n\t}\n\n\tfunction sync(newKeys: K[]) {\n\t\tfor (const entry of activeSubs.values()) {\n\t\t\tfor (const unsub of entry.subs) unsub();\n\t\t}\n\t\tactiveSubs.clear();\n\n\t\tfor (const key of newKeys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst fields = Object.keys(nodes) as (keyof R)[];\n\t\t\tconst values = {} as R;\n\t\t\tconst subs: Array<() => void> = [];\n\n\t\t\tfor (const field of fields) {\n\t\t\t\tconst node = nodes[field];\n\t\t\t\tvalues[field] = node.cache as R[keyof R];\n\t\t\t\tconst unsub = node.subscribe(() => {\n\t\t\t\t\tvalues[field] = node.cache as R[keyof R];\n\t\t\t\t\tscheduleBatch();\n\t\t\t\t});\n\t\t\t\tsubs.push(unsub);\n\t\t\t}\n\n\t\t\tactiveSubs.set(key, { subs, values });\n\t\t}\n\n\t\tconst snap = {} as Record<K, R>;\n\t\tfor (const [key, entry] of activeSubs) {\n\t\t\tsnap[key] = { ...entry.values };\n\t\t}\n\t\tresult.value = snap;\n\t}\n\n\tconst readKeys = (): K[] => {\n\t\tconst current = typeof keys === \"function\" ? keys() : isRef(keys) ? keys.value : keys;\n\t\treturn [...(current ?? [])];\n\t};\n\n\twatch(readKeys, (newKeys) => sync(newKeys ?? []), { immediate: true });\n\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(() => {\n\t\t\tdisposed = true;\n\t\t\tfor (const entry of activeSubs.values()) {\n\t\t\t\tfor (const unsub of entry.subs) unsub();\n\t\t\t}\n\t\t\tactiveSubs.clear();\n\t\t});\n\t} else if (typeof console !== \"undefined\") {\n\t\tconsole.warn(\n\t\t\t\"[graphrefly-ts] useSubscribeRecord called outside a Vue scope — subscription will not be auto-disposed.\",\n\t\t);\n\t}\n\n\treturn readonly(result) as Readonly<Ref<Record<K, R>>>;\n}\n","import { DATA } from \"../../core/messages.js\";\nimport { state as stateNode } from \"../../core/sugar.js\";\nimport { Graph } from \"../../graph/graph.js\";\n\n// Zustand fires listeners on every setState, regardless of reference\n// equality. Configure the state node with a permissive equals so every\n// emit produces DATA (not RESOLVED). Diamond coordination still works\n// because `n.emit` routes through the framed pipeline which auto-\n// prefixes `[DIRTY]`.\nconst alwaysDiffer = () => false;\n\n/** Zustand-compatible Store API. */\nexport interface StoreApi<T> {\n\tgetState: () => T;\n\tsetState: (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean) => void;\n\tgetInitialState: () => T;\n\tsubscribe: (listener: (state: T, prevState: T) => void) => () => void;\n\tdestroy: () => void;\n}\n\n/** Function type for initializing the store. */\nexport type StateCreator<T> = (\n\tset: StoreApi<T>[\"setState\"],\n\tget: StoreApi<T>[\"getState\"],\n\tapi: StoreApi<T>,\n) => T;\n\n/**\n * Creates a Zustand-compatible store backed by a GraphReFly state node.\n * returns an object that is both a Graph and a StoreApi.\n *\n * @example\n * ```ts\n * const store = create((set) => ({\n * count: 0,\n * inc: () => set((s) => ({ count: s.count + 1 }))\n * }));\n * store.getState().inc();\n * ```\n *\n * @category compat\n */\nexport function create<T extends object>(initializer: StateCreator<T>): Graph & StoreApi<T> {\n\tconst g = new Graph(\"zustand\");\n\tconst s = stateNode<T>(undefined as unknown as T, {\n\t\tname: \"state\",\n\t\tequals: alwaysDiffer,\n\t});\n\tg.add(\"state\", s);\n\n\tconst getState = () => s.cache as T;\n\tconst setState = (partial: any, replace?: boolean): void => {\n\t\tconst prev = getState();\n\t\tconst next = typeof partial === \"function\" ? partial(prev) : partial;\n\t\tconst nextState = replace ? next : { ...prev, ...next };\n\t\t// `n.emit` goes through `_actionEmit` → `bundle()`, which auto-\n\t\t// prefixes `[DIRTY]` so diamond legs coordinate under downstream\n\t\t// composition. The `alwaysDiffer` equals keeps zustand's \"fire\n\t\t// on every setState\" semantics — the framing is what matters\n\t\t// here, not the equality folding.\n\t\ts.emit(nextState);\n\t};\n\n\tconst api: StoreApi<T> = {\n\t\tgetState,\n\t\tsetState,\n\t\tgetInitialState: () => initialValue,\n\t\tsubscribe: (listener) => {\n\t\t\tlet prev = getState();\n\t\t\t// Skip the initial push-on-subscribe DATA — zustand subscribe fires on changes only.\n\t\t\tlet initial = true;\n\t\t\treturn s.subscribe((msgs) => {\n\t\t\t\tfor (const [t, v] of msgs) {\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tif (initial) {\n\t\t\t\t\t\t\tinitial = false;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlistener(v as T, prev);\n\t\t\t\t\t\tprev = v as T;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tdestroy: g.destroy.bind(g),\n\t};\n\n\tconst initialValue = initializer(setState, getState, api);\n\ts.emit(initialValue);\n\n\treturn Object.assign(g, api);\n}\n","/**\n * Patterns layer: domain/solution helpers (Phase 4+).\n */\n\nexport * as ai from \"./ai.js\";\nexport * as cqrs from \"./cqrs.js\";\nexport * as demoShell from \"./demo-shell.js\";\nexport * as domainTemplates from \"./domain-templates.js\";\nexport * as graphspec from \"./graphspec.js\";\nexport * as harness from \"./harness/index.js\";\nexport * as memory from \"./memory.js\";\nexport * as messaging from \"./messaging.js\";\nexport * as orchestration from \"./orchestration.js\";\nexport * as layout from \"./reactive-layout/index.js\";\nexport * as reduction from \"./reduction.js\";\n","/**\n * AI surface patterns (roadmap §4.4).\n *\n * Domain-layer factories for LLM-backed agents, chat, tool registries, and\n * agentic memory. Composed from core + extra + Phase 3–4.3 primitives.\n */\n\nimport type { Actor } from \"../core/actor.js\";\nimport { batch } from \"../core/batch.js\";\nimport { monotonicNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, ERROR } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, producer, state } from \"../core/sugar.js\";\nimport {\n\ttype DistillBundle,\n\ttype DistillOptions,\n\tdistill,\n\ttype Extraction,\n} from \"../extra/composite.js\";\nimport { switchMap } from \"../extra/operators.js\";\nimport { type ReactiveLogBundle, reactiveLog } from \"../extra/reactive-log.js\";\nimport { fromAny, fromTimer, type NodeInput } from \"../extra/sources.js\";\nimport type { StorageHandle, StorageTier } from \"../extra/storage.js\";\nimport { ResettableTimer } from \"../extra/timer.js\";\nimport {\n\tGraph,\n\ttype GraphAttachStorageOptions,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n} from \"../graph/graph.js\";\nimport {\n\tdecay,\n\ttype KnowledgeGraphGraph,\n\tknowledgeGraph,\n\ttype LightCollectionBundle,\n\tlightCollection,\n\ttype VectorIndexBundle,\n\ttype VectorSearchResult,\n\tvectorIndex,\n} from \"./memory.js\";\nimport { type TopicGraph, topic } from \"./messaging.js\";\nimport { type GateController, type GateOptions, gate } from \"./orchestration.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A single chat message in a conversation. */\nexport type ChatMessage = {\n\treadonly role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n\treadonly content: string;\n\treadonly name?: string;\n\treadonly toolCallId?: string;\n\treadonly toolCalls?: readonly ToolCall[];\n\treadonly metadata?: Record<string, unknown>;\n};\n\n/** A tool invocation request from an LLM. */\nexport type ToolCall = {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly arguments: Record<string, unknown>;\n};\n\n/** The response from an LLM invocation. */\nexport type LLMResponse = {\n\treadonly content: string;\n\treadonly toolCalls?: readonly ToolCall[];\n\treadonly usage?: { readonly inputTokens: number; readonly outputTokens: number };\n\treadonly finishReason?: string;\n\treadonly metadata?: Record<string, unknown>;\n};\n\n/** Provider-agnostic LLM client adapter protocol. */\nexport type LLMAdapter = {\n\tinvoke(messages: readonly ChatMessage[], opts?: LLMInvokeOptions): NodeInput<LLMResponse>;\n\tstream(messages: readonly ChatMessage[], opts?: LLMInvokeOptions): AsyncIterable<string>;\n};\n\nexport type LLMInvokeOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n\tsignal?: AbortSignal;\n};\n\n/** A tool definition for LLM consumption. */\nexport type ToolDefinition = {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly parameters: Record<string, unknown>; // JSON Schema\n\treadonly handler: (args: Record<string, unknown>) => NodeInput<unknown>;\n\t/**\n\t * V0 version of the backing node at `knobsAsTools()` call time (§6.0b).\n\t * Snapshot — re-call `knobsAsTools()` to refresh.\n\t */\n\treadonly version?: { id: string; version: number };\n};\n\nexport type AgentLoopStatus = \"idle\" | \"thinking\" | \"acting\" | \"done\" | \"error\";\n\n/**\n * A single chunk from any streaming source (LLM tokens, WebSocket, SSE, file tail).\n * Generic enough for any streaming source, not just LLM.\n */\nexport type StreamChunk = {\n\t/** Identifier for the stream source (adapter name, URL, etc.). */\n\treadonly source: string;\n\t/** This chunk's content. */\n\treadonly token: string;\n\t/** Full accumulated text so far. */\n\treadonly accumulated: string;\n\t/** 0-based chunk counter. */\n\treadonly index: number;\n};\n\n// ---------------------------------------------------------------------------\n// Meta helpers\n// ---------------------------------------------------------------------------\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction aiMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"ai\", kind, extra);\n}\n\nfunction isPromiseLike(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isNodeLike(x: unknown): x is Node<unknown> {\n\treturn (\n\t\ttypeof x === \"object\" &&\n\t\tx !== null &&\n\t\t\"subscribe\" in x &&\n\t\ttypeof (x as Node<unknown>).subscribe === \"function\" &&\n\t\t\"cache\" in x\n\t);\n}\n\nfunction isAsyncIterableLike(x: unknown): x is AsyncIterable<unknown> {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === \"object\" &&\n\t\tSymbol.asyncIterator in x &&\n\t\ttypeof (x as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** First settled `DATA` from a `Node` (do not pass plain strings — `fromAny` would iterate chars). */\nfunction firstDataFromNode(\n\tresolved: Node<unknown>,\n\topts?: { timeoutMs?: number },\n): Promise<unknown> {\n\t// Only trust get() when node is in settled state\n\tif ((resolved as { status?: string }).status === \"settled\") {\n\t\tconst immediate = resolved.cache;\n\t\tif (immediate !== undefined) {\n\t\t\treturn Promise.resolve(immediate);\n\t\t}\n\t}\n\tconst timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = new ResettableTimer();\n\t\tconst unsub = resolved.subscribe((messages) => {\n\t\t\tfor (const msg of messages) {\n\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\ttimer.cancel();\n\t\t\t\t\tunsub();\n\t\t\t\t\tresolve(msg[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === ERROR) {\n\t\t\t\t\ttimer.cancel();\n\t\t\t\t\tunsub();\n\t\t\t\t\treject(msg[1]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (msg[0] === COMPLETE) {\n\t\t\t\t\ttimer.cancel();\n\t\t\t\t\tunsub();\n\t\t\t\t\treject(new Error(\"firstDataFromNode: completed without producing a value\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\ttimer.start(timeoutMs, () => {\n\t\t\tunsub();\n\t\t\treject(new Error(`firstDataFromNode: timed out after ${timeoutMs}ms`));\n\t\t});\n\t});\n}\n\n/** Await Promise-likes, then resolve `Node` / async-iterable inputs via `fromAny` + first `DATA`. */\nasync function resolveToolHandlerResult(value: unknown): Promise<unknown> {\n\tif (isPromiseLike(value)) {\n\t\treturn resolveToolHandlerResult(await value);\n\t}\n\tif (isNodeLike(value)) {\n\t\treturn firstDataFromNode(value);\n\t}\n\tif (isAsyncIterableLike(value)) {\n\t\treturn firstDataFromNode(fromAny(value as NodeInput<unknown>));\n\t}\n\treturn value;\n}\n\n// ---------------------------------------------------------------------------\n// fromLLM\n// ---------------------------------------------------------------------------\n\nexport type FromLLMOptions = {\n\tname?: string;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n};\n\n/**\n * Reactive LLM invocation adapter. Returns a derived node that re-invokes\n * the LLM whenever the messages dep changes.\n *\n * Uses `switchMap` internally — new invocations cancel stale in-flight ones.\n */\nexport function fromLLM(\n\tadapter: LLMAdapter,\n\tmessages: NodeInput<readonly ChatMessage[]>,\n\topts?: FromLLMOptions,\n): Node<LLMResponse | null> {\n\tconst msgsNode = fromAny(messages);\n\tconst result = switchMap(msgsNode, (msgs) => {\n\t\tif (!msgs || (msgs as readonly ChatMessage[]).length === 0) {\n\t\t\treturn state<LLMResponse | null>(null) as NodeInput<LLMResponse | null>;\n\t\t}\n\t\tconst tools = opts?.tools;\n\t\treturn adapter.invoke(msgs as readonly ChatMessage[], {\n\t\t\tmodel: opts?.model,\n\t\t\ttemperature: opts?.temperature,\n\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\ttools,\n\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t}) as NodeInput<LLMResponse | null>;\n\t});\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// streamingPromptNode\n// ---------------------------------------------------------------------------\n\nexport type StreamingPromptNodeOptions = {\n\tname?: string;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Output format — `\"json\"` attempts JSON.parse on the final accumulated text. Default: `\"text\"`. */\n\tformat?: \"text\" | \"json\";\n\tsystemPrompt?: string;\n};\n\n/**\n * Bundle returned by {@link streamingPromptNode}.\n */\nexport type StreamingPromptNodeHandle<T> = {\n\t/** Final parsed result (emits once per invocation, after stream completes). */\n\toutput: Node<T | null>;\n\t/** Live stream topic — subscribe to `stream.latest` or `stream.events` for chunks. */\n\tstream: TopicGraph<StreamChunk>;\n\t/** Tear down the keepalive subscription and release resources. */\n\tdispose: () => void;\n};\n\n/**\n * Streaming LLM transform: wraps a prompt template + adapter into a reactive\n * streaming pipeline. Re-invokes the LLM whenever any dep changes; the\n * previous in-flight stream is canceled automatically via `switchMap`.\n *\n * Each token chunk is published to a {@link TopicGraph} as a {@link StreamChunk}.\n * Extractors can mount on the topic independently (see {@link streamExtractor}).\n * Zero overhead if nobody subscribes to the stream topic.\n *\n * The `output` node emits the final parsed result (like {@link promptNode}).\n * The async boundary is handled by `fromAny` (spec §5.10 compliant).\n */\nexport function streamingPromptNode<T = string>(\n\tadapter: LLMAdapter,\n\tdeps: readonly Node<unknown>[],\n\tprompt: string | ((...depValues: unknown[]) => string),\n\topts?: StreamingPromptNodeOptions,\n): StreamingPromptNodeHandle<T> {\n\tconst sourceName = opts?.name ?? \"llm\";\n\tconst format = opts?.format ?? \"text\";\n\tconst streamTopic = topic<StreamChunk>(`${sourceName}/stream`);\n\n\tconst messagesNode = derived<readonly ChatMessage[]>(deps as Node<unknown>[], (values) => {\n\t\tif (values.some((v) => v == null)) return [];\n\t\tconst text = typeof prompt === \"string\" ? prompt : prompt(...values);\n\t\tif (!text) return [];\n\t\tconst msgs: ChatMessage[] = [];\n\t\tif (opts?.systemPrompt) msgs.push({ role: \"system\", content: opts.systemPrompt });\n\t\tmsgs.push({ role: \"user\", content: text });\n\t\treturn msgs;\n\t});\n\n\tconst output = switchMap(messagesNode, (msgs) => {\n\t\tconst chatMsgs = msgs as readonly ChatMessage[];\n\t\tif (!chatMsgs || chatMsgs.length === 0) {\n\t\t\treturn state<T | null>(null) as NodeInput<T | null>;\n\t\t}\n\n\t\tconst ac = new AbortController();\n\n\t\tasync function* pumpAndCollect(): AsyncGenerator<T | null> {\n\t\t\tlet accumulated = \"\";\n\t\t\tlet index = 0;\n\t\t\ttry {\n\t\t\t\tfor await (const token of adapter.stream(chatMsgs, {\n\t\t\t\t\tmodel: opts?.model,\n\t\t\t\t\ttemperature: opts?.temperature,\n\t\t\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t\t\t\tsignal: ac.signal,\n\t\t\t\t})) {\n\t\t\t\t\taccumulated += token;\n\t\t\t\t\tstreamTopic.publish({\n\t\t\t\t\t\tsource: sourceName,\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\taccumulated,\n\t\t\t\t\t\tindex: index++,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tlet result: T | null;\n\t\t\t\tif (format === \"json\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = JSON.parse(stripFences(accumulated)) as T;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tresult = accumulated as unknown as T;\n\t\t\t\t}\n\t\t\t\tyield result;\n\t\t\t} finally {\n\t\t\t\tac.abort();\n\t\t\t}\n\t\t}\n\n\t\treturn fromAny(pumpAndCollect());\n\t});\n\n\tconst unsub = keepalive(output);\n\n\treturn {\n\t\toutput,\n\t\tstream: streamTopic,\n\t\tdispose: () => {\n\t\t\tunsub();\n\t\t\tstreamTopic.destroy();\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// streamExtractor\n// ---------------------------------------------------------------------------\n\n/**\n * Mounts an extractor function on a streaming topic. Returns a derived node\n * that emits extracted values as chunks arrive.\n *\n * `extractFn` receives the accumulated text from the latest chunk and returns\n * the extracted value, or `null` if nothing detected yet. This is the building\n * block for keyword flags, tool call detection, cost metering, etc.\n *\n * @param streamTopic - The stream topic to extract from.\n * @param extractFn - `(accumulated: string) => T | null`.\n * @param opts - Optional name.\n * @returns Derived node emitting extracted values.\n */\nexport function streamExtractor<T>(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\textractFn: (accumulated: string) => T | null,\n\topts?: {\n\t\tname?: string;\n\t\t/**\n\t\t * Optional structural equals for the extractor output. When two\n\t\t * consecutive chunks produce structurally-equal outputs, the framework\n\t\t * emits `RESOLVED` instead of `DATA`, saving downstream work. Default:\n\t\t * reference equality (`Object.is`). The library cannot know your\n\t\t * output shape — supply this when your `extractFn` returns structured\n\t\t * objects or arrays.\n\t\t */\n\t\tequals?: (a: T | null, b: T | null) => boolean;\n\t},\n): Node<T | null> {\n\treturn derived<T | null>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk]) => {\n\t\t\tif (chunk == null) return null;\n\t\t\treturn extractFn((chunk as StreamChunk).accumulated);\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ?? \"extractor\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: null,\n\t\t\tmeta: aiMeta(\"stream_extractor\"),\n\t\t\t...(opts?.equals ? { equals: opts.equals } : {}),\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// keywordFlagExtractor\n// ---------------------------------------------------------------------------\n\n/** A keyword match detected in the stream. */\nexport type KeywordFlag = {\n\treadonly label: string;\n\treadonly pattern: RegExp;\n\treadonly match: string;\n\treadonly position: number;\n};\n\nexport type KeywordFlagExtractorOptions = {\n\tpatterns: readonly { pattern: RegExp; label: string }[];\n\tname?: string;\n\t/**\n\t * Maximum length of any pattern's literal text. Used as an overlap window\n\t * when cursoring through the accumulated stream so matches that span\n\t * chunk boundaries aren't missed. Default: 128.\n\t */\n\tmaxPatternLength?: number;\n};\n\nconst keywordFlagsEqual = (\n\ta: readonly KeywordFlag[] | null,\n\tb: readonly KeywordFlag[] | null,\n): boolean => {\n\tif (a === b) return true;\n\tif (a == null || b == null) return a === b;\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tconst x = a[i];\n\t\tconst y = b[i];\n\t\tif (\n\t\t\tx.label !== y.label ||\n\t\t\tx.pattern !== y.pattern ||\n\t\t\tx.match !== y.match ||\n\t\t\tx.position !== y.position\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n};\n\n/**\n * Mounts a keyword-flag extractor on a streaming topic. Scans accumulated text\n * for all configured patterns and emits an array of matches.\n *\n * Use cases: design invariant violations (`setTimeout`, `EventEmitter`), PII\n * detection (SSN, email, phone), toxicity keywords, off-track reasoning.\n *\n * **Streaming optimization.** Maintains a cursor across chunks in `ctx.store`\n * so each chunk scans only the delta region `accumulated.slice(scannedTo -\n * maxPatternLength)` — not the full string. Default structural equals\n * suppresses DATA emission when no new flags were found this chunk.\n */\nexport function keywordFlagExtractor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\topts: KeywordFlagExtractorOptions,\n): Node<readonly KeywordFlag[]> {\n\tconst maxPatternLength = opts.maxPatternLength ?? 128;\n\treturn derived<readonly KeywordFlag[]>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk], ctx) => {\n\t\t\tif (chunk == null) return [];\n\t\t\tconst accumulated = (chunk as StreamChunk).accumulated;\n\n\t\t\tif (!(\"flags\" in ctx.store)) {\n\t\t\t\tctx.store.flags = [] as KeywordFlag[];\n\t\t\t\tctx.store.scannedTo = 0;\n\t\t\t}\n\t\t\tconst flags = ctx.store.flags as KeywordFlag[];\n\t\t\tconst scannedTo = ctx.store.scannedTo as number;\n\n\t\t\t// Scan the delta plus an overlap window so matches that span\n\t\t\t// chunk boundaries (e.g. \"EventE\" + \"mitter\") are still found.\n\t\t\tconst startOffset = Math.max(0, scannedTo - maxPatternLength);\n\t\t\tconst region = accumulated.slice(startOffset);\n\t\t\tlet added = false;\n\t\t\tfor (const { pattern, label } of opts.patterns) {\n\t\t\t\tconst re = new RegExp(pattern.source, `${pattern.flags.replace(\"g\", \"\")}g`);\n\t\t\t\tfor (const m of region.matchAll(re)) {\n\t\t\t\t\tconst pos = startOffset + m.index!;\n\t\t\t\t\t// Skip matches that end inside the already-scanned prefix.\n\t\t\t\t\tif (pos + m[0].length <= scannedTo) continue;\n\t\t\t\t\tflags.push({ label, pattern, match: m[0], position: pos });\n\t\t\t\t\tadded = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.store.scannedTo = accumulated.length;\n\n\t\t\t// Always return a fresh copy so downstream never holds a live\n\t\t\t// reference to ctx.store.flags. Structural equals suppresses the\n\t\t\t// emission when no new flag was added this chunk.\n\t\t\treturn added ? [...flags] : flags.slice();\n\t\t},\n\t\t{\n\t\t\tname: opts.name ?? \"keyword-flag-extractor\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: [],\n\t\t\tmeta: aiMeta(\"keyword_flag_extractor\"),\n\t\t\tequals: keywordFlagsEqual,\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// toolCallExtractor\n// ---------------------------------------------------------------------------\n\n/** A tool call detected in the stream. */\nexport type ExtractedToolCall = {\n\treadonly name: string;\n\treadonly arguments: Record<string, unknown>;\n\treadonly raw: string;\n\treadonly startIndex: number;\n};\n\nconst toolCallsEqual = (\n\ta: readonly ExtractedToolCall[] | null,\n\tb: readonly ExtractedToolCall[] | null,\n): boolean => {\n\tif (a === b) return true;\n\tif (a == null || b == null) return a === b;\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tconst x = a[i];\n\t\tconst y = b[i];\n\t\tif (x.startIndex !== y.startIndex || x.name !== y.name || x.raw !== y.raw) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n};\n\n/**\n * Mounts a tool-call extractor on a streaming topic. Scans accumulated text\n * for complete JSON objects containing `\"name\"` and `\"arguments\"` keys (the\n * standard tool_call shape). Partial JSON is ignored until the closing brace.\n *\n * Feeds into the tool interception chain for reactive tool gating mid-stream.\n *\n * **Streaming optimization.** Maintains a cursor (`scanFrom`) in `ctx.store`\n * so each chunk resumes brace-scanning from the position after the last\n * complete parse (or the last incomplete open brace). Already-parsed objects\n * are not re-parsed. Default structural equals suppresses DATA emission when\n * no new tool call completed this chunk.\n */\nexport function toolCallExtractor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\topts?: { name?: string },\n): Node<readonly ExtractedToolCall[]> {\n\treturn derived<readonly ExtractedToolCall[]>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk], ctx) => {\n\t\t\tif (chunk == null) return [];\n\t\t\tconst accumulated = (chunk as StreamChunk).accumulated;\n\n\t\t\tif (!(\"calls\" in ctx.store)) {\n\t\t\t\tctx.store.calls = [] as ExtractedToolCall[];\n\t\t\t\tctx.store.scanFrom = 0;\n\t\t\t}\n\t\t\tconst calls = ctx.store.calls as ExtractedToolCall[];\n\t\t\tlet i = ctx.store.scanFrom as number;\n\t\t\tlet added = false;\n\n\t\t\twhile (i < accumulated.length) {\n\t\t\t\tconst start = accumulated.indexOf(\"{\", i);\n\t\t\t\tif (start === -1) {\n\t\t\t\t\tctx.store.scanFrom = accumulated.length;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlet depth = 0;\n\t\t\t\tlet end = -1;\n\t\t\t\tlet inString = false;\n\t\t\t\tfor (let j = start; j < accumulated.length; j++) {\n\t\t\t\t\tconst ch = accumulated[j];\n\t\t\t\t\tif (inString) {\n\t\t\t\t\t\tif (ch === \"\\\\\" && j + 1 < accumulated.length) {\n\t\t\t\t\t\t\tj++; // skip escaped character\n\t\t\t\t\t\t} else if (ch === '\"') {\n\t\t\t\t\t\t\tinString = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (ch === '\"') {\n\t\t\t\t\t\tinString = true;\n\t\t\t\t\t} else if (ch === \"{\") {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t} else if (ch === \"}\") {\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\tend = j;\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\tif (end === -1) {\n\t\t\t\t\t// Incomplete — resume brace-scanning from this open brace\n\t\t\t\t\t// next chunk. Do NOT advance past it.\n\t\t\t\t\tctx.store.scanFrom = start;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst raw = accumulated.slice(start, end + 1);\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(raw) as Record<string, unknown>;\n\t\t\t\t\tif (\n\t\t\t\t\t\ttypeof parsed.name === \"string\" &&\n\t\t\t\t\t\tparsed.arguments != null &&\n\t\t\t\t\t\ttypeof parsed.arguments === \"object\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tcalls.push({\n\t\t\t\t\t\t\tname: parsed.name,\n\t\t\t\t\t\t\targuments: parsed.arguments as Record<string, unknown>,\n\t\t\t\t\t\t\traw,\n\t\t\t\t\t\t\tstartIndex: start,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tadded = true;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Not valid JSON — skip\n\t\t\t\t}\n\t\t\t\ti = end + 1;\n\t\t\t\tctx.store.scanFrom = i;\n\t\t\t}\n\n\t\t\t// Always return a fresh copy so downstream never holds a live\n\t\t\t// reference to ctx.store.calls.\n\t\t\treturn added ? [...calls] : calls.slice();\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ?? \"tool-call-extractor\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: [],\n\t\t\tmeta: aiMeta(\"tool_call_extractor\"),\n\t\t\tequals: toolCallsEqual,\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// costMeterExtractor\n// ---------------------------------------------------------------------------\n\n/** A cost meter reading from the stream. */\nexport type CostMeterReading = {\n\treadonly chunkCount: number;\n\treadonly charCount: number;\n\treadonly estimatedTokens: number;\n};\n\nexport type CostMeterOptions = {\n\t/** Characters per token approximation. Default: 4 (GPT-family). */\n\tcharsPerToken?: number;\n\tname?: string;\n};\n\nconst costMeterEqual = (a: CostMeterReading, b: CostMeterReading): boolean => {\n\tif (a === b) return true;\n\treturn (\n\t\ta.chunkCount === b.chunkCount &&\n\t\ta.charCount === b.charCount &&\n\t\ta.estimatedTokens === b.estimatedTokens\n\t);\n};\n\n/**\n * Mounts a cost meter on a streaming topic. Counts chunks, characters, and\n * estimates token count. Compose with `budgetGate` for hard-stop when LLM\n * output exceeds budget mid-generation.\n *\n * Default structural equals suppresses DATA emission when two consecutive\n * readings are identical (same chunk count + char count + token estimate).\n */\nexport function costMeterExtractor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\topts?: CostMeterOptions,\n): Node<CostMeterReading> {\n\tconst charsPerToken = opts?.charsPerToken ?? 4;\n\treturn derived<CostMeterReading>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk]) => {\n\t\t\tif (chunk == null) return { chunkCount: 0, charCount: 0, estimatedTokens: 0 };\n\t\t\tconst c = chunk as StreamChunk;\n\t\t\tconst charCount = c.accumulated.length;\n\t\t\treturn {\n\t\t\t\tchunkCount: c.index + 1,\n\t\t\t\tcharCount,\n\t\t\t\testimatedTokens: Math.ceil(charCount / charsPerToken),\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ?? \"cost-meter\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: { chunkCount: 0, charCount: 0, estimatedTokens: 0 },\n\t\t\tmeta: aiMeta(\"cost_meter_extractor\"),\n\t\t\tequals: costMeterEqual,\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition B: Content safety pipeline\n// ---------------------------------------------------------------------------\n\n/** Options for {@link redactor}. */\nexport type RedactorOptions = {\n\tname?: string;\n};\n\n/**\n * Stream extractor that replaces matched patterns in the accumulated text.\n *\n * Returns a derived node emitting a sanitized `StreamChunk` on every chunk:\n * `accumulated` and `token` have matched substrings replaced by `replaceFn`.\n * The default `replaceFn` replaces with `\"[REDACTED]\"`.\n *\n * Compose with `contentGate` for in-flight safety pipelines.\n *\n * @param streamTopic - Streaming topic to monitor.\n * @param patterns - Array of RegExps to match against accumulated text.\n * @param replaceFn - Replacement producer (default: always `\"[REDACTED]\"`).\n */\nexport function redactor(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\tpatterns: RegExp[],\n\treplaceFn?: (match: string, pattern: RegExp) => string,\n\topts?: RedactorOptions,\n): Node<StreamChunk> {\n\tconst replace = replaceFn ?? (() => \"[REDACTED]\");\n\n\tfunction sanitize(text: string): string {\n\t\tlet result = text;\n\t\tfor (const pat of patterns) {\n\t\t\tconst global = pat.global ? pat : new RegExp(pat.source, `${pat.flags}g`);\n\t\t\tresult = result.replace(global, (m) => replace(m, pat));\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn derived<StreamChunk>(\n\t\t[streamTopic.latest as Node<StreamChunk | null>],\n\t\t([chunk]) => {\n\t\t\tif (chunk == null) {\n\t\t\t\treturn { source: \"\", token: \"\", accumulated: \"\", index: -1 };\n\t\t\t}\n\t\t\tconst c = chunk as StreamChunk;\n\t\t\tconst sanitizedAccumulated = sanitize(c.accumulated);\n\t\t\tconst sanitizedToken = sanitize(c.token);\n\t\t\treturn {\n\t\t\t\tsource: c.source,\n\t\t\t\ttoken: sanitizedToken,\n\t\t\t\taccumulated: sanitizedAccumulated,\n\t\t\t\tindex: c.index,\n\t\t\t};\n\t\t},\n\t\t{ name: opts?.name ?? \"redactor\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Content safety decision. */\nexport type ContentDecision = \"allow\" | \"block\" | \"review\";\n\n/** Options for {@link contentGate}. */\nexport type ContentGateOptions = {\n\t/**\n\t * Hard-block threshold multiplier (default 1.5).\n\t * Scores above `threshold * hardMultiplier` emit `\"block\"`.\n\t * Scores between `threshold` and that emit `\"review\"`.\n\t */\n\thardMultiplier?: number;\n\tname?: string;\n};\n\n/**\n * Derived node that classifies accumulated stream text as `\"allow\"`,\n * `\"review\"`, or `\"block\"` based on a classifier score.\n *\n * Emits a three-way decision on every new chunk:\n * - `\"allow\"` — score below `threshold`\n * - `\"review\"` — score in `[threshold, threshold × hardMultiplier)`\n * - `\"block\"` — score at or above `threshold × hardMultiplier`\n *\n * Wire the output into a `valve` (automatic) or `gate` (human approval).\n * This node does not itself control flow — it just classifies.\n *\n * @param streamTopic - Streaming topic to classify.\n * @param classifier - `(accumulated: string) => number` scoring function, or\n * a `Node<number>` for live scores.\n * @param threshold - Score at which output becomes \"review\" or \"block\".\n */\nexport function contentGate(\n\tstreamTopic: TopicGraph<StreamChunk>,\n\tclassifier: ((accumulated: string) => number) | Node<number>,\n\tthreshold: number,\n\topts?: ContentGateOptions,\n): Node<ContentDecision> {\n\tconst hardThreshold = threshold * (opts?.hardMultiplier ?? 1.5);\n\tconst isNodeClassifier = typeof classifier !== \"function\";\n\n\tconst deps: Node<unknown>[] = [streamTopic.latest as Node<StreamChunk | null>];\n\tif (isNodeClassifier) deps.push(classifier as Node<unknown>);\n\n\treturn derived<ContentDecision>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst chunk = values[0] as StreamChunk | undefined;\n\t\t\tif (chunk == null) return \"allow\";\n\n\t\t\tconst score = isNodeClassifier\n\t\t\t\t? ((values[1] as number | undefined) ?? 0)\n\t\t\t\t: (classifier as (text: string) => number)(chunk.accumulated);\n\n\t\t\tif (score >= hardThreshold) return \"block\";\n\t\t\tif (score >= threshold) return \"review\";\n\t\t\treturn \"allow\";\n\t\t},\n\t\t{ name: opts?.name ?? \"content-gate\", initial: \"allow\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// gatedStream\n// ---------------------------------------------------------------------------\n\nexport type GatedStreamOptions = StreamingPromptNodeOptions & {\n\t/** Gate options (maxPending, startOpen). */\n\tgate?: Omit<GateOptions, \"meta\">;\n};\n\n/**\n * Bundle returned by {@link gatedStream}.\n */\nexport type GatedStreamHandle<T> = {\n\t/** Final parsed result (after gate approval). */\n\toutput: Node<T | null>;\n\t/** Live stream topic — subscribe to `stream.latest` for chunks. */\n\tstream: TopicGraph<StreamChunk>;\n\t/** Gate controller — approve, reject (aborts in-flight stream), modify. */\n\tgate: GateController<T | null>;\n\t/** Tear down everything. */\n\tdispose: () => void;\n};\n\n/**\n * Streaming LLM transform with human-in-the-loop gate integration.\n *\n * Composes {@link streamingPromptNode} with {@link gate} so that:\n * - `gate.reject()` discards the pending value **and** aborts the in-flight\n * stream (cancels the `AbortController`).\n * - `gate.modify()` transforms the pending value before forwarding downstream.\n * - `gate.approve()` forwards the final result as normal.\n *\n * The abort-on-reject works by toggling an internal cancel signal that causes\n * the `switchMap` inside `streamingPromptNode` to restart with an empty message\n * list, which triggers the `AbortController.abort()` in the async generator's\n * `finally` block.\n */\nexport function gatedStream<T = string>(\n\tgraph: Graph,\n\tname: string,\n\tadapter: LLMAdapter,\n\tdeps: readonly Node<unknown>[],\n\tprompt: string | ((...depValues: unknown[]) => string),\n\topts?: GatedStreamOptions,\n): GatedStreamHandle<T> {\n\t// Cancel signal: toggling this forces switchMap to restart (aborting stream).\n\tconst cancelSignal = state<number>(0, { name: `${name}/cancel` });\n\tlet cancelCounter = 0;\n\n\t// Build the streaming prompt node with cancelSignal as an extra dep.\n\t// The cancel dep is excluded from prompt template arguments.\n\tconst allDeps = [...deps, cancelSignal] as readonly Node<unknown>[];\n\n\tconst sourceName = opts?.name ?? name;\n\tconst format = opts?.format ?? \"text\";\n\tconst streamTopic = topic<StreamChunk>(`${sourceName}/stream`);\n\n\tconst messagesNode = derived<readonly ChatMessage[]>(allDeps as Node<unknown>[], (values) => {\n\t\t// Last dep is the cancel signal — exclude from prompt args\n\t\tconst depValues = values.slice(0, -1);\n\t\tif (depValues.some((v) => v == null)) return [];\n\t\tconst text = typeof prompt === \"string\" ? prompt : prompt(...depValues);\n\t\tif (!text) return [];\n\t\tconst msgs: ChatMessage[] = [];\n\t\tif (opts?.systemPrompt) msgs.push({ role: \"system\", content: opts.systemPrompt });\n\t\tmsgs.push({ role: \"user\", content: text });\n\t\treturn msgs;\n\t});\n\n\tconst output = switchMap(messagesNode, (msgs) => {\n\t\tconst chatMsgs = msgs as readonly ChatMessage[];\n\t\tif (!chatMsgs || chatMsgs.length === 0) {\n\t\t\treturn state<T | null>(null) as NodeInput<T | null>;\n\t\t}\n\n\t\tconst ac = new AbortController();\n\n\t\tasync function* pumpAndCollect(): AsyncGenerator<T | null> {\n\t\t\tlet accumulated = \"\";\n\t\t\tlet index = 0;\n\t\t\ttry {\n\t\t\t\tfor await (const token of adapter.stream(chatMsgs, {\n\t\t\t\t\tmodel: opts?.model,\n\t\t\t\t\ttemperature: opts?.temperature,\n\t\t\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t\t\t\tsignal: ac.signal,\n\t\t\t\t})) {\n\t\t\t\t\taccumulated += token;\n\t\t\t\t\tstreamTopic.publish({\n\t\t\t\t\t\tsource: sourceName,\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\taccumulated,\n\t\t\t\t\t\tindex: index++,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tlet result: T | null;\n\t\t\t\tif (format === \"json\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = JSON.parse(stripFences(accumulated)) as T;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tresult = null;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tresult = accumulated as unknown as T;\n\t\t\t\t}\n\t\t\t\tyield result;\n\t\t\t} finally {\n\t\t\t\tac.abort();\n\t\t\t}\n\t\t}\n\n\t\treturn fromAny(pumpAndCollect());\n\t});\n\n\tconst unsub = keepalive(output);\n\n\t// Filter: only forward non-null results to the gate. Null is the switchMap\n\t// initial/cancel state — not a real LLM result worth gating. Returning\n\t// undefined from a derived fn means \"no auto-emit\" (spec §2.4), so null\n\t// values are silently suppressed.\n\tconst nonNullOutput = derived<T>(\n\t\t[output],\n\t\t([v]) => {\n\t\t\tif (v == null) return undefined;\n\t\t\treturn v as T;\n\t\t},\n\t\t{\n\t\t\tname: `${name}/filter`,\n\t\t},\n\t);\n\n\t// Register the filtered output so gate() can find it as a dep\n\tgraph.add(`${name}/raw`, nonNullOutput);\n\n\t// Wire gate on the output\n\tconst gateCtrl = gate<T | null>(graph, `${name}/gate`, `${name}/raw`, opts?.gate);\n\n\t// Wrap reject to also abort the in-flight stream\n\tconst originalReject = gateCtrl.reject.bind(gateCtrl);\n\tconst gateWithAbort: GateController<T | null> = {\n\t\t...gateCtrl,\n\t\treject(count = 1) {\n\t\t\toriginalReject(count);\n\t\t\t// Toggle cancel signal to force switchMap restart → abort\n\t\t\tcancelSignal.down([[DATA, ++cancelCounter]]);\n\t\t},\n\t};\n\n\treturn {\n\t\toutput: gateCtrl.node,\n\t\tstream: streamTopic,\n\t\tgate: gateWithAbort,\n\t\tdispose: () => {\n\t\t\tunsub();\n\t\t\tstreamTopic.destroy();\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// promptNode\n// ---------------------------------------------------------------------------\n\nexport type PromptNodeOptions = {\n\tname?: string;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Output format — `\"json\"` attempts JSON.parse on the response. Default: `\"text\"`. */\n\tformat?: \"text\" | \"json\";\n\t/** Number of retries on transient errors. Default: 0. */\n\tretries?: number;\n\t/** Cache LLM responses for identical inputs. Default: false. */\n\tcache?: boolean;\n\tsystemPrompt?: string;\n\tmeta?: Record<string, unknown>;\n};\n\n/** Extract text content from an LLM response, handling various response shapes. */\nfunction extractContent(resp: unknown): string {\n\tif (resp != null && typeof resp === \"object\" && \"content\" in resp) {\n\t\treturn String((resp as LLMResponse).content);\n\t}\n\tif (typeof resp === \"string\") return resp;\n\treturn String(resp);\n}\n\n/**\n * Universal LLM transform: wraps a prompt template + model adapter into a reactive derived node.\n * Re-invokes the LLM whenever any dep changes. Suitable for triage, QA, hypothesis, parity, etc.\n *\n * @param adapter - LLM adapter (provider-agnostic).\n * @param deps - Input nodes whose values feed the prompt.\n * @param prompt - Static string or template function receiving dep values.\n * @param opts - Optional configuration.\n * @returns `Node` emitting LLM responses (string or parsed JSON).\n */\nexport function promptNode<T = string>(\n\tadapter: LLMAdapter,\n\tdeps: readonly Node<unknown>[],\n\tprompt: string | ((...depValues: unknown[]) => string),\n\topts?: PromptNodeOptions,\n): Node<T | null> {\n\tconst format = opts?.format ?? \"text\";\n\tconst retries = opts?.retries ?? 0;\n\tconst useCache = opts?.cache ?? false;\n\tconst cache = useCache ? new Map<string, T>() : null;\n\n\t// Seed with `initial: []` so `switchMap` below fires with `[]` during the\n\t// initial activation pass and emits null (composition guide §8 — promptNode\n\t// gates on nullish deps). Dep-level null guarding is done inside the fn.\n\tconst messagesNode = derived<readonly ChatMessage[]>(\n\t\tdeps as Node<unknown>[],\n\t\t(values) => {\n\t\t\t// Dep-level null guard (composition guide §8): if any dep is\n\t\t\t// nullish, return empty messages → switchMap emits null.\n\t\t\tif (values.some((v) => v == null)) return [];\n\t\t\tconst text = typeof prompt === \"string\" ? prompt : prompt(...values);\n\t\t\tif (!text) return [];\n\t\t\tconst msgs: ChatMessage[] = [];\n\t\t\tif (opts?.systemPrompt) msgs.push({ role: \"system\", content: opts.systemPrompt });\n\t\t\tmsgs.push({ role: \"user\", content: text });\n\t\t\treturn msgs;\n\t\t},\n\t\t{\n\t\t\tname: opts?.name ? `${opts.name}::messages` : \"prompt_node::messages\",\n\t\t\tmeta: aiMeta(\"prompt_node\"),\n\t\t\tinitial: [] as readonly ChatMessage[],\n\t\t},\n\t);\n\n\tconst result = switchMap<readonly ChatMessage[], T | null>(messagesNode, (msgs) => {\n\t\tif (!msgs || msgs.length === 0) {\n\t\t\treturn state<T | null>(null) as NodeInput<T | null>;\n\t\t}\n\n\t\tconst cacheKey = useCache ? JSON.stringify(msgs.map((m) => [m.role, m.content])) : \"\";\n\t\tif (cache?.has(cacheKey)) {\n\t\t\treturn state<T | null>(cache.get(cacheKey)!) as NodeInput<T | null>;\n\t\t}\n\n\t\tasync function attempt(remaining: number): Promise<T | null> {\n\t\t\ttry {\n\t\t\t\tconst resp = await new Promise<LLMResponse>((resolve, reject) => {\n\t\t\t\t\tconst input = adapter.invoke(msgs, {\n\t\t\t\t\t\tmodel: opts?.model,\n\t\t\t\t\t\ttemperature: opts?.temperature,\n\t\t\t\t\t\tmaxTokens: opts?.maxTokens,\n\t\t\t\t\t\tsystemPrompt: opts?.systemPrompt,\n\t\t\t\t\t});\n\t\t\t\t\t// NodeInput may be a Node, Promise, or raw value\n\t\t\t\t\tif (input && typeof (input as PromiseLike<LLMResponse>).then === \"function\") {\n\t\t\t\t\t\t(input as PromiseLike<LLMResponse>).then(resolve, reject);\n\t\t\t\t\t} else if (input && typeof (input as Node<LLMResponse>).subscribe === \"function\") {\n\t\t\t\t\t\tresolve((input as Node<LLMResponse>).cache as LLMResponse);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(input as LLMResponse);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tconst content = extractContent(resp);\n\t\t\t\tlet parsed: T;\n\t\t\t\tif (format === \"json\") {\n\t\t\t\t\tparsed = JSON.parse(stripFences(content)) as T;\n\t\t\t\t} else {\n\t\t\t\t\tparsed = content as unknown as T;\n\t\t\t\t}\n\t\t\t\tcache?.set(cacheKey, parsed);\n\t\t\t\treturn parsed;\n\t\t\t} catch (err) {\n\t\t\t\tif (remaining > 0) return attempt(remaining - 1);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\treturn attempt(retries) as NodeInput<T | null>;\n\t});\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// chatStream\n// ---------------------------------------------------------------------------\n\nexport type ChatStreamOptions = {\n\tgraph?: GraphOptions;\n\tmaxMessages?: number;\n};\n\nexport class ChatStreamGraph extends Graph {\n\tprivate readonly _log: ReactiveLogBundle<ChatMessage>;\n\treadonly messages: Node<readonly ChatMessage[]>;\n\treadonly latest: Node<ChatMessage | null>;\n\treadonly messageCount: Node<number>;\n\n\tconstructor(name: string, opts: ChatStreamOptions = {}) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis._log = reactiveLog<ChatMessage>([], {\n\t\t\tname: \"messages\",\n\t\t\tmaxSize: opts.maxMessages,\n\t\t});\n\t\tthis.messages = this._log.entries;\n\t\tthis.add(\"messages\", this.messages);\n\n\t\tthis.latest = derived<ChatMessage | null>(\n\t\t\t[this.messages],\n\t\t\t([snapshot]) => {\n\t\t\t\tconst entries = snapshot as readonly ChatMessage[];\n\t\t\t\treturn entries.length === 0 ? null : (entries[entries.length - 1] as ChatMessage);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"latest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"chat_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"latest\", this.latest);\n\t\tthis.addDisposer(keepalive(this.latest));\n\n\t\tthis.messageCount = derived<number>(\n\t\t\t[this.messages],\n\t\t\t([snapshot]) => (snapshot as readonly ChatMessage[]).length,\n\t\t\t{\n\t\t\t\tname: \"messageCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"chat_message_count\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"messageCount\", this.messageCount);\n\t\tthis.addDisposer(keepalive(this.messageCount));\n\t}\n\n\tappend(role: ChatMessage[\"role\"], content: string, extra?: Partial<ChatMessage>): void {\n\t\tthis._log.append({ role, content, ...extra });\n\t}\n\n\tappendToolResult(callId: string, content: string): void {\n\t\tthis._log.append({ role: \"tool\", content, toolCallId: callId });\n\t}\n\n\tclear(): void {\n\t\tthis._log.clear();\n\t}\n\n\tallMessages(): readonly ChatMessage[] {\n\t\treturn this.messages.cache as readonly ChatMessage[];\n\t}\n}\n\nexport function chatStream(name: string, opts?: ChatStreamOptions): ChatStreamGraph {\n\treturn new ChatStreamGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// toolRegistry\n// ---------------------------------------------------------------------------\n\nexport type ToolRegistryOptions = {\n\tgraph?: GraphOptions;\n};\n\nexport class ToolRegistryGraph extends Graph {\n\treadonly definitions: Node<ReadonlyMap<string, ToolDefinition>>;\n\treadonly schemas: Node<readonly ToolDefinition[]>;\n\n\tconstructor(name: string, opts: ToolRegistryOptions = {}) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis.definitions = state<ReadonlyMap<string, ToolDefinition>>(new Map(), {\n\t\t\tname: \"definitions\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"tool_definitions\"),\n\t\t});\n\t\tthis.add(\"definitions\", this.definitions);\n\n\t\tthis.schemas = derived<readonly ToolDefinition[]>(\n\t\t\t[this.definitions],\n\t\t\t([defs]) => [...((defs ?? new Map()) as ReadonlyMap<string, ToolDefinition>).values()],\n\t\t\t{\n\t\t\t\tname: \"schemas\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: aiMeta(\"tool_schemas\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tthis.add(\"schemas\", this.schemas);\n\t\tthis.addDisposer(keepalive(this.schemas));\n\t}\n\n\tregister(tool: ToolDefinition): void {\n\t\tconst current = this.definitions.cache as ReadonlyMap<string, ToolDefinition>;\n\t\tconst next = new Map(current);\n\t\tnext.set(tool.name, tool);\n\t\tthis.definitions.down([[DATA, next]]);\n\t}\n\n\tunregister(name: string): void {\n\t\tconst current = this.definitions.cache as ReadonlyMap<string, ToolDefinition>;\n\t\tif (!current.has(name)) return;\n\t\tconst next = new Map(current);\n\t\tnext.delete(name);\n\t\tthis.definitions.down([[DATA, next]]);\n\t}\n\n\tasync execute(name: string, args: Record<string, unknown>): Promise<unknown> {\n\t\tconst defs = this.definitions.cache as ReadonlyMap<string, ToolDefinition>;\n\t\tconst tool = defs.get(name);\n\t\tif (!tool) throw new Error(`toolRegistry: unknown tool \"${name}\"`);\n\t\tconst raw = tool.handler(args);\n\t\treturn resolveToolHandlerResult(raw);\n\t}\n\n\tgetDefinition(name: string): ToolDefinition | undefined {\n\t\treturn (this.definitions.cache as ReadonlyMap<string, ToolDefinition>)?.get(name);\n\t}\n}\n\nexport function toolRegistry(name: string, opts?: ToolRegistryOptions): ToolRegistryGraph {\n\treturn new ToolRegistryGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// systemPromptBuilder\n// ---------------------------------------------------------------------------\n\n/**\n * Assembles a system prompt from reactive sections. Each section is a\n * `NodeInput<string>` — the prompt updates when any section changes.\n */\nexport type SystemPromptHandle = Node<string> & { dispose: () => void };\n\nexport function systemPromptBuilder(\n\tsections: readonly NodeInput<string>[],\n\topts?: { separator?: string; name?: string },\n): SystemPromptHandle {\n\tconst separator = opts?.separator ?? \"\\n\\n\";\n\tconst sectionNodes = sections.map((s) => (typeof s === \"string\" ? state(s) : fromAny(s)));\n\tconst prompt = derived(\n\t\tsectionNodes,\n\t\t(values) => (values as string[]).filter((v) => v != null && v !== \"\").join(separator),\n\t\t{\n\t\t\tname: opts?.name ?? \"systemPrompt\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: aiMeta(\"system_prompt\"),\n\t\t\tinitial: \"\",\n\t\t},\n\t);\n\tconst unsub = keepalive(prompt);\n\treturn Object.assign(prompt, { dispose: unsub });\n}\n\n// ---------------------------------------------------------------------------\n// llmExtractor / llmConsolidator\n// ---------------------------------------------------------------------------\n\nexport type LLMExtractorOptions = {\n\tadapter: LLMAdapter;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n};\n\n/**\n * Returns an `extractFn` callback for `distill()` that invokes an LLM to\n * extract structured memories from raw input.\n *\n * The system prompt should instruct the LLM to return JSON matching\n * `Extraction<TMem>` shape: `{ upsert: [{ key, value }], remove?: [key] }`.\n */\nexport function llmExtractor<TRaw, TMem>(\n\tsystemPrompt: string,\n\topts: LLMExtractorOptions,\n): (raw: TRaw, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>> {\n\treturn (raw: TRaw, existing: ReadonlyMap<string, TMem>) => {\n\t\tconst existingKeys = [...existing.keys()].slice(0, 100); // sample for dedup\n\t\tconst messages: ChatMessage[] = [\n\t\t\t{ role: \"system\", content: systemPrompt },\n\t\t\t{\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: JSON.stringify({\n\t\t\t\t\tinput: raw,\n\t\t\t\t\texistingKeys,\n\t\t\t\t}),\n\t\t\t},\n\t\t];\n\t\t// Wrap the adapter call in a producer that parses the JSON response\n\t\treturn producer<Extraction<TMem>>((actions) => {\n\t\t\tlet active = true;\n\t\t\tconst result = opts.adapter.invoke(messages, {\n\t\t\t\tmodel: opts.model,\n\t\t\t\ttemperature: opts.temperature ?? 0,\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t});\n\t\t\t// result is NodeInput — could be a Promise, Node, etc.\n\t\t\tconst resolved = fromAny(result);\n\t\t\tconst unsub = resolved.subscribe((msgs) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tlet done = false;\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst response = msg[1] as LLMResponse;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst parsed = JSON.parse(response.content) as Extraction<TMem>;\n\t\t\t\t\t\t\tactions.emit(parsed);\n\t\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tactions.down([\n\t\t\t\t\t\t\t\t[ERROR, new Error(\"llmExtractor: failed to parse LLM response as JSON\")],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tactions.down([[ERROR, msg[1]]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Forward unknown message types (spec §1.3.6)\n\t\t\t\t\t\tactions.down([[msg[0], msg[1]]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tactive = false;\n\t\t\t};\n\t\t});\n\t};\n}\n\nexport type LLMConsolidatorOptions = LLMExtractorOptions;\n\n/**\n * Returns a `consolidateFn` callback for `distill()` that invokes an LLM to\n * cluster and merge related memories.\n */\nexport function llmConsolidator<TMem>(\n\tsystemPrompt: string,\n\topts: LLMConsolidatorOptions,\n): (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>> {\n\treturn (entries: ReadonlyMap<string, TMem>) => {\n\t\tconst entriesArray = [...entries.entries()].map(([key, value]) => ({ key, value }));\n\t\tconst messages: ChatMessage[] = [\n\t\t\t{ role: \"system\", content: systemPrompt },\n\t\t\t{ role: \"user\", content: JSON.stringify({ memories: entriesArray }) },\n\t\t];\n\t\treturn producer<Extraction<TMem>>((actions) => {\n\t\t\tlet active = true;\n\t\t\tconst result = opts.adapter.invoke(messages, {\n\t\t\t\tmodel: opts.model,\n\t\t\t\ttemperature: opts.temperature ?? 0,\n\t\t\t\tmaxTokens: opts.maxTokens,\n\t\t\t});\n\t\t\tconst resolved = fromAny(result);\n\t\t\tconst unsub = resolved.subscribe((msgs) => {\n\t\t\t\tif (!active) return;\n\t\t\t\tlet done = false;\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst response = msg[1] as LLMResponse;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst parsed = JSON.parse(response.content) as Extraction<TMem>;\n\t\t\t\t\t\t\tactions.emit(parsed);\n\t\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tactions.down([\n\t\t\t\t\t\t\t\t[ERROR, new Error(\"llmConsolidator: failed to parse LLM response as JSON\")],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tactions.down([[ERROR, msg[1]]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Forward unknown message types (spec §1.3.6)\n\t\t\t\t\t\tactions.down([[msg[0], msg[1]]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tactive = false;\n\t\t\t};\n\t\t});\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// 3D Admission Scoring\n// ---------------------------------------------------------------------------\n\n/** Scores for the three admission dimensions. Each 0–1. */\nexport type AdmissionScores = {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n};\n\nexport type AdmissionScore3DOptions = {\n\t/** Custom scoring function. Default: rule-based (all dimensions 0.5). */\n\tscoreFn?: (raw: unknown) => AdmissionScores;\n\t/** Minimum persistence score to admit (default 0.3). */\n\tpersistenceThreshold?: number;\n\t/** Minimum personalValue score to admit (default 0.3). */\n\tpersonalValueThreshold?: number;\n\t/** Require structure score > 0 to admit (default false). */\n\trequireStructured?: boolean;\n};\n\n/**\n * Default 3D admission scorer. Returns middle scores for all dimensions.\n * Override with `scoreFn` for LLM-backed or domain-specific scoring.\n */\nfunction defaultAdmissionScorer(_raw: unknown): AdmissionScores {\n\treturn { persistence: 0.5, structure: 0.5, personalValue: 0.5 };\n}\n\n/**\n * Creates a 3D admission filter function compatible with `agentMemory`'s\n * `admissionFilter` option. Scores each candidate on persistence, structure,\n * and personalValue, then applies thresholds.\n */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions = {}): (raw: unknown) => boolean {\n\tconst scoreFn = opts.scoreFn ?? defaultAdmissionScorer;\n\tconst pThresh = opts.persistenceThreshold ?? 0.3;\n\tconst pvThresh = opts.personalValueThreshold ?? 0.3;\n\tconst reqStructured = opts.requireStructured ?? false;\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = scoreFn(raw);\n\t\tif (scores.persistence < pThresh) return false;\n\t\tif (scores.personalValue < pvThresh) return false;\n\t\tif (reqStructured && scores.structure <= 0) return false;\n\t\treturn true;\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Memory Tiers\n// ---------------------------------------------------------------------------\n\nexport type MemoryTier = \"permanent\" | \"active\" | \"archived\";\n\nexport type MemoryTiersOptions<TMem> = {\n\t/** Exponential decay rate per second for active tier.\n\t * Default: 7-day half-life ≈ ln(2)/(7×86400) ≈ 0.00000114. */\n\tdecayRate?: number;\n\t/** Max entries in the active tier before archiving lowest-scored (default 1000). */\n\tmaxActive?: number;\n\t/** Score threshold below which active entries get archived (default 0.1). */\n\tarchiveThreshold?: number;\n\t/** Predicate: true → entry belongs in permanent tier (default: never). */\n\tpermanentFilter?: (key: string, mem: TMem) => boolean;\n\t/** Storage tier for the archive. Omit to disable archiving. */\n\tarchiveTier?: StorageTier;\n\t/** Options forwarded to `graph.attachStorage` for the archive tier. */\n\tarchiveStorageOptions?: GraphAttachStorageOptions;\n};\n\nconst DEFAULT_DECAY_RATE = Math.LN2 / (7 * 86_400); // 7-day half-life\n\nexport type MemoryTiersBundle<TMem> = {\n\t/** Permanent tier: never evicted. */\n\treadonly permanent: LightCollectionBundle<TMem>;\n\t/** Active entries node (reactive, holds ReadonlyMap). */\n\treadonly activeEntries: Node<unknown>;\n\t/** Archive storage handle (null if no tier configured). */\n\treadonly archiveHandle: StorageHandle | null;\n\t/** Classify a key into its current tier. */\n\ttierOf: (key: string) => MemoryTier;\n\t/** Move a key to the permanent tier. */\n\tmarkPermanent: (key: string, value: TMem) => void;\n};\n\n// ---------------------------------------------------------------------------\n// Retrieval Pipeline\n// ---------------------------------------------------------------------------\n\nexport type RetrievalQuery = {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n};\n\nexport type RetrievalPipelineOptions<TMem> = {\n\t/** Max candidates from vector search (default 20). */\n\ttopK?: number;\n\t/** KG expansion depth in hops (default 1). */\n\tgraphDepth?: number;\n\t/** Token budget for final packing (default 2000). */\n\tbudget?: number;\n\t/** Cost function for budget packing. */\n\tcost: (mem: TMem) => number;\n\t/** Score function for ranking. */\n\tscore: (mem: TMem, context: unknown) => number;\n};\n\n/** A single entry in the retrieval result, with causal trace metadata. */\nexport type RetrievalEntry<TMem> = {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n};\n\n/** Causal trace for a retrieval run. */\nexport type RetrievalTrace<TMem> = {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n};\n\n// ---------------------------------------------------------------------------\n// agentMemory\n// ---------------------------------------------------------------------------\n\nexport type AgentMemoryOptions<TMem = unknown> = {\n\tgraph?: GraphOptions;\n\t/** LLM adapter for extraction and consolidation. */\n\tadapter?: LLMAdapter;\n\t/** System prompt for the extractor LLM. */\n\textractPrompt?: string;\n\t/** Custom extractFn (overrides adapter + extractPrompt). */\n\textractFn?: (raw: unknown, existing: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;\n\t/** System prompt for the consolidation LLM. */\n\tconsolidatePrompt?: string;\n\t/** Custom consolidateFn (overrides adapter + consolidatePrompt). */\n\tconsolidateFn?: (entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>;\n\t/** Reactive trigger for consolidation (caller supplies e.g. `fromTimer`). */\n\tconsolidateTrigger?: NodeInput<unknown>;\n\t/** Score function for budget packing (required). */\n\tscore: (mem: TMem, context: unknown) => number;\n\t/** Cost function for budget packing (required). */\n\tcost: (mem: TMem) => number;\n\t/** Token budget for compact view (default 2000). */\n\tbudget?: number;\n\t/** Context node for scoring. */\n\tcontext?: NodeInput<unknown>;\n\t/** Admission filter (default: admit all). */\n\tadmissionFilter?: (candidate: unknown) => boolean;\n\t/** Vector index dimensions (> 0 enables vector index for retrieval). */\n\tvectorDimensions?: number;\n\n\t// --- In-factory composition (new) ---\n\n\t/** Extract embedding vector from a memory entry (enables vector index). */\n\tembedFn?: (mem: TMem) => readonly number[] | undefined;\n\t/** Enable knowledge graph for entity/relation tracking. */\n\tenableKnowledgeGraph?: boolean;\n\t/** Extract entities and relations from a memory entry. */\n\tentityFn?: (\n\t\tkey: string,\n\t\tmem: TMem,\n\t) =>\n\t\t| {\n\t\t\t\tentities?: Array<{ id: string; value: unknown }>;\n\t\t\t\trelations?: Array<{ from: string; to: string; relation: string; weight?: number }>;\n\t\t }\n\t\t| undefined;\n\n\t/** 3-tier storage configuration. Omit to use single-tier (existing behavior). */\n\ttiers?: MemoryTiersOptions<TMem>;\n\n\t/** Retrieval pipeline configuration. Requires vector index or knowledge graph. */\n\tretrieval?: {\n\t\t/** Max candidates from vector search (default 20). */\n\t\ttopK?: number;\n\t\t/** KG expansion depth in hops (default 1). */\n\t\tgraphDepth?: number;\n\t};\n\n\t/** Periodic reflection/consolidation configuration. */\n\treflection?: {\n\t\t/** Interval in ms between consolidation runs (default 300_000 = 5 min). */\n\t\tinterval?: number;\n\t\t/** Enable/disable periodic reflection (default true when consolidateFn is available). */\n\t\tenabled?: boolean;\n\t};\n};\n\nexport type AgentMemoryGraph<TMem = unknown> = Graph & {\n\treadonly distillBundle: DistillBundle<TMem>;\n\treadonly compact: Node<Array<{ key: string; value: TMem; score: number }>>;\n\treadonly size: Node<number>;\n\t/** Vector index bundle (null if not enabled). */\n\treadonly vectors: VectorIndexBundle<TMem> | null;\n\t/** Knowledge graph (null if not enabled). */\n\treadonly kg: KnowledgeGraphGraph<unknown, string> | null;\n\t/** Memory tiers bundle (null if not configured). */\n\treadonly memoryTiers: MemoryTiersBundle<TMem> | null;\n\t/** Retrieval result node (null if no retrieval pipeline configured). */\n\treadonly retrieval: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null;\n\t/** Latest retrieval trace for observability (null if no retrieval pipeline). */\n\treadonly retrievalTrace: Node<RetrievalTrace<TMem> | null> | null;\n\t/**\n\t * Execute a retrieval query (null if no retrieval pipeline).\n\t *\n\t * **Synchronous consumer API** — returns the result immediately and batch-writes\n\t * `retrieval` and `retrievalTrace` state nodes for observers. Reads the store\n\t * snapshot and context value **at call time** (external-boundary read).\n\t *\n\t * **Do not call from inside a reactive fn body** (derived fn, subscribe callback,\n\t * effect body). The cache reads would become transitive protocol violations and\n\t * may observe wave-progressive rather than wave-final state.\n\t *\n\t * **Caller-batch caveat:** if invoked inside a caller's `batch(() => ...)` alongside\n\t * upstream store mutations, the store snapshot reflects what has been committed to\n\t * `store.entries.cache` at call time. State-backed stores update cache synchronously\n\t * so batched inserts are visible; derived-backed store transforms may defer. If you\n\t * need fresh state after batched mutations, call `retrieve` after the batch returns.\n\t */\n\treadonly retrieve: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null;\n};\n\n/**\n * Pre-wired agentic memory graph. Composes `distill()` with optional\n * `knowledgeGraph()`, `vectorIndex()`, `lightCollection()` (permanent tier),\n * `decay()`, and `attachStorage()` (archive tier). Supports 3D admission\n * scoring, a default retrieval pipeline, periodic reflection, and\n * retrieval observability traces.\n */\n\n/** Extract the key→value map from a reactive_map snapshot. */\nfunction extractStoreMap<TMem>(snapshot: unknown): ReadonlyMap<string, TMem> {\n\tif (snapshot instanceof Map) return snapshot as ReadonlyMap<string, TMem>;\n\treturn new Map<string, TMem>();\n}\n\nexport function agentMemory<TMem = unknown>(\n\tname: string,\n\tsource: NodeInput<unknown>,\n\topts: AgentMemoryOptions<TMem>,\n): AgentMemoryGraph<TMem> {\n\tconst graph = new Graph(name, opts.graph);\n\tconst keepaliveSubs: Array<() => void> = [];\n\n\t// --- Extract function resolution ---\n\tlet rawExtractFn: (\n\t\traw: unknown,\n\t\texisting: ReadonlyMap<string, TMem>,\n\t) => NodeInput<Extraction<TMem>>;\n\tif (opts.extractFn) {\n\t\trawExtractFn = opts.extractFn;\n\t} else if (opts.adapter && opts.extractPrompt) {\n\t\trawExtractFn = llmExtractor<unknown, TMem>(opts.extractPrompt, { adapter: opts.adapter });\n\t} else {\n\t\tthrow new Error(\"agentMemory: provide either extractFn or adapter + extractPrompt\");\n\t}\n\tconst extractFn = (\n\t\traw: unknown,\n\t\texisting: ReadonlyMap<string, TMem>,\n\t): NodeInput<Extraction<TMem>> => {\n\t\tif (raw == null) return { upsert: [] };\n\t\treturn rawExtractFn(raw, existing);\n\t};\n\n\t// --- Admission filter ---\n\tlet filteredSource = source;\n\tif (opts.admissionFilter) {\n\t\tconst srcNode = fromAny(source);\n\t\tconst filter = opts.admissionFilter;\n\t\tfilteredSource = derived(\n\t\t\t[srcNode],\n\t\t\t([raw]) => {\n\t\t\t\tif (filter(raw)) return raw;\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{ name: \"admissionFilter\", describeKind: \"derived\" },\n\t\t);\n\t}\n\n\t// --- Consolidation ---\n\tlet consolidateFn:\n\t\t| ((entries: ReadonlyMap<string, TMem>) => NodeInput<Extraction<TMem>>)\n\t\t| undefined;\n\tif (opts.consolidateFn) {\n\t\tconsolidateFn = opts.consolidateFn;\n\t} else if (opts.adapter && opts.consolidatePrompt) {\n\t\tconsolidateFn = llmConsolidator<TMem>(opts.consolidatePrompt, { adapter: opts.adapter });\n\t}\n\n\t// --- Reflection: default consolidateTrigger from fromTimer ---\n\tlet consolidateTrigger = opts.consolidateTrigger;\n\tif (!consolidateTrigger && consolidateFn && opts.reflection?.enabled !== false) {\n\t\tconst interval = opts.reflection?.interval ?? 300_000;\n\t\tconsolidateTrigger = fromTimer(interval, { period: interval });\n\t}\n\n\t// --- Build distill bundle ---\n\tconst distillOpts: DistillOptions<TMem> = {\n\t\tscore: opts.score,\n\t\tcost: opts.cost,\n\t\tbudget: opts.budget ?? 2000,\n\t\tcontext: opts.context,\n\t\tconsolidate: consolidateFn,\n\t\tconsolidateTrigger,\n\t};\n\tconst distillBundle = distill<unknown, TMem>(filteredSource, extractFn, distillOpts);\n\n\tgraph.add(\"store\", distillBundle.store.entries);\n\tgraph.add(\"compact\", distillBundle.compact);\n\tgraph.add(\"size\", distillBundle.size);\n\n\t// --- Vector index (optional) ---\n\tlet vectors: VectorIndexBundle<TMem> | null = null;\n\tif (opts.vectorDimensions && opts.vectorDimensions > 0 && opts.embedFn) {\n\t\tvectors = vectorIndex<TMem>({ dimension: opts.vectorDimensions });\n\t\tgraph.add(\"vectorIndex\", vectors.entries);\n\t}\n\n\t// --- Knowledge graph (optional) ---\n\tlet kg: KnowledgeGraphGraph<unknown, string> | null = null;\n\tif (opts.enableKnowledgeGraph) {\n\t\tkg = knowledgeGraph<unknown, string>(`${name}-kg`);\n\t\tgraph.mount(\"kg\", kg);\n\t}\n\n\t// --- 3-tier storage (optional) ---\n\tlet memoryTiersBundle: MemoryTiersBundle<TMem> | null = null;\n\tif (opts.tiers) {\n\t\tconst tiersOpts = opts.tiers;\n\t\tconst decayRate = tiersOpts.decayRate ?? DEFAULT_DECAY_RATE;\n\t\tconst maxActive = tiersOpts.maxActive ?? 1000;\n\t\tconst archiveThreshold = tiersOpts.archiveThreshold ?? 0.1;\n\t\tconst permanentFilter = tiersOpts.permanentFilter ?? (() => false);\n\n\t\t// Permanent tier\n\t\tconst permanent = lightCollection<TMem>({ name: \"permanent\" });\n\t\tgraph.add(\"permanent\", permanent.entries);\n\n\t\t// Track which keys are permanent\n\t\tconst permanentKeys = new Set<string>();\n\n\t\tconst tierOf = (key: string): MemoryTier => {\n\t\t\tif (permanentKeys.has(key)) return \"permanent\";\n\t\t\tconst storeMap = extractStoreMap<TMem>(distillBundle.store.entries.cache);\n\t\t\tif (storeMap.has(key)) return \"active\";\n\t\t\treturn \"archived\";\n\t\t};\n\n\t\tconst markPermanent = (key: string, value: TMem): void => {\n\t\t\tpermanentKeys.add(key);\n\t\t\tpermanent.upsert(key, value);\n\t\t};\n\n\t\t// Track entry creation times for accurate decay age calculation\n\t\tconst entryCreatedAtNs = new Map<string, number>();\n\n\t\t// Post-extraction hook: classify into tiers and archive low-scored entries\n\t\tconst storeNode = distillBundle.store.entries;\n\t\tconst contextNode = opts.context ? fromAny(opts.context) : state<unknown>(null);\n\t\tconst tierClassifier = effect([storeNode, contextNode], ([snapshot, ctx]) => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(snapshot);\n\t\t\tconst nowNs = monotonicNs();\n\t\t\tconst toArchive: string[] = [];\n\t\t\tconst toPermanent: Array<{ key: string; value: TMem }> = [];\n\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\t// Track creation time for new entries\n\t\t\t\tif (!entryCreatedAtNs.has(key)) {\n\t\t\t\t\tentryCreatedAtNs.set(key, nowNs);\n\t\t\t\t}\n\n\t\t\t\t// Check permanent classification\n\t\t\t\tif (permanentFilter(key, mem)) {\n\t\t\t\t\ttoPermanent.push({ key, value: mem });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Compute decayed score for active tier\n\t\t\t\tconst baseScore = opts.score(mem, ctx);\n\t\t\t\tconst createdNs = entryCreatedAtNs.get(key) ?? nowNs;\n\t\t\t\tconst ageSeconds = Number(nowNs - createdNs) / 1e9;\n\t\t\t\tconst decayed = decay(baseScore, ageSeconds, decayRate);\n\t\t\t\tif (decayed < archiveThreshold) {\n\t\t\t\t\ttoArchive.push(key);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Clean up creation times for removed entries\n\t\t\tfor (const key of entryCreatedAtNs.keys()) {\n\t\t\t\tif (!storeMap.has(key)) entryCreatedAtNs.delete(key);\n\t\t\t}\n\n\t\t\t// Move to permanent\n\t\t\tfor (const { key, value } of toPermanent) {\n\t\t\t\tif (!permanentKeys.has(key)) {\n\t\t\t\t\tmarkPermanent(key, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Archive and evict from active (respect maxActive, excluding permanent keys)\n\t\t\tconst activeCount = storeMap.size - permanentKeys.size;\n\t\t\tif (activeCount > maxActive) {\n\t\t\t\tconst scored = [...storeMap.entries()]\n\t\t\t\t\t.filter(([k]) => !permanentKeys.has(k))\n\t\t\t\t\t.map(([k, m]) => ({ key: k, score: opts.score(m, ctx) }))\n\t\t\t\t\t.sort((a, b) => a.score - b.score);\n\t\t\t\tconst excess = activeCount - maxActive;\n\t\t\t\tfor (let i = 0; i < excess && i < scored.length; i++) {\n\t\t\t\t\tconst sk = scored[i]!.key;\n\t\t\t\t\tif (!toArchive.includes(sk)) toArchive.push(sk);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Evict archived keys from active store\n\t\t\tif (toArchive.length > 0) {\n\t\t\t\tbatch(() => {\n\t\t\t\t\tfor (const key of toArchive) {\n\t\t\t\t\t\tdistillBundle.store.delete(key);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\tkeepaliveSubs.push(tierClassifier.subscribe(() => undefined));\n\n\t\t// Archive checkpoint\n\t\tlet archiveHandle: StorageHandle | null = null;\n\t\tif (tiersOpts.archiveTier) {\n\t\t\tarchiveHandle = graph.attachStorage(\n\t\t\t\t[tiersOpts.archiveTier],\n\t\t\t\ttiersOpts.archiveStorageOptions ?? {},\n\t\t\t);\n\t\t}\n\n\t\tmemoryTiersBundle = {\n\t\t\tpermanent,\n\t\t\tactiveEntries: storeNode,\n\t\t\tarchiveHandle,\n\t\t\ttierOf,\n\t\t\tmarkPermanent,\n\t\t};\n\t}\n\n\t// --- Post-extraction hooks: vector + KG indexing ---\n\tif (vectors || kg) {\n\t\tconst embedFn = opts.embedFn;\n\t\tconst entityFn = opts.entityFn;\n\t\tconst storeNode = distillBundle.store.entries;\n\n\t\tconst indexer = effect([storeNode], ([snapshot]) => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(snapshot);\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\t// Vector indexing\n\t\t\t\tif (vectors && embedFn) {\n\t\t\t\t\tconst vec = embedFn(mem);\n\t\t\t\t\tif (vec) vectors.upsert(key, vec, mem);\n\t\t\t\t}\n\t\t\t\t// Knowledge graph entity/relation extraction\n\t\t\t\tif (kg && entityFn) {\n\t\t\t\t\tconst extracted = entityFn(key, mem);\n\t\t\t\t\tif (extracted) {\n\t\t\t\t\t\tfor (const ent of extracted.entities ?? []) {\n\t\t\t\t\t\t\tkg.upsertEntity(ent.id, ent.value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const rel of extracted.relations ?? []) {\n\t\t\t\t\t\t\tkg.link(rel.from, rel.to, rel.relation as string, rel.weight);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tkeepaliveSubs.push(indexer.subscribe(() => undefined));\n\t}\n\n\t// --- Retrieval pipeline (optional) ---\n\tlet retrievalNode: Node<ReadonlyArray<RetrievalEntry<TMem>>> | null = null;\n\tlet retrievalTraceNode: Node<RetrievalTrace<TMem> | null> | null = null;\n\tlet retrieveFn: ((query: RetrievalQuery) => ReadonlyArray<RetrievalEntry<TMem>>) | null = null;\n\n\tif (vectors || kg) {\n\t\tconst topK = opts.retrieval?.topK ?? 20;\n\t\tconst graphDepth = opts.retrieval?.graphDepth ?? 1;\n\t\tconst budget = opts.budget ?? 2000;\n\t\tconst costFn = opts.cost;\n\t\tconst scoreFn = opts.score;\n\n\t\tconst contextNode = opts.context ? fromAny(opts.context) : state<unknown>(null);\n\n\t\t// Observer-facing state nodes. `retrieve()` writes both in a batch on every call.\n\t\t// (Option W from the 2026-04-12 P3 audit — retrieveFn is a sync consumer API that\n\t\t// reads store/context at call time, computes inline, and publishes results via\n\t\t// state writes. No derived, no queryInput, no closure side-channel.)\n\t\tconst retrievalOutput = state<ReadonlyArray<RetrievalEntry<TMem>>>([], {\n\t\t\tname: \"retrieval\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"retrieval_pipeline\"),\n\t\t});\n\t\tgraph.add(\"retrieval\", retrievalOutput);\n\t\tretrievalNode = retrievalOutput;\n\n\t\tconst traceState = state<RetrievalTrace<TMem> | null>(null, {\n\t\t\tname: \"retrievalTrace\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"retrieval_trace\"),\n\t\t});\n\t\tgraph.add(\"retrievalTrace\", traceState);\n\t\tretrievalTraceNode = traceState;\n\n\t\t// Sync consumer API. Reads `store.entries.cache` and `contextNode.cache` at\n\t\t// call time — these are external-boundary reads, allowed per the foundation\n\t\t// redesign. **Do not call from inside a reactive fn body**: the cache reads\n\t\t// would become transitive P3 violations.\n\t\tretrieveFn = (query: RetrievalQuery): ReadonlyArray<RetrievalEntry<TMem>> => {\n\t\t\tconst storeMap = extractStoreMap<TMem>(distillBundle.store.entries.cache);\n\t\t\tconst ctx = contextNode.cache;\n\n\t\t\tconst candidateMap = new Map<\n\t\t\t\tstring,\n\t\t\t\t{ value: TMem; sources: Set<\"vector\" | \"graph\" | \"store\"> }\n\t\t\t>();\n\n\t\t\t// Stage 1: Vector search\n\t\t\tlet vectorCandidates: VectorSearchResult<TMem>[] = [];\n\t\t\tif (vectors && query.vector) {\n\t\t\t\tvectorCandidates = vectors.search(query.vector, topK) as VectorSearchResult<TMem>[];\n\t\t\t\tfor (const vc of vectorCandidates) {\n\t\t\t\t\tconst mem = storeMap.get(vc.id);\n\t\t\t\t\tif (mem) {\n\t\t\t\t\t\tcandidateMap.set(vc.id, { value: mem, sources: new Set([\"vector\"]) });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Stage 2: KG expansion\n\t\t\tconst graphExpanded: string[] = [];\n\t\t\tif (kg) {\n\t\t\t\tconst seedIds = [...(query.entityIds ?? []), ...[...candidateMap.keys()]];\n\t\t\t\tconst visited = new Set<string>();\n\t\t\t\tlet frontier = seedIds;\n\t\t\t\tfor (let depth = 0; depth < graphDepth; depth++) {\n\t\t\t\t\tconst nextFrontier: string[] = [];\n\t\t\t\t\tfor (const id of frontier) {\n\t\t\t\t\t\tif (visited.has(id)) continue;\n\t\t\t\t\t\tvisited.add(id);\n\t\t\t\t\t\tconst related = kg.related(id);\n\t\t\t\t\t\tfor (const edge of related) {\n\t\t\t\t\t\t\tconst targetId = edge.to;\n\t\t\t\t\t\t\tif (!visited.has(targetId)) {\n\t\t\t\t\t\t\t\tnextFrontier.push(targetId);\n\t\t\t\t\t\t\t\tconst mem = storeMap.get(targetId);\n\t\t\t\t\t\t\t\tif (mem) {\n\t\t\t\t\t\t\t\t\tconst existing = candidateMap.get(targetId);\n\t\t\t\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\t\t\t\texisting.sources.add(\"graph\");\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tcandidateMap.set(targetId, { value: mem, sources: new Set([\"graph\"]) });\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tgraphExpanded.push(targetId);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfrontier = nextFrontier;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Also include direct store matches not yet in candidates\n\t\t\tfor (const [key, mem] of storeMap) {\n\t\t\t\tif (!candidateMap.has(key)) {\n\t\t\t\t\tcandidateMap.set(key, { value: mem, sources: new Set([\"store\"]) });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Stage 3: Score and rank\n\t\t\tconst ranked: RetrievalEntry<TMem>[] = [];\n\t\t\tfor (const [key, { value, sources }] of candidateMap) {\n\t\t\t\tconst score = scoreFn(value, ctx);\n\t\t\t\tranked.push({ key, value, score, sources: [...sources] });\n\t\t\t}\n\t\t\tranked.sort((a, b) => b.score - a.score);\n\n\t\t\t// Stage 4: Budget packing\n\t\t\tconst packed: RetrievalEntry<TMem>[] = [];\n\t\t\tlet usedBudget = 0;\n\t\t\tfor (const entry of ranked) {\n\t\t\t\tconst c = costFn(entry.value);\n\t\t\t\tif (usedBudget + c > budget && packed.length > 0) break;\n\t\t\t\tpacked.push(entry);\n\t\t\t\tusedBudget += c;\n\t\t\t}\n\n\t\t\tconst trace: RetrievalTrace<TMem> = {\n\t\t\t\tvectorCandidates,\n\t\t\t\tgraphExpanded,\n\t\t\t\tranked,\n\t\t\t\tpacked,\n\t\t\t};\n\n\t\t\tbatch(() => {\n\t\t\t\tretrievalOutput.down([[DATA, packed]]);\n\t\t\t\ttraceState.down([[DATA, trace]]);\n\t\t\t});\n\n\t\t\treturn packed;\n\t\t};\n\t}\n\n\t// --- Cleanup ---\n\tgraph.addDisposer(() => {\n\t\tfor (const unsub of keepaliveSubs) unsub();\n\t\tkeepaliveSubs.length = 0;\n\t});\n\n\treturn Object.assign(graph, {\n\t\tdistillBundle,\n\t\tcompact: distillBundle.compact,\n\t\tsize: distillBundle.size,\n\t\tvectors,\n\t\tkg,\n\t\tmemoryTiers: memoryTiersBundle,\n\t\tretrieval: retrievalNode,\n\t\tretrievalTrace: retrievalTraceNode,\n\t\tretrieve: retrieveFn,\n\t}) as AgentMemoryGraph<TMem>;\n}\n\n// ---------------------------------------------------------------------------\n// agentLoop\n// ---------------------------------------------------------------------------\n\nexport type AgentLoopOptions = {\n\tgraph?: GraphOptions;\n\tadapter: LLMAdapter;\n\ttools?: readonly ToolDefinition[];\n\tsystemPrompt?: string;\n\tmaxTurns?: number;\n\tstopWhen?: (response: LLMResponse) => boolean;\n\tonToolCall?: (call: ToolCall) => void;\n\tmaxMessages?: number;\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n};\n\nexport class AgentLoopGraph extends Graph {\n\treadonly chat: ChatStreamGraph;\n\treadonly tools: ToolRegistryGraph;\n\treadonly status: Node<AgentLoopStatus>;\n\treadonly turnCount: Node<number>;\n\treadonly lastResponse: Node<LLMResponse | null>;\n\tprivate readonly _statusState: Node<AgentLoopStatus>;\n\tprivate readonly _turnCountState: Node<number>;\n\tprivate readonly _adapter: LLMAdapter;\n\tprivate readonly _maxTurns: number;\n\tprivate readonly _stopWhen?: (response: LLMResponse) => boolean;\n\tprivate readonly _onToolCall?: (call: ToolCall) => void;\n\tprivate readonly _systemPrompt?: string;\n\tprivate readonly _model?: string;\n\tprivate readonly _temperature?: number;\n\tprivate readonly _maxTokens?: number;\n\tprivate _running = false;\n\tprivate _abortController: AbortController | null = null;\n\n\tconstructor(name: string, opts: AgentLoopOptions) {\n\t\tsuper(name, opts.graph);\n\n\t\tthis._adapter = opts.adapter;\n\t\tthis._maxTurns = opts.maxTurns ?? 10;\n\t\tthis._stopWhen = opts.stopWhen;\n\t\tthis._onToolCall = opts.onToolCall;\n\t\tthis._systemPrompt = opts.systemPrompt;\n\t\tthis._model = opts.model;\n\t\tthis._temperature = opts.temperature;\n\t\tthis._maxTokens = opts.maxTokens;\n\n\t\t// Mount chat subgraph\n\t\tthis.chat = chatStream(`${name}-chat`, { maxMessages: opts.maxMessages });\n\t\tthis.mount(\"chat\", this.chat);\n\n\t\t// Mount tool registry subgraph\n\t\tthis.tools = toolRegistry(`${name}-tools`);\n\t\tthis.mount(\"tools\", this.tools);\n\n\t\t// Register initial tools\n\t\tif (opts.tools) {\n\t\t\tfor (const tool of opts.tools) {\n\t\t\t\tthis.tools.register(tool);\n\t\t\t}\n\t\t}\n\n\t\t// Status state\n\t\tthis._statusState = state<AgentLoopStatus>(\"idle\", {\n\t\t\tname: \"status\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_status\"),\n\t\t});\n\t\tthis.status = this._statusState;\n\t\tthis.add(\"status\", this.status);\n\n\t\t// Turn count\n\t\tthis._turnCountState = state<number>(0, {\n\t\t\tname: \"turnCount\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_turn_count\"),\n\t\t});\n\t\tthis.turnCount = this._turnCountState;\n\t\tthis.add(\"turnCount\", this.turnCount);\n\n\t\t// Last LLM response\n\t\tthis.lastResponse = state<LLMResponse | null>(null, {\n\t\t\tname: \"lastResponse\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: aiMeta(\"agent_last_response\"),\n\t\t});\n\t\tthis.add(\"lastResponse\", this.lastResponse);\n\t}\n\n\t/**\n\t * Start the agent loop with a user message. The loop runs reactively:\n\t * think (LLM call) → act (tool execution) → repeat until done.\n\t *\n\t * Messages accumulate across calls. Call `chat.clear()` before `run()`\n\t * to reset conversation history.\n\t */\n\tasync run(userMessage: string): Promise<LLMResponse | null> {\n\t\tif (this._running) throw new Error(\"agentLoop: already running\");\n\t\tthis._running = true;\n\t\tthis._abortController = new AbortController();\n\t\tconst { signal } = this._abortController;\n\n\t\tbatch(() => {\n\t\t\tthis._statusState.down([[DATA, \"idle\" as AgentLoopStatus]]);\n\t\t\tthis._turnCountState.down([[DATA, 0]]);\n\t\t});\n\t\tthis.chat.append(\"user\", userMessage);\n\n\t\ttry {\n\t\t\tlet turns = 0;\n\t\t\twhile (turns < this._maxTurns) {\n\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\t\t\t\tturns++;\n\t\t\t\tbatch(() => {\n\t\t\t\t\tthis._turnCountState.down([[DATA, turns]]);\n\t\t\t\t\tthis._statusState.down([[DATA, \"thinking\" as AgentLoopStatus]]);\n\t\t\t\t});\n\n\t\t\t\t// Invoke LLM\n\t\t\t\tconst msgs = this.chat.allMessages();\n\t\t\t\tconst toolSchemas = (this.tools.schemas.cache as readonly ToolDefinition[]) ?? [];\n\t\t\t\tconst response = await this._invokeLLM(msgs, toolSchemas, signal);\n\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\n\t\t\t\t(this.lastResponse as Node<LLMResponse | null>).down([[DATA, response]]);\n\n\t\t\t\t// Append assistant message\n\t\t\t\tthis.chat.append(\"assistant\", response.content, {\n\t\t\t\t\ttoolCalls: response.toolCalls,\n\t\t\t\t});\n\n\t\t\t\t// Check stop conditions\n\t\t\t\tif (this._shouldStop(response)) {\n\t\t\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\t\t\tthis._running = false;\n\t\t\t\t\tthis._abortController = null;\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Execute tool calls if present\n\t\t\t\tif (response.toolCalls && response.toolCalls.length > 0) {\n\t\t\t\t\tthis._statusState.down([[DATA, \"acting\" as AgentLoopStatus]]);\n\t\t\t\t\tfor (const call of response.toolCalls) {\n\t\t\t\t\t\tif (signal.aborted) throw new Error(\"agentLoop: aborted\");\n\t\t\t\t\t\tthis._onToolCall?.(call);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await this.tools.execute(call.name, call.arguments);\n\t\t\t\t\t\t\tthis.chat.appendToolResult(call.id, JSON.stringify(result));\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tthis.chat.appendToolResult(call.id, JSON.stringify({ error: String(err) }));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// No tool calls and not explicitly stopped → done\n\t\t\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\t\t\tthis._running = false;\n\t\t\t\t\tthis._abortController = null;\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Max turns reached\n\t\t\tthis._statusState.down([[DATA, \"done\" as AgentLoopStatus]]);\n\t\t\tthis._running = false;\n\t\t\tthis._abortController = null;\n\t\t\treturn this.lastResponse.cache as LLMResponse | null;\n\t\t} catch (err) {\n\t\t\tthis._statusState.down([[DATA, \"error\" as AgentLoopStatus]]);\n\t\t\tthis._running = false;\n\t\t\tthis._abortController = null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprivate async _invokeLLM(\n\t\tmsgs: readonly ChatMessage[],\n\t\ttools: readonly ToolDefinition[],\n\t\tsignal?: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tconst result = this._adapter.invoke(msgs, {\n\t\t\ttools: tools.length > 0 ? tools : undefined,\n\t\t\tsystemPrompt: this._systemPrompt,\n\t\t\tmodel: this._model,\n\t\t\ttemperature: this._temperature,\n\t\t\tmaxTokens: this._maxTokens,\n\t\t\tsignal,\n\t\t});\n\t\t// Null/undefined guard\n\t\tif (result == null) {\n\t\t\tthrow new Error(\"_invokeLLM: adapter.invoke() returned null or undefined\");\n\t\t}\n\t\t// String guard — fromAny would iterate characters\n\t\tif (typeof result === \"string\") {\n\t\t\tthrow new Error(\"_invokeLLM: adapter.invoke() returned a string, expected LLMResponse\");\n\t\t}\n\t\t// If result is already an LLMResponse (sync adapter), return directly\n\t\tif (\n\t\t\ttypeof result === \"object\" &&\n\t\t\t\"content\" in result &&\n\t\t\t!(\"subscribe\" in result) &&\n\t\t\t!(\"then\" in result)\n\t\t) {\n\t\t\treturn result as LLMResponse;\n\t\t}\n\t\t// If result is a Promise, await it then check for LLMResponse\n\t\tif (isPromiseLike(result)) {\n\t\t\tconst awaited = await result;\n\t\t\tif (\n\t\t\t\ttypeof awaited === \"object\" &&\n\t\t\t\tawaited !== null &&\n\t\t\t\t\"content\" in awaited &&\n\t\t\t\t!(\"subscribe\" in awaited)\n\t\t\t) {\n\t\t\t\treturn awaited as LLMResponse;\n\t\t\t}\n\t\t\treturn firstDataFromNode(fromAny(awaited as NodeInput<LLMResponse>)) as Promise<LLMResponse>;\n\t\t}\n\t\t// If result is a Node or async iterable, resolve via fromAny + firstDataFromNode\n\t\treturn firstDataFromNode(fromAny(result)) as Promise<LLMResponse>;\n\t}\n\n\tprivate _shouldStop(response: LLMResponse): boolean {\n\t\tif (\n\t\t\tresponse.finishReason === \"end_turn\" &&\n\t\t\t(!response.toolCalls || response.toolCalls.length === 0)\n\t\t)\n\t\t\treturn true;\n\t\tif (this._stopWhen?.(response)) return true;\n\t\treturn false;\n\t}\n\n\toverride destroy(): void {\n\t\tif (this._abortController) {\n\t\t\tthis._abortController.abort();\n\t\t\tthis._abortController = null;\n\t\t}\n\t\tthis._running = false;\n\t\tsuper.destroy();\n\t}\n}\n\nexport function agentLoop(name: string, opts: AgentLoopOptions): AgentLoopGraph {\n\treturn new AgentLoopGraph(name, opts);\n}\n\n// ---------------------------------------------------------------------------\n// 5.4 — LLM tool integration\n// ---------------------------------------------------------------------------\n\n/** OpenAI function-calling tool schema. */\nexport type OpenAIToolSchema = {\n\treadonly type: \"function\";\n\treadonly function: {\n\t\treadonly name: string;\n\t\treadonly description: string;\n\t\treadonly parameters: Record<string, unknown>;\n\t};\n};\n\n/** MCP (Model Context Protocol) tool schema. */\nexport type McpToolSchema = {\n\treadonly name: string;\n\treadonly description: string;\n\treadonly inputSchema: Record<string, unknown>;\n};\n\n/** Result of {@link knobsAsTools}. */\nexport type KnobsAsToolsResult = {\n\t/** OpenAI function-calling tool schemas. */\n\treadonly openai: readonly OpenAIToolSchema[];\n\t/** MCP tool schemas. */\n\treadonly mcp: readonly McpToolSchema[];\n\t/** GraphReFly ToolDefinitions with handlers that call `graph.set()`. */\n\treadonly definitions: readonly ToolDefinition[];\n};\n\n/**\n * Build a JSON Schema `properties.value` descriptor from a node's meta fields.\n *\n * Maps `meta.type`, `meta.range`, `meta.values`, `meta.format`, and `meta.unit`\n * to a JSON Schema property definition.\n */\nfunction metaToJsonSchema(meta: Record<string, unknown>): Record<string, unknown> {\n\tconst schema: Record<string, unknown> = {};\n\n\tconst metaType = meta.type as string | undefined;\n\tif (metaType === \"enum\" && Array.isArray(meta.values)) {\n\t\tschema.type = \"string\";\n\t\tschema.enum = meta.values;\n\t} else if (metaType === \"integer\") {\n\t\tschema.type = \"integer\";\n\t} else if (metaType === \"number\") {\n\t\tschema.type = \"number\";\n\t} else if (metaType === \"boolean\") {\n\t\tschema.type = \"boolean\";\n\t} else if (metaType === \"string\") {\n\t\tschema.type = \"string\";\n\t} else {\n\t\t// Unknown or unspecified — accept anything\n\t\tschema.type = [\"string\", \"number\", \"boolean\"];\n\t}\n\n\tif (Array.isArray(meta.range) && meta.range.length === 2) {\n\t\tschema.minimum = meta.range[0];\n\t\tschema.maximum = meta.range[1];\n\t}\n\n\tif (typeof meta.format === \"string\") {\n\t\tschema.description = `Format: ${meta.format}`;\n\t}\n\n\tif (typeof meta.unit === \"string\") {\n\t\tif (schema.description) {\n\t\t\tschema.description += ` (${meta.unit})`;\n\t\t} else {\n\t\t\tschema.description = `Unit: ${meta.unit}`;\n\t\t}\n\t}\n\n\treturn schema;\n}\n\n/**\n * Derive tool schemas from a graph's writable (knob) nodes.\n *\n * Knobs are state nodes whose `meta.access` is `\"llm\"`, `\"both\"`, or absent\n * (default: writable). Each knob becomes a tool that calls `graph.set()`.\n *\n * Speaks **domain language** (spec §5.4): the returned schemas use node names\n * and meta descriptions — no protocol internals exposed.\n *\n * @param graph - The graph to introspect.\n * @param actor - Optional actor for guard-scoped describe.\n * @returns OpenAI, MCP, and GraphReFly tool schemas.\n */\nexport function knobsAsTools(graph: Graph, actor?: Actor): KnobsAsToolsResult {\n\tconst described = graph.describe({ actor, detail: \"full\" });\n\tconst openai: OpenAIToolSchema[] = [];\n\tconst mcp: McpToolSchema[] = [];\n\tconst definitions: ToolDefinition[] = [];\n\n\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\t// Only state nodes are writable knobs\n\t\tif (node.type !== \"state\") continue;\n\n\t\t// Skip meta companion nodes (§2.3)\n\t\tif (path.includes(\"::__meta__::\")) continue;\n\n\t\t// Skip terminal-state nodes (§1.3.4 — no further messages after COMPLETE/ERROR)\n\t\tif (node.status === \"completed\" || node.status === \"errored\") continue;\n\n\t\t// Skip if access explicitly excludes LLM\n\t\tconst meta = node.meta ?? {};\n\t\tconst access = meta.access as string | undefined;\n\t\tif (access === \"human\" || access === \"system\") continue;\n\n\t\tconst description = (meta.description as string) ?? `Set the value of ${path}`;\n\t\tconst valueSchema = metaToJsonSchema(meta);\n\n\t\tconst parameterSchema: Record<string, unknown> = {\n\t\t\ttype: \"object\",\n\t\t\trequired: [\"value\"],\n\t\t\tproperties: {\n\t\t\t\tvalue: valueSchema,\n\t\t\t},\n\t\t\tadditionalProperties: false,\n\t\t};\n\n\t\t// OpenAI requires [a-zA-Z0-9_-] in function names; sanitize :: separators\n\t\tconst sanitizedName = path.replace(/::/g, \"__\");\n\n\t\topenai.push({\n\t\t\ttype: \"function\",\n\t\t\tfunction: {\n\t\t\t\tname: sanitizedName,\n\t\t\t\tdescription,\n\t\t\t\tparameters: parameterSchema,\n\t\t\t},\n\t\t});\n\n\t\tmcp.push({\n\t\t\tname: path,\n\t\t\tdescription,\n\t\t\tinputSchema: parameterSchema,\n\t\t});\n\n\t\tconst graphRef = graph;\n\t\tconst actorRef = actor;\n\t\tconst nv = node.v;\n\t\tdefinitions.push({\n\t\t\tname: path,\n\t\t\tdescription,\n\t\t\tparameters: parameterSchema,\n\t\t\thandler(args: Record<string, unknown>) {\n\t\t\t\tgraphRef.set(path, args.value, actorRef ? { actor: actorRef } : undefined);\n\t\t\t\treturn args.value;\n\t\t\t},\n\t\t\t...(nv != null ? { version: { id: nv.id, version: nv.version } } : {}),\n\t\t});\n\t}\n\n\treturn { openai, mcp, definitions };\n}\n\n// ---------------------------------------------------------------------------\n// gaugesAsContext\n// ---------------------------------------------------------------------------\n\nexport type GaugesAsContextOptions = {\n\t/** Group gauges by `meta.tags` (default true). */\n\tgroupByTags?: boolean;\n\t/** Separator between gauge lines (default \"\\n\"). */\n\tseparator?: string;\n\t/**\n\t * V0 delta mode (§6.0b): only include nodes whose `v.version` exceeds\n\t * the corresponding entry in this map. Nodes without V0 or not in the\n\t * map are always included. Callers maintain this map across calls.\n\t *\n\t * The `id` field guards against node replacement: if a node is removed\n\t * and re-added under the same name (new id), it is always included.\n\t */\n\tsinceVersion?: ReadonlyMap<string, { id: string; version: number }>;\n};\n\n/**\n * Format a graph's readable (gauge) nodes as a context string for LLM\n * system prompts.\n *\n * Gauges are nodes with `meta.description` or `meta.format`. Values are\n * formatted using `meta.format` and `meta.unit` hints.\n *\n * @param graph - The graph to introspect.\n * @param actor - Optional actor for guard-scoped describe.\n * @param options - Formatting options.\n * @returns A formatted string ready for system prompt injection.\n */\nexport function gaugesAsContext(\n\tgraph: Graph,\n\tactor?: Actor,\n\toptions?: GaugesAsContextOptions,\n): string {\n\tconst described = graph.describe({ actor, detail: \"full\" });\n\tconst groupByTags = options?.groupByTags ?? true;\n\tconst separator = options?.separator ?? \"\\n\";\n\n\ttype GaugeEntry = { path: string; description: string; formatted: string };\n\tconst entries: GaugeEntry[] = [];\n\n\tconst sinceVersion = options?.sinceVersion;\n\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\tconst meta = node.meta ?? {};\n\t\tconst desc = meta.description as string | undefined;\n\t\tconst format = meta.format as string | undefined;\n\t\t// Must have description or format to be a gauge\n\t\tif (!desc && !format) continue;\n\t\t// V0 delta filter: skip nodes unchanged since last seen version (§6.0b).\n\t\tif (sinceVersion != null && node.v != null) {\n\t\t\tconst lastSeen = sinceVersion.get(path);\n\t\t\tif (lastSeen != null && lastSeen.id === node.v.id && node.v.version <= lastSeen.version)\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tconst label = desc ?? path;\n\t\tconst value = node.value;\n\t\tconst unit = meta.unit as string | undefined;\n\n\t\tlet formatted: string;\n\t\tif (format === \"currency\" && typeof value === \"number\") {\n\t\t\tformatted = `$${value.toFixed(2)}`;\n\t\t} else if (format === \"percentage\" && typeof value === \"number\") {\n\t\t\tformatted = `${(value * 100).toFixed(1)}%`;\n\t\t} else if (value === undefined || value === null) {\n\t\t\tformatted = \"(no value)\";\n\t\t} else {\n\t\t\tformatted = String(value);\n\t\t}\n\n\t\tif (unit && format !== \"currency\" && format !== \"percentage\") {\n\t\t\tformatted = `${formatted} ${unit}`;\n\t\t}\n\n\t\tentries.push({ path, description: label, formatted });\n\t}\n\n\tif (entries.length === 0) return \"\";\n\n\tif (groupByTags) {\n\t\tconst tagGroups = new Map<string, GaugeEntry[]>();\n\t\tconst ungrouped: GaugeEntry[] = [];\n\n\t\tfor (const entry of entries) {\n\t\t\tconst node = described.nodes[entry.path]!;\n\t\t\tconst tags = node.meta?.tags as string[] | undefined;\n\t\t\tif (tags && tags.length > 0) {\n\t\t\t\t// Use first tag for grouping to avoid duplicating entries across groups\n\t\t\t\tconst tag = tags[0]!;\n\t\t\t\tlet group = tagGroups.get(tag);\n\t\t\t\tif (!group) {\n\t\t\t\t\tgroup = [];\n\t\t\t\t\ttagGroups.set(tag, group);\n\t\t\t\t}\n\t\t\t\tgroup.push(entry);\n\t\t\t} else {\n\t\t\t\tungrouped.push(entry);\n\t\t\t}\n\t\t}\n\n\t\tif (tagGroups.size === 0) {\n\t\t\treturn entries.map((e) => `- ${e.description}: ${e.formatted}`).join(separator);\n\t\t}\n\n\t\tconst sections: string[] = [];\n\t\tfor (const [tag, group] of [...tagGroups.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n\t\t\tsections.push(\n\t\t\t\t`[${tag}]${separator}${group.map((e) => `- ${e.description}: ${e.formatted}`).join(separator)}`,\n\t\t\t);\n\t\t}\n\t\tif (ungrouped.length > 0) {\n\t\t\tsections.push(ungrouped.map((e) => `- ${e.description}: ${e.formatted}`).join(separator));\n\t\t}\n\t\treturn sections.join(separator + separator);\n\t}\n\n\treturn entries.map((e) => `- ${e.description}: ${e.formatted}`).join(separator);\n}\n\n// ---------------------------------------------------------------------------\n// validateGraphDef\n// ---------------------------------------------------------------------------\n\n/** Validation result from {@link validateGraphDef}. */\nexport type GraphDefValidation = {\n\treadonly valid: boolean;\n\treadonly errors: readonly string[];\n};\n\nconst VALID_NODE_TYPES = new Set([\"state\", \"derived\", \"producer\", \"operator\", \"effect\"]);\n\n/**\n * Validate an LLM-generated graph definition before passing to\n * `Graph.fromSnapshot()`.\n *\n * Checks:\n * - Required fields: `name`, `nodes`, `edges`\n * - Node types are valid enum values\n * - Edge `from`/`to` reference existing nodes\n * - No duplicate edge entries\n *\n * @param def - The graph definition to validate (parsed JSON).\n * @returns Validation result with errors array.\n */\nexport function validateGraphDef(def: unknown): GraphDefValidation {\n\tconst errors: string[] = [];\n\n\tif (def == null || typeof def !== \"object\") {\n\t\treturn { valid: false, errors: [\"Definition must be a non-null object\"] };\n\t}\n\n\tconst d = def as Record<string, unknown>;\n\n\tif (typeof d.name !== \"string\" || d.name.length === 0) {\n\t\terrors.push(\"Missing or empty 'name' field\");\n\t}\n\n\tif (d.nodes == null || typeof d.nodes !== \"object\" || Array.isArray(d.nodes)) {\n\t\terrors.push(\"Missing or invalid 'nodes' field (must be an object)\");\n\t\treturn { valid: false, errors };\n\t}\n\n\tconst nodeNames = new Set(Object.keys(d.nodes as object));\n\n\tfor (const [name, raw] of Object.entries(d.nodes as Record<string, unknown>)) {\n\t\tif (raw == null || typeof raw !== \"object\") {\n\t\t\terrors.push(`Node \"${name}\": must be an object`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = raw as Record<string, unknown>;\n\t\tif (typeof node.type !== \"string\" || !VALID_NODE_TYPES.has(node.type)) {\n\t\t\terrors.push(\n\t\t\t\t`Node \"${name}\": invalid type \"${String(node.type)}\" (expected: ${[...VALID_NODE_TYPES].join(\", \")})`,\n\t\t\t);\n\t\t}\n\t\tif (Array.isArray(node.deps)) {\n\t\t\tfor (const dep of node.deps) {\n\t\t\t\tif (typeof dep === \"string\" && !nodeNames.has(dep)) {\n\t\t\t\t\terrors.push(`Node \"${name}\": dep \"${dep}\" does not reference an existing node`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!Array.isArray(d.edges)) {\n\t\tif (d.edges !== undefined) {\n\t\t\terrors.push(\"'edges' must be an array\");\n\t\t}\n\t\t// edges are optional — no error if absent\n\t} else {\n\t\tconst seen = new Set<string>();\n\t\tfor (let i = 0; i < (d.edges as unknown[]).length; i++) {\n\t\t\tconst edge = (d.edges as unknown[])[i];\n\t\t\tif (edge == null || typeof edge !== \"object\") {\n\t\t\t\terrors.push(`Edge [${i}]: must be an object`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst e = edge as Record<string, unknown>;\n\t\t\tif (typeof e.from !== \"string\" || !nodeNames.has(e.from)) {\n\t\t\t\terrors.push(`Edge [${i}]: 'from' \"${String(e.from)}\" does not reference an existing node`);\n\t\t\t}\n\t\t\tif (typeof e.to !== \"string\" || !nodeNames.has(e.to)) {\n\t\t\t\terrors.push(`Edge [${i}]: 'to' \"${String(e.to)}\" does not reference an existing node`);\n\t\t\t}\n\t\t\tconst key = `${e.from}->${e.to}`;\n\t\t\tif (seen.has(key)) {\n\t\t\t\terrors.push(`Edge [${i}]: duplicate edge ${key}`);\n\t\t\t}\n\t\t\tseen.add(key);\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// graphFromSpec\n// ---------------------------------------------------------------------------\n\nexport type GraphFromSpecOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Callback to construct topology before values are applied (passed to `Graph.fromSnapshot`). */\n\tbuild?: (g: Graph) => void;\n\t/** Extra instructions appended to the system prompt. */\n\tsystemPromptExtra?: string;\n};\n\n/** Strip markdown code fences, handling trailing commentary after closing fence. */\nfunction stripFences(text: string): string {\n\tconst match = text.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```[\\s\\S]*$/);\n\treturn match ? match[1]! : text;\n}\n\nconst GRAPH_FROM_SPEC_SYSTEM_PROMPT = `You are a graph architect for GraphReFly, a reactive graph protocol.\n\nGiven a natural-language description, produce a JSON graph definition with this structure:\n\n{\n \"name\": \"<graph_name>\",\n \"nodes\": {\n \"<node_name>\": {\n \"type\": \"state\" | \"derived\" | \"producer\" | \"operator\" | \"effect\",\n \"value\": <initial_value_or_null>,\n \"deps\": [\"<dep_node_name>\", ...],\n \"meta\": {\n \"description\": \"<human-readable purpose>\",\n \"type\": \"string\" | \"number\" | \"boolean\" | \"integer\" | \"enum\",\n \"range\": [min, max],\n \"values\": [\"a\", \"b\"],\n \"format\": \"currency\" | \"percentage\" | \"status\",\n \"access\": \"human\" | \"llm\" | \"both\" | \"system\",\n \"unit\": \"<unit>\",\n \"tags\": [\"<tag>\"]\n }\n }\n },\n \"edges\": [\n { \"from\": \"<source_node>\", \"to\": \"<target_node>\" }\n ]\n}\n\nRules:\n- \"state\" nodes have no deps and hold user/LLM-writable values (knobs).\n- \"derived\" nodes have deps and compute from them.\n- \"effect\" nodes have deps but produce side effects (no return value).\n- \"producer\" nodes have no deps but generate values asynchronously.\n- Edges wire output of one node as input to another. They must match deps.\n- meta.description is required for every node.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/**\n * Ask an LLM to compose a Graph from a natural-language description.\n *\n * The LLM returns a JSON graph definition which is validated and then\n * constructed via `Graph.fromSnapshot()`.\n *\n * @param naturalLanguage - The problem/use-case description.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options and optional `build` callback for node factories.\n * @returns A constructed Graph.\n * @throws On invalid LLM output or validation failure.\n */\nexport async function graphFromSpec(\n\tnaturalLanguage: string,\n\tadapter: LLMAdapter,\n\topts?: GraphFromSpecOptions,\n): Promise<Graph> {\n\tconst systemPrompt = opts?.systemPromptExtra\n\t\t? `${GRAPH_FROM_SPEC_SYSTEM_PROMPT}\\n\\n${opts.systemPromptExtra}`\n\t\t: GRAPH_FROM_SPEC_SYSTEM_PROMPT;\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{ role: \"user\", content: naturalLanguage },\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\tconst response = (await resolveToolHandlerResult(rawResult)) as LLMResponse;\n\tlet content = response.content.trim();\n\n\t// Strip markdown fences if present (handles trailing commentary after ```)\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`graphFromSpec: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateGraphDef(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`graphFromSpec: invalid graph definition:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tconst def = parsed as Record<string, unknown>;\n\t// Ensure version field is present for fromSnapshot envelope check\n\tif (def.version === undefined) def.version = 1;\n\tif (!Array.isArray(def.subgraphs)) def.subgraphs = [];\n\treturn Graph.fromSnapshot(def as GraphPersistSnapshot, opts?.build);\n}\n\n// ---------------------------------------------------------------------------\n// suggestStrategy\n// ---------------------------------------------------------------------------\n\n/** A single operation in a strategy plan. */\nexport type StrategyOperation =\n\t| {\n\t\t\treadonly type: \"add_node\";\n\t\t\treadonly name: string;\n\t\t\treadonly nodeType: string;\n\t\t\treadonly meta?: Record<string, unknown>;\n\t\t\treadonly initial?: unknown;\n\t }\n\t| { readonly type: \"remove_node\"; readonly name: string }\n\t| { readonly type: \"connect\"; readonly from: string; readonly to: string }\n\t| { readonly type: \"disconnect\"; readonly from: string; readonly to: string }\n\t| { readonly type: \"set_value\"; readonly name: string; readonly value: unknown }\n\t| {\n\t\t\treadonly type: \"update_meta\";\n\t\t\treadonly name: string;\n\t\t\treadonly key: string;\n\t\t\treadonly value: unknown;\n\t };\n\n/** Structured strategy plan returned by {@link suggestStrategy}. */\nexport type StrategyPlan = {\n\treadonly summary: string;\n\treadonly operations: readonly StrategyOperation[];\n\treadonly reasoning: string;\n};\n\nexport type SuggestStrategyOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\tactor?: Actor;\n};\n\nconst SUGGEST_STRATEGY_SYSTEM_PROMPT = `You are a reactive graph optimizer for GraphReFly.\n\nGiven a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.\n\nReturn ONLY valid JSON with this structure:\n{\n \"summary\": \"<one-line summary of the strategy>\",\n \"reasoning\": \"<explanation of why these changes help>\",\n \"operations\": [\n { \"type\": \"add_node\", \"name\": \"<name>\", \"nodeType\": \"state|derived|effect|producer|operator\", \"meta\": {...}, \"initial\": <value> },\n { \"type\": \"remove_node\", \"name\": \"<name>\" },\n { \"type\": \"connect\", \"from\": \"<source>\", \"to\": \"<target>\" },\n { \"type\": \"disconnect\", \"from\": \"<source>\", \"to\": \"<target>\" },\n { \"type\": \"set_value\", \"name\": \"<name>\", \"value\": <new_value> },\n { \"type\": \"update_meta\", \"name\": \"<name>\", \"key\": \"<meta_key>\", \"value\": <new_value> }\n ]\n}\n\nRules:\n- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).\n- Keep changes minimal — prefer the smallest set of operations that solves the problem.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/**\n * Ask an LLM to analyze a graph and suggest topology/parameter changes\n * to solve a stated problem.\n *\n * Returns a structured plan — does NOT auto-apply. The caller reviews\n * and selectively applies operations.\n *\n * @param graph - The graph to analyze.\n * @param problem - Natural-language problem statement.\n * @param adapter - LLM adapter for the analysis call.\n * @param opts - Model and actor options.\n * @returns A structured strategy plan.\n * @throws On invalid LLM output.\n */\nexport async function suggestStrategy(\n\tgraph: Graph,\n\tproblem: string,\n\tadapter: LLMAdapter,\n\topts?: SuggestStrategyOptions,\n): Promise<StrategyPlan> {\n\tconst { expand: _, ...described } = graph.describe({ actor: opts?.actor, detail: \"standard\" });\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: SUGGEST_STRATEGY_SYSTEM_PROMPT },\n\t\t{\n\t\t\trole: \"user\",\n\t\t\tcontent: JSON.stringify({\n\t\t\t\tgraph: described,\n\t\t\t\tproblem,\n\t\t\t}),\n\t\t},\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\tconst response = (await resolveToolHandlerResult(rawResult)) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = content.replace(/^```(?:json)?\\s*/, \"\").replace(/\\s*```$/, \"\");\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`suggestStrategy: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst plan = parsed as Record<string, unknown>;\n\n\tif (typeof plan.summary !== \"string\") {\n\t\tthrow new Error(\"suggestStrategy: missing 'summary' in response\");\n\t}\n\tif (typeof plan.reasoning !== \"string\") {\n\t\tthrow new Error(\"suggestStrategy: missing 'reasoning' in response\");\n\t}\n\tif (!Array.isArray(plan.operations)) {\n\t\tthrow new Error(\"suggestStrategy: missing 'operations' array in response\");\n\t}\n\n\treturn {\n\t\tsummary: plan.summary,\n\t\treasoning: plan.reasoning,\n\t\toperations: plan.operations as readonly StrategyOperation[],\n\t};\n}\n","/**\n * Memory patterns (roadmap §4.3).\n *\n * Domain-layer helpers composed from GraphRefly primitives. `vectorIndex` uses\n * an exact-search backend by default; an HNSW adapter can be injected as an\n * optional dependency.\n */\n\nimport { monotonicNs } from \"../core/clock.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { Graph } from \"../graph/graph.js\";\n\nexport type CollectionPolicy = \"fifo\" | \"lru\";\nexport type VectorBackend = \"flat\" | \"hnsw\";\n\nexport type LightCollectionEntry<T> = {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: number;\n\treadonly lastAccessNs: number;\n};\n\nexport type LightCollectionOptions = {\n\tname?: string;\n\tmaxSize?: number;\n\tpolicy?: CollectionPolicy;\n};\n\nexport type LightCollectionBundle<T> = {\n\treadonly entries: Node<ReadonlyMap<string, LightCollectionEntry<T>>>;\n\tupsert: (id: string, value: T) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tget: (id: string) => T | undefined;\n\thas: (id: string) => boolean;\n};\n\nexport type CollectionEntry<T> = LightCollectionEntry<T> & {\n\treadonly baseScore: number;\n};\n\nexport type RankedCollectionEntry<T> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionOptions<T> = {\n\tmaxSize?: number;\n\tpolicy?: CollectionPolicy;\n\t/**\n\t * Produces a base score at insert/update time.\n\t */\n\tscore?: (value: T) => number;\n\t/**\n\t * Exponential decay rate per second. 0 disables decay.\n\t */\n\tdecayRate?: number;\n\t/**\n\t * Minimum score floor after decay.\n\t */\n\tminScore?: number;\n};\n\nexport type CollectionGraph<T> = Graph & {\n\tupsert: (id: string, value: T, opts?: { score?: number }) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tgetItem: (id: string) => CollectionEntry<T> | undefined;\n};\n\nexport type VectorRecord<TMeta> = {\n\treadonly id: string;\n\treadonly vector: readonly number[];\n\treadonly meta?: TMeta;\n};\n\nexport type VectorSearchResult<TMeta> = {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n};\n\nexport type HnswAdapter<TMeta> = {\n\tupsert: (id: string, vector: readonly number[], meta?: TMeta) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tsearch: (query: readonly number[], k: number) => ReadonlyArray<VectorSearchResult<TMeta>>;\n};\n\nexport type VectorIndexOptions<TMeta> = {\n\tbackend?: VectorBackend;\n\tdimension?: number;\n\t/**\n\t * Optional dependency seam for HNSW.\n\t */\n\thnswFactory?: () => HnswAdapter<TMeta>;\n};\n\nexport type VectorIndexBundle<TMeta> = {\n\treadonly backend: VectorBackend;\n\treadonly entries: Node<ReadonlyMap<string, VectorRecord<TMeta>>>;\n\tupsert: (id: string, vector: readonly number[], meta?: TMeta) => void;\n\tremove: (id: string) => void;\n\tclear: () => void;\n\tsearch: (query: readonly number[], k?: number) => ReadonlyArray<VectorSearchResult<TMeta>>;\n};\n\nexport type KnowledgeEdge<TRelation extends string = string> = {\n\treadonly from: string;\n\treadonly to: string;\n\treadonly relation: TRelation;\n\treadonly weight: number;\n};\n\nexport type KnowledgeGraphGraph<TEntity, TRelation extends string = string> = Graph & {\n\tupsertEntity: (id: string, value: TEntity) => void;\n\tremoveEntity: (id: string) => void;\n\tlink: (from: string, to: string, relation: TRelation, weight?: number) => void;\n\tunlink: (from: string, to: string, relation?: TRelation) => void;\n\trelated: (id: string, relation?: TRelation) => ReadonlyArray<KnowledgeEdge<TRelation>>;\n};\n\nexport function decay(\n\tbaseScore: number,\n\tageSeconds: number,\n\tratePerSecond: number,\n\tminScore = 0,\n): number {\n\tif (!Number.isFinite(baseScore)) return minScore;\n\tif (!Number.isFinite(ageSeconds) || ageSeconds <= 0) return Math.max(minScore, baseScore);\n\tif (!Number.isFinite(ratePerSecond) || ratePerSecond <= 0) return Math.max(minScore, baseScore);\n\tconst decayed = baseScore * Math.exp(-ratePerSecond * ageSeconds);\n\treturn Math.max(minScore, decayed);\n}\n\nfunction assertMaxSize(maxSize: number | undefined): void {\n\tif (maxSize !== undefined && maxSize < 1) {\n\t\tthrow new RangeError(\"maxSize must be >= 1\");\n\t}\n}\n\nfunction copyMap<K, V>(m: ReadonlyMap<K, V>): Map<K, V> {\n\treturn new Map(m);\n}\n\nfunction readMap<K, V>(node: Node<ReadonlyMap<K, V>>): ReadonlyMap<K, V> {\n\treturn node.cache ?? new Map<K, V>();\n}\n\nfunction readArray<T>(node: Node<ReadonlyArray<T>>): ReadonlyArray<T> {\n\treturn node.cache ?? [];\n}\n\nfunction cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\treturn dot / Math.sqrt(na * nb);\n}\n\nexport function lightCollection<T>(opts: LightCollectionOptions = {}): LightCollectionBundle<T> {\n\tconst maxSize = opts.maxSize;\n\tconst policy = opts.policy ?? \"fifo\";\n\tassertMaxSize(maxSize);\n\n\tconst entries = state<ReadonlyMap<string, LightCollectionEntry<T>>>(new Map(), {\n\t\tname: opts.name,\n\t\tdescribeKind: \"state\",\n\t});\n\n\tfunction evictIfNeeded(next: Map<string, LightCollectionEntry<T>>): void {\n\t\tif (maxSize === undefined) return;\n\t\twhile (next.size > maxSize) {\n\t\t\tlet victim: LightCollectionEntry<T> | undefined;\n\t\t\tfor (const entry of next.values()) {\n\t\t\t\tif (!victim) {\n\t\t\t\t\tvictim = entry;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lhs = policy === \"lru\" ? entry.lastAccessNs : entry.createdAtNs;\n\t\t\t\tconst rhs = policy === \"lru\" ? victim.lastAccessNs : victim.createdAtNs;\n\t\t\t\tif (lhs < rhs) victim = entry;\n\t\t\t}\n\t\t\tif (!victim) break;\n\t\t\tnext.delete(victim.id);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, LightCollectionEntry<T>>): void {\n\t\tentries.down([[DATA, next]]);\n\t}\n\n\treturn {\n\t\tentries,\n\t\tupsert(id, value) {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst current = readMap(entries);\n\t\t\tconst prev = current.get(id);\n\t\t\tconst next = copyMap(current);\n\t\t\tnext.set(id, {\n\t\t\t\tid,\n\t\t\t\tvalue,\n\t\t\t\tcreatedAtNs: prev?.createdAtNs ?? now,\n\t\t\t\tlastAccessNs: now,\n\t\t\t});\n\t\t\tevictIfNeeded(next);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id) {\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(entries).size === 0) return;\n\t\t\tcommit(new Map());\n\t\t},\n\t\tget(id) {\n\t\t\tconst current = readMap(entries);\n\t\t\tconst found = current.get(id);\n\t\t\tif (!found) return undefined;\n\t\t\tif (policy === \"lru\") {\n\t\t\t\tconst now = monotonicNs();\n\t\t\t\tconst next = copyMap(current);\n\t\t\t\tnext.set(id, { ...found, lastAccessNs: now });\n\t\t\t\tcommit(next);\n\t\t\t}\n\t\t\treturn found.value;\n\t\t},\n\t\thas(id) {\n\t\t\treturn readMap(entries).has(id);\n\t\t},\n\t};\n}\n\nexport function collection<T>(name: string, opts: CollectionOptions<T> = {}): CollectionGraph<T> {\n\tconst maxSize = opts.maxSize;\n\tconst policy = opts.policy ?? \"lru\";\n\tconst decayRate = opts.decayRate ?? 0;\n\tconst minScore = opts.minScore ?? 0;\n\tconst scoreFn = opts.score ?? (() => 1);\n\tassertMaxSize(maxSize);\n\n\tconst graph = new Graph(name);\n\tconst items = state<ReadonlyMap<string, CollectionEntry<T>>>(new Map(), {\n\t\tname: \"items\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst ranked = derived(\n\t\t[items],\n\t\t([snapshot]) => {\n\t\t\tconst typed = (snapshot ?? new Map()) as ReadonlyMap<string, CollectionEntry<T>>;\n\t\t\tconst now = monotonicNs();\n\t\t\tconst out = [...typed.values()].map((entry) => {\n\t\t\t\tconst ageSeconds = (now - entry.lastAccessNs) / 1_000_000_000;\n\t\t\t\treturn {\n\t\t\t\t\t...entry,\n\t\t\t\t\tscore: decay(entry.baseScore, ageSeconds, decayRate, minScore),\n\t\t\t\t};\n\t\t\t});\n\t\t\tout.sort((a, b) => b.score - a.score || b.lastAccessNs - a.lastAccessNs);\n\t\t\treturn out;\n\t\t},\n\t\t{ name: \"ranked\", describeKind: \"derived\" },\n\t);\n\tconst size = derived(\n\t\t[items],\n\t\t([snapshot]) => ((snapshot ?? new Map()) as ReadonlyMap<string, CollectionEntry<T>>).size,\n\t\t{\n\t\t\tname: \"size\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tinitial: 0,\n\t\t},\n\t);\n\tvoid ranked.subscribe(() => undefined);\n\tvoid size.subscribe(() => undefined);\n\n\tgraph.add(\"items\", items);\n\tgraph.add(\"ranked\", ranked);\n\tgraph.add(\"size\", size);\n\n\tfunction effective(entry: CollectionEntry<T>, now: number): number {\n\t\tconst ageSeconds = (now - entry.lastAccessNs) / 1_000_000_000;\n\t\treturn decay(entry.baseScore, ageSeconds, decayRate, minScore);\n\t}\n\n\tfunction evictIfNeeded(next: Map<string, CollectionEntry<T>>): void {\n\t\tif (maxSize === undefined) return;\n\t\twhile (next.size > maxSize) {\n\t\t\tconst now = monotonicNs();\n\t\t\tlet victim: CollectionEntry<T> | undefined;\n\t\t\tlet victimScore = Number.POSITIVE_INFINITY;\n\t\t\tfor (const entry of next.values()) {\n\t\t\t\tconst score = effective(entry, now);\n\t\t\t\tif (score < victimScore) {\n\t\t\t\t\tvictim = entry;\n\t\t\t\t\tvictimScore = score;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (score === victimScore && victim) {\n\t\t\t\t\tconst lhs = policy === \"lru\" ? entry.lastAccessNs : entry.createdAtNs;\n\t\t\t\t\tconst rhs = policy === \"lru\" ? victim.lastAccessNs : victim.createdAtNs;\n\t\t\t\t\tif (lhs < rhs) victim = entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!victim) break;\n\t\t\tnext.delete(victim.id);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, CollectionEntry<T>>): void {\n\t\titems.down([[DATA, next]]);\n\t}\n\n\tconst out = Object.assign(graph, {\n\t\tupsert(id: string, value: T, upsertOpts?: { score?: number }) {\n\t\t\tconst now = monotonicNs();\n\t\t\tconst current = readMap(items);\n\t\t\tconst prev = current.get(id);\n\t\t\tconst baseScore = upsertOpts?.score ?? scoreFn(value);\n\t\t\tconst next = copyMap(current);\n\t\t\tnext.set(id, {\n\t\t\t\tid,\n\t\t\t\tvalue,\n\t\t\t\tbaseScore,\n\t\t\t\tcreatedAtNs: prev?.createdAtNs ?? now,\n\t\t\t\tlastAccessNs: now,\n\t\t\t});\n\t\t\tevictIfNeeded(next);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id: string) {\n\t\t\tconst next = copyMap(readMap(items));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(items).size === 0) return;\n\t\t\tcommit(new Map());\n\t\t},\n\t\tgetItem(id: string): CollectionEntry<T> | undefined {\n\t\t\tconst current = readMap(items);\n\t\t\tconst found = current.get(id);\n\t\t\tif (!found) return undefined;\n\t\t\tif (policy === \"lru\") {\n\t\t\t\tconst next = copyMap(current);\n\t\t\t\tnext.set(id, { ...found, lastAccessNs: monotonicNs() });\n\t\t\t\tcommit(next);\n\t\t\t}\n\t\t\treturn found;\n\t\t},\n\t}) as CollectionGraph<T>;\n\treturn out;\n}\n\nexport function vectorIndex<TMeta>(opts: VectorIndexOptions<TMeta> = {}): VectorIndexBundle<TMeta> {\n\tconst backend = opts.backend ?? \"flat\";\n\tconst dimension = opts.dimension;\n\tlet hnsw: HnswAdapter<TMeta> | undefined;\n\tif (backend === \"hnsw\") {\n\t\thnsw = opts.hnswFactory?.();\n\t\tif (!hnsw) {\n\t\t\tthrow new Error(\n\t\t\t\t'vectorIndex backend \"hnsw\" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.',\n\t\t\t);\n\t\t}\n\t}\n\n\tconst entries = state<ReadonlyMap<string, VectorRecord<TMeta>>>(new Map(), {\n\t\tdescribeKind: \"state\",\n\t\tname: \"vector-index\",\n\t});\n\n\tfunction assertDimension(vector: readonly number[]): void {\n\t\tif (dimension !== undefined && vector.length !== dimension) {\n\t\t\tthrow new RangeError(\n\t\t\t\t`vector dimension mismatch: expected ${dimension}, got ${vector.length}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction commit(next: Map<string, VectorRecord<TMeta>>): void {\n\t\tentries.down([[DATA, next]]);\n\t}\n\n\treturn {\n\t\tbackend,\n\t\tentries,\n\t\tupsert(id, vector, meta) {\n\t\t\tassertDimension(vector);\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tnext.set(id, { id, vector: [...vector], meta });\n\t\t\tif (backend === \"hnsw\") hnsw!.upsert(id, vector, meta);\n\t\t\tcommit(next);\n\t\t},\n\t\tremove(id) {\n\t\t\tconst next = copyMap(readMap(entries));\n\t\t\tif (!next.delete(id)) return;\n\t\t\tif (backend === \"hnsw\") hnsw!.remove(id);\n\t\t\tcommit(next);\n\t\t},\n\t\tclear() {\n\t\t\tif (readMap(entries).size === 0) return;\n\t\t\tif (backend === \"hnsw\") hnsw!.clear();\n\t\t\tcommit(new Map());\n\t\t},\n\t\tsearch(query, k = 5) {\n\t\t\tassertDimension(query);\n\t\t\tif (k <= 0) return [];\n\t\t\tif (backend === \"hnsw\") return hnsw!.search(query, k);\n\t\t\tconst ranked = [...readMap(entries).values()]\n\t\t\t\t.map((row) => ({\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tscore: cosineSimilarity(query, row.vector),\n\t\t\t\t\tmeta: row.meta,\n\t\t\t\t}))\n\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t.slice(0, k);\n\t\t\treturn ranked;\n\t\t},\n\t};\n}\n\nexport function knowledgeGraph<TEntity, TRelation extends string = string>(\n\tname: string,\n): KnowledgeGraphGraph<TEntity, TRelation> {\n\tconst graph = new Graph(name);\n\tconst entities = state<ReadonlyMap<string, TEntity>>(new Map(), {\n\t\tname: \"entities\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst edges = state<ReadonlyArray<KnowledgeEdge<TRelation>>>([], {\n\t\tname: \"edges\",\n\t\tdescribeKind: \"state\",\n\t});\n\tconst adjacency = derived(\n\t\t[edges],\n\t\t([rows]) => {\n\t\t\tconst typed = (rows ?? []) as ReadonlyArray<KnowledgeEdge<TRelation>>;\n\t\t\tconst out = new Map<string, ReadonlyArray<KnowledgeEdge<TRelation>>>();\n\t\t\tfor (const edge of typed) {\n\t\t\t\tconst prev = out.get(edge.from) ?? [];\n\t\t\t\tout.set(edge.from, Object.freeze([...prev, edge]));\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t\t{ name: \"adjacency\", describeKind: \"derived\", initial: new Map() },\n\t);\n\tvoid adjacency.subscribe(() => undefined);\n\n\tgraph.add(\"entities\", entities);\n\tgraph.add(\"edges\", edges);\n\tgraph.add(\"adjacency\", adjacency);\n\n\tfunction commitEntities(next: Map<string, TEntity>): void {\n\t\tentities.down([[DATA, next]]);\n\t}\n\n\tfunction commitEdges(next: ReadonlyArray<KnowledgeEdge<TRelation>>): void {\n\t\tedges.down([[DATA, next]]);\n\t}\n\n\tconst out = Object.assign(graph, {\n\t\tupsertEntity(id: string, value: TEntity) {\n\t\t\tconst next = copyMap(readMap(entities));\n\t\t\tnext.set(id, value);\n\t\t\tcommitEntities(next);\n\t\t},\n\t\tremoveEntity(id: string) {\n\t\t\tconst nextEntities = copyMap(readMap(entities));\n\t\t\tconst existed = nextEntities.delete(id);\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst nextEdges = currentEdges.filter((edge) => edge.from !== id && edge.to !== id);\n\t\t\tif (!existed && nextEdges.length === currentEdges.length) return;\n\t\t\tcommitEntities(nextEntities);\n\t\t\tcommitEdges(nextEdges);\n\t\t},\n\t\tlink(from: string, to: string, relation: TRelation, weight = 1) {\n\t\t\tconst key = `${from}\\u0000${to}\\u0000${relation}`;\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst existing = new Set(\n\t\t\t\tcurrentEdges.map((edge) => `${edge.from}\\u0000${edge.to}\\u0000${edge.relation}`),\n\t\t\t);\n\t\t\tconst next = [...currentEdges];\n\t\t\tif (existing.has(key)) {\n\t\t\t\tfor (let i = 0; i < next.length; i += 1) {\n\t\t\t\t\tconst edge = next[i]!;\n\t\t\t\t\tif (edge.from === from && edge.to === to && edge.relation === relation) {\n\t\t\t\t\t\tnext[i] = { ...edge, weight };\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnext.push({ from, to, relation, weight });\n\t\t\t}\n\t\t\tcommitEdges(next);\n\t\t},\n\t\tunlink(from: string, to: string, relation?: TRelation) {\n\t\t\tconst currentEdges = readArray(edges);\n\t\t\tconst next = currentEdges.filter((edge) =>\n\t\t\t\trelation === undefined\n\t\t\t\t\t? !(edge.from === from && edge.to === to)\n\t\t\t\t\t: !(edge.from === from && edge.to === to && edge.relation === relation),\n\t\t\t);\n\t\t\tif (next.length === currentEdges.length) return;\n\t\t\tcommitEdges(next);\n\t\t},\n\t\trelated(id: string, relation?: TRelation): ReadonlyArray<KnowledgeEdge<TRelation>> {\n\t\t\treturn readArray(edges).filter(\n\t\t\t\t(edge) =>\n\t\t\t\t\t(edge.from === id || edge.to === id) &&\n\t\t\t\t\t(relation === undefined || edge.relation === relation),\n\t\t\t);\n\t\t},\n\t}) as KnowledgeGraphGraph<TEntity, TRelation>;\n\treturn out;\n}\n","/**\n * Messaging patterns (roadmap §4.2).\n *\n * Pulsar-inspired messaging features modeled as graph factories:\n * - `topic()` for append-only topic streams\n * - `subscription()` for cursor-based consumers\n * - `jobQueue()` for queue claim/ack flow\n */\n\nimport { batch, COMPLETE, DATA, derived, type Node, node, state } from \"../core/index.js\";\nimport { reactiveList } from \"../extra/reactive-list.js\";\nimport { reactiveLog } from \"../extra/reactive-log.js\";\nimport { reactiveMap } from \"../extra/reactive-map.js\";\nimport { Graph, type GraphOptions } from \"../graph/index.js\";\n\nconst DEFAULT_MAX_PER_PUMP = 2_147_483_647;\n\nfunction requireNonNegativeInt(value: number, label: string): number {\n\tif (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n\t\tthrow new Error(`${label} must be a non-negative integer`);\n\t}\n\treturn value;\n}\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction messagingMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"messaging\", kind, extra);\n}\n\nexport type TopicOptions = {\n\tgraph?: GraphOptions;\n\tretainedLimit?: number;\n};\n\nexport class TopicGraph<T> extends Graph {\n\tprivate readonly _log;\n\treadonly events: Node<readonly T[]>;\n\t/**\n\t * Most recently published value, or `null` when the topic has no entries\n\t * yet. Spec §5.12 reserves `undefined` as the protocol-internal \"never\n\t * sent DATA\" sentinel — `null` is the idiomatic \"empty / no value\" signal\n\t * for domain nodes. F7.\n\t *\n\t * **Caveat when `T` itself includes `null`** (e.g., `topic<number | null>`):\n\t * `latest === null` is ambiguous — it could mean \"no publish yet\" OR \"a\n\t * `null` value was published\". Use {@link hasLatest} to disambiguate, or\n\t * observe {@link events} directly and track length yourself.\n\t */\n\treadonly latest: Node<T | null>;\n\t/**\n\t * Reactive `true` once the topic has at least one published entry.\n\t * Disambiguates \"`null` never published\" from \"`null` was published\" when\n\t * `T` includes `null`.\n\t */\n\treadonly hasLatest: Node<boolean>;\n\n\tconstructor(name: string, opts: TopicOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._log = reactiveLog<T>([], { name: \"events\", maxSize: opts.retainedLimit });\n\t\tthis.events = this._log.entries;\n\t\tthis.add(\"events\", this.events);\n\t\tthis.latest = derived<T | null>(\n\t\t\t[this.events],\n\t\t\t([snapshot]) => {\n\t\t\t\tconst entries = snapshot as readonly T[];\n\t\t\t\treturn entries.length === 0 ? null : (entries[entries.length - 1] as T);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"latest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"topic_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"latest\", this.latest);\n\t\tthis.addDisposer(keepalive(this.latest));\n\n\t\tthis.hasLatest = derived<boolean>(\n\t\t\t[this.events],\n\t\t\t([snapshot]) => (snapshot as readonly T[]).length > 0,\n\t\t\t{\n\t\t\t\tname: \"hasLatest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"topic_has_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"hasLatest\", this.hasLatest);\n\t\tthis.addDisposer(keepalive(this.hasLatest));\n\n\t\t// D1(a): on teardown, propagate COMPLETE on `events` so downstream\n\t\t// derived chains (including any externally-held SubscriptionGraph\n\t\t// sources) see the termination via their `terminalDeps` and can stop\n\t\t// serving stale caches. Tier-3 terminal per spec §2.2.\n\t\tthis.addDisposer(() => {\n\t\t\tthis.events.down([[COMPLETE]]);\n\t\t});\n\t\t// P9: release any memoized tail/slice view keepalives held by the log.\n\t\t// TopicGraph itself doesn't call log.tail/slice, but plugins may have\n\t\t// attached views via `_log` — defensive.\n\t\tthis.addDisposer(() => this._log.disposeAllViews());\n\t}\n\n\tpublish(value: T): void {\n\t\tthis._log.append(value);\n\t}\n\n\tretained(): readonly T[] {\n\t\treturn this.events.cache as readonly T[];\n\t}\n}\n\nexport type SubscriptionOptions = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n};\n\nexport class SubscriptionGraph<T> extends Graph {\n\treadonly source: Node<readonly T[]>;\n\treadonly cursor: Node<number>;\n\treadonly available: Node<readonly T[]>;\n\t/**\n\t * Reference to the upstream topic graph. Intentionally NOT mounted\n\t * under this subscription: a subscription is a VIEW over an\n\t * externally-owned topic. Double-mounting (e.g. hub-owned topic +\n\t * sub-mount here) would make either-side teardown leave the other\n\t * holding a dead reference. Node-level `derived([topicEvents], …)`\n\t * still wires the data dependency across graph boundaries. D1(e).\n\t */\n\treadonly topic: TopicGraph<T>;\n\n\tconstructor(name: string, topicGraph: TopicGraph<T>, opts: SubscriptionOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst initialCursor = requireNonNegativeInt(opts.cursor ?? 0, \"subscription cursor\");\n\t\tthis.topic = topicGraph;\n\t\tconst topicEvents = topicGraph.events;\n\t\tthis.source = derived([topicEvents], ([snapshot]) => snapshot as readonly T[], {\n\t\t\tname: \"source\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: messagingMeta(\"subscription_source\"),\n\t\t\tinitial: topicEvents.cache as readonly T[],\n\t\t});\n\t\tthis.add(\"source\", this.source);\n\t\tthis.cursor = state(initialCursor, {\n\t\t\tname: \"cursor\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"subscription_cursor\"),\n\t\t});\n\t\tthis.add(\"cursor\", this.cursor);\n\t\tthis.available = derived(\n\t\t\t[this.source, this.cursor],\n\t\t\t([sourceSnapshot, cursor]) => {\n\t\t\t\tconst entries = sourceSnapshot as readonly T[];\n\t\t\t\tconst start = Math.max(0, Math.trunc((cursor as number) ?? 0));\n\t\t\t\treturn entries.slice(start);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"available\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"subscription_available\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tthis.add(\"available\", this.available);\n\t\t// No `connect(\"topic::events\", \"source\")` — topic is not mounted here.\n\t\t// The node-level dep `derived([topicEvents], …)` above is the live wire.\n\t\tthis.addDisposer(keepalive(this.source));\n\t\tthis.addDisposer(keepalive(this.available));\n\t}\n\n\tack(count?: number): number {\n\t\tconst available = this.available.cache as readonly T[];\n\t\tconst requested =\n\t\t\tcount === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(count, \"subscription ack count\");\n\t\tconst step = Math.min(requested, available.length);\n\t\tif (step <= 0) return this.cursor.cache as number;\n\t\tconst next = (this.cursor.cache as number) + step;\n\t\t// F8: use emit() so the pipeline auto-prefixes DIRTY, runs equals\n\t\t// substitution, and produces a proper two-phase wave (the raw\n\t\t// `down([[DATA, next]])` path bypassed those contracts).\n\t\tthis.cursor.emit(next);\n\t\treturn next;\n\t}\n\n\tpull(limit?: number, opts: { ack?: boolean } = {}): readonly T[] {\n\t\tconst available = this.available.cache as readonly T[];\n\t\tconst max =\n\t\t\tlimit === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(limit, \"subscription pull limit\");\n\t\tconst out = available.slice(0, max);\n\t\tif (opts.ack && out.length > 0) this.ack(out.length);\n\t\treturn out;\n\t}\n}\n\nexport type JobState = \"queued\" | \"inflight\";\n\nexport type JobEnvelope<T> = {\n\tid: string;\n\tpayload: T;\n\tattempts: number;\n\tmetadata: Readonly<Record<string, unknown>>;\n\tstate: JobState;\n};\n\nexport type JobQueueOptions = {\n\tgraph?: GraphOptions;\n};\n\nexport class JobQueueGraph<T> extends Graph {\n\tprivate readonly _pending;\n\tprivate readonly _jobs;\n\tprivate _seq = 0;\n\treadonly pending: Node<readonly string[]>;\n\treadonly jobs: Node<ReadonlyMap<string, JobEnvelope<T>>>;\n\treadonly depth: Node<number>;\n\n\tconstructor(name: string, opts: JobQueueOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._pending = reactiveList<string>([], { name: \"pending\" });\n\t\tthis._jobs = reactiveMap<string, JobEnvelope<T>>({ name: \"jobs\" });\n\t\tthis.pending = this._pending.items;\n\t\tthis.jobs = this._jobs.entries;\n\t\tthis.add(\"pending\", this.pending);\n\t\tthis.add(\"jobs\", this.jobs);\n\t\tthis.depth = derived([this.pending], ([snapshot]) => (snapshot as readonly string[]).length, {\n\t\t\tname: \"depth\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: messagingMeta(\"queue_depth\"),\n\t\t\tinitial: 0,\n\t\t});\n\t\tthis.add(\"depth\", this.depth);\n\t\tthis.addDisposer(keepalive(this.depth));\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\tconst id = opts.id ?? `${this.name}-${++this._seq}`;\n\t\tif (this._jobs.get(id) !== undefined) {\n\t\t\tthrow new Error(`jobQueue(\"${this.name}\"): duplicate job id \"${id}\"`);\n\t\t}\n\t\tconst job: JobEnvelope<T> = {\n\t\t\tid,\n\t\t\tpayload,\n\t\t\tattempts: 0,\n\t\t\tmetadata: Object.freeze({ ...(opts.metadata ?? {}) }),\n\t\t\tstate: \"queued\",\n\t\t};\n\t\tthis._jobs.set(id, job);\n\t\tthis._pending.append(id);\n\t\treturn id;\n\t}\n\n\tclaim(limit = 1): readonly JobEnvelope<T>[] {\n\t\tconst max = requireNonNegativeInt(limit, \"job queue claim limit\");\n\t\tif (max === 0) return [];\n\t\tconst out: JobEnvelope<T>[] = [];\n\t\twhile (out.length < max) {\n\t\t\tconst ids = this.pending.cache as readonly string[];\n\t\t\tif (ids.length === 0) break;\n\t\t\tconst id = this._pending.pop(0);\n\t\t\tconst job = this._jobs.get(id);\n\t\t\tif (!job || job.state !== \"queued\") continue;\n\t\t\tconst inflight: JobEnvelope<T> = {\n\t\t\t\t...job,\n\t\t\t\tstate: \"inflight\",\n\t\t\t\tattempts: job.attempts + 1,\n\t\t\t};\n\t\t\tthis._jobs.set(id, inflight);\n\t\t\tout.push(inflight);\n\t\t}\n\t\treturn out;\n\t}\n\n\tack(id: string): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n\n\tnack(id: string, opts: { requeue?: boolean } = {}): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tif (opts.requeue ?? true) {\n\t\t\tthis._jobs.set(id, { ...job, state: \"queued\" });\n\t\t\tthis._pending.append(id);\n\t\t\treturn true;\n\t\t}\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n}\n\nexport type JobFlowOptions = {\n\tgraph?: GraphOptions;\n\tstages?: readonly string[];\n\tmaxPerPump?: number;\n};\n\nexport class JobFlowGraph<T> extends Graph {\n\tprivate readonly _stageNames: readonly string[];\n\tprivate readonly _queues = new Map<string, JobQueueGraph<T>>();\n\tprivate readonly _completed;\n\treadonly completed: Node<readonly JobEnvelope<T>[]>;\n\treadonly completedCount: Node<number>;\n\n\tconstructor(name: string, opts: JobFlowOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst stages = (opts.stages ?? [\"incoming\", \"processing\", \"done\"]).map((v) => v.trim());\n\t\tif (stages.length < 2) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): requires at least 2 stages`);\n\t\t}\n\t\tconst unique = new Set(stages);\n\t\tif (unique.size !== stages.length) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): stage names must be unique`);\n\t\t}\n\t\tthis._stageNames = Object.freeze([...stages]);\n\t\tfor (const stage of this._stageNames) {\n\t\t\tconst q = jobQueue<T>(`${name}-${stage}`);\n\t\t\tthis._queues.set(stage, q);\n\t\t\tthis.mount(stage, q);\n\t\t}\n\t\tthis._completed = reactiveLog<JobEnvelope<T>>([], { name: \"completed\" });\n\t\tthis.completed = this._completed.entries;\n\t\tthis.add(\"completed\", this.completed);\n\t\tthis.completedCount = derived(\n\t\t\t[this.completed],\n\t\t\t([snapshot]) => (snapshot as readonly JobEnvelope<T>[]).length,\n\t\t\t{\n\t\t\t\tname: \"completedCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"job_flow_completed_count\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"completedCount\", this.completedCount);\n\t\tthis.addDisposer(keepalive(this.completedCount));\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"job flow maxPerPump\"),\n\t\t);\n\t\tfor (let i = 0; i < this._stageNames.length; i += 1) {\n\t\t\tconst stage = this._stageNames[i] as string;\n\t\t\tconst current = this.queue(stage);\n\t\t\tconst next =\n\t\t\t\ti + 1 < this._stageNames.length ? this.queue(this._stageNames[i + 1] as string) : null;\n\t\t\tconst pump = node<unknown>(\n\t\t\t\t[current.pending],\n\t\t\t\t() => {\n\t\t\t\t\tlet moved = 0;\n\t\t\t\t\twhile (moved < maxPerPump) {\n\t\t\t\t\t\tconst claim = current.claim(1);\n\t\t\t\t\t\tif (claim.length === 0) break;\n\t\t\t\t\t\tconst job = claim[0] as JobEnvelope<T>;\n\t\t\t\t\t\tif (!job) break;\n\t\t\t\t\t\tif (next) {\n\t\t\t\t\t\t\tnext.enqueue(job.payload, {\n\t\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\t\t...job.metadata,\n\t\t\t\t\t\t\t\t\tjob_flow_from: stage,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis._completed.append(job);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrent.ack(job.id);\n\t\t\t\t\t\tmoved += 1;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `pump_${stage}`,\n\t\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\t\tmeta: messagingMeta(\"job_flow_pump\"),\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.add(`pump_${stage}`, pump);\n\t\t\tthis.addDisposer(keepalive(pump));\n\t\t}\n\t}\n\n\tstages(): readonly string[] {\n\t\treturn this._stageNames;\n\t}\n\n\tqueue(stage: string): JobQueueGraph<T> {\n\t\tconst q = this._queues.get(stage);\n\t\tif (!q) throw new Error(`jobFlow(\"${this.name}\"): unknown stage \"${stage}\"`);\n\t\treturn q;\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\treturn this.queue(this._stageNames[0] as string).enqueue(payload, opts);\n\t}\n\n\tretainedCompleted(): readonly JobEnvelope<T>[] {\n\t\treturn this.completed.cache as readonly JobEnvelope<T>[];\n\t}\n}\n\nexport type TopicBridgeOptions<TIn, TOut> = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n\tmaxPerPump?: number;\n\tmap?: (value: TIn) => TOut | undefined;\n};\n\nexport class TopicBridgeGraph<TIn, TOut = TIn> extends Graph {\n\tprivate readonly _sourceSub;\n\tprivate readonly _target;\n\treadonly bridgedCount: Node<number>;\n\n\tconstructor(\n\t\tname: string,\n\t\tsourceTopic: TopicGraph<TIn>,\n\t\ttargetTopic: TopicGraph<TOut>,\n\t\topts: TopicBridgeOptions<TIn, TOut> = {},\n\t) {\n\t\tsuper(name, opts.graph);\n\t\tthis._sourceSub = subscription<TIn>(`${name}-subscription`, sourceTopic, {\n\t\t\tcursor: opts.cursor,\n\t\t});\n\t\tthis._target = targetTopic;\n\t\tthis.mount(\"subscription\", this._sourceSub);\n\t\tthis.bridgedCount = state(0, {\n\t\t\tname: \"bridgedCount\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"topic_bridge_count\"),\n\t\t});\n\t\tthis.add(\"bridgedCount\", this.bridgedCount);\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"topic bridge maxPerPump\"),\n\t\t);\n\t\tconst mapValue = opts.map ?? ((value: TIn) => value as unknown as TOut);\n\t\tconst pump = node<unknown>(\n\t\t\t[this._sourceSub.available],\n\t\t\t() => {\n\t\t\t\tconst available = this._sourceSub.pull(maxPerPump, { ack: true });\n\t\t\t\tif (available.length === 0) return;\n\t\t\t\tlet bridged = 0;\n\t\t\t\tfor (const value of available) {\n\t\t\t\t\tconst mapped = mapValue(value as TIn);\n\t\t\t\t\tif (mapped === undefined) continue;\n\t\t\t\t\tthis._target.publish(mapped);\n\t\t\t\t\tbridged += 1;\n\t\t\t\t}\n\t\t\t\tif (bridged > 0) {\n\t\t\t\t\tconst current = this.bridgedCount.cache as number;\n\t\t\t\t\tthis.bridgedCount.down([[DATA, current + bridged]]);\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"pump\",\n\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\tmeta: messagingMeta(\"topic_bridge_pump\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"pump\", pump);\n\t\tthis.addDisposer(keepalive(pump));\n\t}\n}\n\n// ── MessagingHubGraph ─────────────────────────────────────────────────────\n\nexport type MessagingHubOptions = {\n\tgraph?: GraphOptions;\n\t/**\n\t * Default `TopicOptions` applied to every topic created via `topic(name)`\n\t * without explicit options. Per-call opts override. Default: `{}`\n\t * (unbounded retention per topic unless `retainedLimit` is set per call).\n\t */\n\tdefaultTopicOptions?: TopicOptions;\n};\n\n/**\n * Lazy Pulsar-inspired topic registry. Manages a named set of {@link TopicGraph}\n * instances with retention + cursor semantics. Topics are created on first\n * access; `removeTopic(name)` unmounts and tears down via {@link Graph.remove}.\n *\n * **Relationship to `pubsub()` in `src/extra/pubsub.ts`:** `pubsub` is a\n * lightweight last-value state hub (no retention, no cursors). `MessagingHubGraph`\n * is the full messaging hub — retained message logs, cursor-based subscriptions,\n * and pattern-layer lifecycle management.\n *\n * @category patterns\n */\nexport class MessagingHubGraph extends Graph {\n\tprivate readonly _topics = new Map<string, TopicGraph<unknown>>();\n\tprivate _version = 0;\n\tprivate readonly _defaultTopicOptions: TopicOptions;\n\n\tconstructor(name: string, opts: MessagingHubOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\t// P8: shallow-copy caller-provided defaults so post-construction\n\t\t// mutations by the caller don't leak into every future `topic()` call.\n\t\tthis._defaultTopicOptions = { ...(opts.defaultTopicOptions ?? {}) };\n\t}\n\n\t/** Monotonic counter advancing on topic create/remove. */\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\t/** Number of topics currently in the hub. */\n\tget size(): number {\n\t\treturn this._topics.size;\n\t}\n\n\t/** Checks topic existence without creating. */\n\thas(name: string): boolean {\n\t\treturn this._topics.has(name);\n\t}\n\n\t/** Iterator over topic names. */\n\ttopicNames(): IterableIterator<string> {\n\t\treturn this._topics.keys();\n\t}\n\n\t/**\n\t * Returns the {@link TopicGraph} for `name`, creating lazily on first call.\n\t * Subsequent calls with the same name return the same instance (options on\n\t * repeat calls are ignored — the topic is already configured).\n\t */\n\ttopic<T = unknown>(name: string, opts?: TopicOptions): TopicGraph<T> {\n\t\tlet t = this._topics.get(name) as TopicGraph<T> | undefined;\n\t\tif (t === undefined) {\n\t\t\tconst effective: TopicOptions = { ...this._defaultTopicOptions, ...(opts ?? {}) };\n\t\t\tt = new TopicGraph<T>(name, effective);\n\t\t\tthis._topics.set(name, t as TopicGraph<unknown>);\n\t\t\tthis.mount(name, t);\n\t\t\tthis._version += 1;\n\t\t}\n\t\treturn t;\n\t}\n\n\t/**\n\t * Publishes a value to the topic, lazily creating it on first publish.\n\t *\n\t * **Late-subscriber caveat:** the topic is created lazily, so subscribers\n\t * that attach AFTER a publish only see the retained window (governed by\n\t * `retainedLimit` on `TopicOptions` / `defaultTopicOptions`). If\n\t * `retainedLimit === 0` is set explicitly, early publishes are\n\t * effectively dropped — prefer an unset `retainedLimit` (unbounded\n\t * retention) or subscribe before publishing when late-subscribers matter.\n\t */\n\tpublish<T = unknown>(name: string, value: T): void {\n\t\tthis.topic<T>(name).publish(value);\n\t}\n\n\t/**\n\t * Bulk publish — issues all publishes inside one outer batch. New topics\n\t * are created on demand. No-op if `entries` yields nothing.\n\t *\n\t * **Iterable consumption (F6):** `entries` is consumed once (single-pass)\n\t * INSIDE the batch frame. If the iterator throws mid-way, the batch is\n\t * discarded and NO publishes are visible to subscribers (all-or-nothing).\n\t * Pass an array or `Set` for multi-shot callers.\n\t */\n\tpublishMany(entries: Iterable<[string, unknown]>): void {\n\t\t// P2: iterate inside batch — no `[...entries]` materialization so large\n\t\t// / infinite iterables don't OOM, and iterator throws are contained.\n\t\tbatch(() => {\n\t\t\tfor (const [name, value] of entries) {\n\t\t\t\tthis.topic(name).publish(value);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Creates a {@link SubscriptionGraph} over a named topic. The topic is\n\t * lazily created if missing. Subscription lifecycle is owned by the caller —\n\t * the hub does NOT mount the subscription.\n\t *\n\t * @param subName - Local name for the subscription graph.\n\t * @param topicName - Hub topic to subscribe to.\n\t * @param opts - `SubscriptionOptions` (initial cursor, etc.).\n\t */\n\tsubscribe<T = unknown>(\n\t\tsubName: string,\n\t\ttopicName: string,\n\t\topts?: SubscriptionOptions,\n\t): SubscriptionGraph<T> {\n\t\tconst t = this.topic<T>(topicName);\n\t\treturn new SubscriptionGraph<T>(subName, t, opts);\n\t}\n\n\t/**\n\t * Unmounts and tears down the topic's graph. Returns `true` if the topic\n\t * existed. Subscribers receive `TEARDOWN` via {@link Graph.remove}.\n\t */\n\tremoveTopic(name: string): boolean {\n\t\tif (!this._topics.has(name)) return false;\n\t\t// P1 / P3: Graph.remove first — if it throws, `_topics` must NOT still\n\t\t// hold the broken half-disposed topic (otherwise the next\n\t\t// `hub.topic(name)` returns the corrupted reference). Wrap in\n\t\t// try/finally so `_topics` / `_version` converge to a consistent state\n\t\t// regardless of whether `remove` throws. Mount-orphan safety is\n\t\t// preserved by removing before deleting.\n\t\ttry {\n\t\t\tthis.remove(name); // unmounts, drops edges, tears down\n\t\t} finally {\n\t\t\tthis._topics.delete(name);\n\t\t\tthis._version += 1;\n\t\t}\n\t\treturn true;\n\t}\n}\n\n/**\n * Creates a Pulsar-inspired topic graph (append-only retained stream + latest value).\n */\nexport function topic<T>(name: string, opts?: TopicOptions): TopicGraph<T> {\n\treturn new TopicGraph<T>(name, opts);\n}\n\n/**\n * Creates a lazy Pulsar-inspired messaging hub. Topics are created on first access\n * via `hub.topic(name)`; `hub.publish(name, value)` shortcuts through the registry.\n *\n * @example\n * ```ts\n * import { messagingHub } from \"@graphrefly/graphrefly-ts\";\n *\n * const hub = messagingHub(\"main\", { defaultTopicOptions: { retainedLimit: 256 } });\n * hub.publish(\"orders\", { id: 1 });\n * hub.publishMany([[\"shipments\", { id: 1 }], [\"orders\", { id: 2 }]]);\n * const sub = hub.subscribe(\"orders-worker\", \"orders\", { cursor: 0 });\n * ```\n */\nexport function messagingHub(name: string, opts?: MessagingHubOptions): MessagingHubGraph {\n\treturn new MessagingHubGraph(name, opts);\n}\n\n/**\n * Creates a cursor-based subscription graph over a topic.\n */\nexport function subscription<T>(\n\tname: string,\n\ttopicGraph: TopicGraph<T>,\n\topts?: SubscriptionOptions,\n): SubscriptionGraph<T> {\n\treturn new SubscriptionGraph<T>(name, topicGraph, opts);\n}\n\n/**\n * Creates a Pulsar-inspired job queue graph with claim/ack/nack workflow.\n */\nexport function jobQueue<T>(name: string, opts?: JobQueueOptions): JobQueueGraph<T> {\n\treturn new JobQueueGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous multi-stage queue chain graph.\n */\nexport function jobFlow<T>(name: string, opts?: JobFlowOptions): JobFlowGraph<T> {\n\treturn new JobFlowGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous cursor-based topic relay graph.\n */\nexport function topicBridge<TIn, TOut = TIn>(\n\tname: string,\n\tsourceTopic: TopicGraph<TIn>,\n\ttargetTopic: TopicGraph<TOut>,\n\topts?: TopicBridgeOptions<TIn, TOut>,\n): TopicBridgeGraph<TIn, TOut> {\n\treturn new TopicBridgeGraph<TIn, TOut>(name, sourceTopic, targetTopic, opts);\n}\n","/**\n * Orchestration patterns (roadmap §4.1).\n *\n * Domain-layer helpers that build workflow shapes on top of core + extra primitives.\n * Exported under the `patterns.orchestration` namespace to avoid collisions with\n * Phase 2 operator names (for example `gate`, `forEach`).\n */\n\nimport { batch } from \"../core/batch.js\";\nimport type { NodeActions } from \"../core/config.js\";\nimport { COMPLETE, DATA, ERROR, type Messages, RESOLVED } from \"../core/messages.js\";\nimport { type Node, type NodeFn, type NodeOptions, node } from \"../core/node.js\";\nimport { type DerivedFn, derived, state } from \"../core/sugar.js\";\nimport { GRAPH_META_SEGMENT, Graph, type GraphOptions } from \"../graph/graph.js\";\n\nexport type StepRef = string | Node<unknown>;\n\ntype OrchestrationMeta = {\n\torchestration?: true;\n\torchestration_type?: string;\n};\n\nexport type OrchestrationStepOptions = Omit<\n\tNodeOptions<unknown>,\n\t\"describeKind\" | \"name\" | \"meta\"\n> & {\n\tdeps?: ReadonlyArray<StepRef>;\n\tmeta?: Record<string, unknown> & OrchestrationMeta;\n};\n\nexport type BranchResult<T> = {\n\tbranch: \"then\" | \"else\";\n\tvalue: T;\n};\n\nexport type SensorControls<T> = {\n\tnode: Node<T>;\n\tpush(value: T): void;\n\terror(err: unknown): void;\n\tcomplete(): void;\n};\n\nexport type LoopOptions = Omit<OrchestrationStepOptions, \"deps\"> & {\n\titerations?: number | StepRef;\n};\n\nexport type WaitOptions = Omit<OrchestrationStepOptions, \"deps\">;\n\nexport type SubPipelineBuilder = (sub: Graph) => void;\n\nfunction resolveDep(graph: Graph, dep: StepRef): { node: Node<unknown>; path?: string } {\n\tif (typeof dep === \"string\") {\n\t\treturn { node: graph.resolve(dep), path: dep };\n\t}\n\tconst path = findRegisteredNodePath(graph, dep);\n\tif (!path) {\n\t\tthrow new Error(\n\t\t\t\"orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first\",\n\t\t);\n\t}\n\treturn { node: dep, path };\n}\n\nfunction findRegisteredNodePath(graph: Graph, target: Node<unknown>): string | undefined {\n\tconst described = graph.describe();\n\tconst metaSegment = `::${GRAPH_META_SEGMENT}::`;\n\tfor (const path of Object.keys(described.nodes).sort()) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\ttry {\n\t\t\tif (graph.resolve(path) === target) return path;\n\t\t} catch {\n\t\t\t/* ignore stale path while scanning */\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction registerStep(\n\tgraph: Graph,\n\tname: string,\n\tstep: Node<unknown>,\n\tdepPaths: ReadonlyArray<string>,\n): void {\n\tgraph.add(name, step);\n\t// depPaths used to drive graph.connect() edge-registry calls; after\n\t// Unit 7 edges are derived from node _deps and this wiring is a no-op.\n\tvoid depPaths;\n}\n\nimport { domainMeta } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"orchestration\", kind, meta);\n}\n\nfunction coerceLoopIterations(raw: unknown): number {\n\tconst parseString = (value: string): number => {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed.length === 0) return 0;\n\t\treturn Number(trimmed);\n\t};\n\tlet parsed: number;\n\tif (typeof raw === \"string\") {\n\t\tparsed = parseString(raw);\n\t} else if (raw === null) {\n\t\tparsed = 0;\n\t} else {\n\t\tparsed = Number(raw);\n\t}\n\tif (!Number.isFinite(parsed)) return 1;\n\treturn Math.max(0, Math.trunc(parsed));\n}\n\n/**\n * Creates an orchestration graph container.\n */\nexport function pipeline(name: string, opts?: GraphOptions): Graph {\n\treturn new Graph(name, opts);\n}\n\n/**\n * Registers a workflow task node.\n */\nexport function task<T>(\n\tgraph: Graph,\n\tname: string,\n\trun: DerivedFn<T>,\n\topts?: OrchestrationStepOptions,\n): Node<T> {\n\tconst depRefs = opts?.deps ?? [];\n\tconst deps = depRefs.map((dep) => resolveDep(graph, dep));\n\tconst { deps: _deps, ...nodeOpts } = opts ?? {};\n\tconst wrapped: NodeFn = (batchData, actions, ctx) => {\n\t\tconst data = batchData.map((batch, i) =>\n\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t);\n\t\tactions.emit(run(data, ctx));\n\t\treturn undefined;\n\t};\n\tconst step = node<T>(\n\t\tdeps.map((d) => d.node),\n\t\twrapped,\n\t\t{\n\t\t\t...nodeOpts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"task\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\tdeps.flatMap((d) => (d.path ? [d.path] : [])),\n\t);\n\treturn step;\n}\n\n/**\n * Emits tagged branch outcomes (`then` / `else`) for each source value.\n */\nexport function branch<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tpredicate: (value: T) => boolean,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<BranchResult<T>> {\n\tconst src = resolveDep(graph, source);\n\tconst step = derived<BranchResult<T>>(\n\t\t[src.node],\n\t\t([value]) => ({\n\t\t\tbranch: predicate(value as T) ? \"then\" : \"else\",\n\t\t\tvalue: value as T,\n\t\t}),\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tmeta: baseMeta(\"branch\", opts?.meta),\n\t\t} as NodeOptions<BranchResult<T>>,\n\t);\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n\n/**\n * Forwards source values only while `control` is truthy.\n */\nexport function valve<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tcontrol: StepRef,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst ctrl = resolveDep(graph, control);\n\t// Raw node so we can emit RESOLVED (hold) instead of DATA(undefined) when closed.\n\tconst step = node<T>(\n\t\t[src.node, ctrl.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst batch0 = batchData[0];\n\t\t\tconst batch1 = batchData[1];\n\t\t\t// undefined = control never sent DATA (closed); falsy = explicitly closed.\n\t\t\tconst ctrlVal = batch1 != null && batch1.length > 0 ? batch1.at(-1) : ctx.prevData[1];\n\t\t\t// Control just opened and no new source data this wave: re-emit last source value.\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\tif (batch1 != null && batch1.length > 0 && ctrlVal && ctx.prevData[0] !== undefined) {\n\t\t\t\t\tactions.emit(ctx.prevData[0] as T);\n\t\t\t\t} else {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!ctrlVal) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) actions.emit(v);\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"valve\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, ctrl.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\nexport type ApprovalOptions = Omit<OrchestrationStepOptions, \"deps\"> & {\n\tisApproved?: (value: unknown) => boolean;\n};\n\n/**\n * Human/LLM approval gate over a source value.\n */\nexport function approval<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tapprover: StepRef,\n\topts?: ApprovalOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst ctrl = resolveDep(graph, approver);\n\tconst isApproved = opts?.isApproved ?? ((value: unknown) => Boolean(value));\n\t// Raw node so we can emit RESOLVED (hold) instead of DATA(undefined) when not approved.\n\tconst step = node<T>(\n\t\t[src.node, ctrl.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst batch0 = batchData[0];\n\t\t\tconst batch1 = batchData[1];\n\t\t\t// undefined = approver never sent DATA (not yet approved).\n\t\t\tconst ctrlVal = batch1 != null && batch1.length > 0 ? batch1.at(-1) : ctx.prevData[1];\n\t\t\tif (ctrlVal === undefined || !isApproved(ctrlVal)) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\t// Approval just granted and no new source data: re-emit last source value.\n\t\t\t\tif (batch1 != null && batch1.length > 0 && ctx.prevData[0] !== undefined) {\n\t\t\t\t\tactions.emit(ctx.prevData[0] as T);\n\t\t\t\t} else {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) actions.emit(v);\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"approval\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, ctrl.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\n// ---------------------------------------------------------------------------\n// gate — human-in-the-loop approval with pending queue\n// ---------------------------------------------------------------------------\n\nexport interface GateOptions {\n\t/** Maximum queue size. Oldest values are FIFO-dropped when exceeded. Default: Infinity. */\n\tmaxPending?: number;\n\t/** Start in open mode (auto-approve). Default: false. */\n\tstartOpen?: boolean;\n\tmeta?: Record<string, unknown>;\n}\n\n/** Control surface returned by {@link gate}. */\nexport interface GateController<T> {\n\t/** The output node registered in the graph (subscribe to receive approved values). */\n\tnode: Node<T>;\n\t/** Reactive queue of values waiting for approval. */\n\tpending: Node<T[]>;\n\t/** Derived count of pending items. */\n\tcount: Node<number>;\n\t/** Whether the gate is currently open (auto-approving). */\n\tisOpen: Node<boolean>;\n\t/** Approve and forward the next `count` pending values (default: 1). */\n\tapprove(count?: number): void;\n\t/** Reject (discard) the next `count` pending values (default: 1). */\n\treject(count?: number): void;\n\t/**\n\t * Transform and forward `count` pending values (default: 1).\n\t * `fn` receives `(value, index, pending)` — Array.map-style.\n\t */\n\tmodify(fn: (value: T, index: number, pending: readonly T[]) => T, count?: number): void;\n\t/** Flush all pending values and auto-approve future values. */\n\topen(): void;\n\t/** Re-enable manual gating (stop auto-approving). */\n\tclose(): void;\n}\n\n/**\n * Human-in-the-loop gate: queues incoming values from `source` and lets an external\n * controller {@link GateController.approve approve}, {@link GateController.reject reject},\n * or {@link GateController.modify modify} them before forwarding downstream.\n *\n * Observable surfaces (`pending`, `count`, `isOpen`) are reactive nodes registered in\n * the graph. The gate output node is also registered.\n */\nexport function gate<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\topts?: GateOptions,\n): GateController<T> {\n\tconst maxPending = opts?.maxPending ?? Infinity;\n\tif (maxPending < 1 && maxPending !== Infinity) {\n\t\tthrow new RangeError(\"gate: maxPending must be >= 1\");\n\t}\n\tconst startOpen = opts?.startOpen ?? false;\n\n\tconst src = resolveDep(graph, source);\n\n\t// Internal reactive state\n\tconst pendingNode = state<T[]>([], { name: \"pending\", equals: () => false });\n\tconst isOpenNode = state<boolean>(startOpen, { name: \"isOpen\" });\n\tconst countNode = derived<number>([pendingNode], ([arr]) => (arr as T[]).length, {\n\t\tname: \"count\",\n\t});\n\n\tlet queue: T[] = [];\n\tlet torn = false;\n\t// Capture `isOpenNode` DATA into a closure variable fed by its own subscribe\n\t// handler. The output producer consults `latestIsOpen` instead of reading\n\t// `isOpenNode.cache` from inside its callback — keeps the gate decision on\n\t// the protocol delivery path (P3 audit #11). Seeded with `startOpen` at\n\t// wiring time so the first item arriving before any open()/close() uses\n\t// the same value the state node was constructed with. Same template as\n\t// the `stratify` rule-capture pattern.\n\tlet latestIsOpen = startOpen;\n\tconst isOpenUnsub = isOpenNode.subscribe((msgs) => {\n\t\tfor (const m of msgs) {\n\t\t\tif (m[0] === DATA) latestIsOpen = m[1] as boolean;\n\t\t}\n\t});\n\n\tfunction syncPending(): void {\n\t\tpendingNode.down([[DATA, [...queue]]]);\n\t}\n\n\tfunction enqueue(value: T): void {\n\t\tqueue.push(value);\n\t\tif (queue.length > maxPending) queue.shift();\n\t\tsyncPending();\n\t}\n\n\tfunction dequeue(n: number): T[] {\n\t\tconst items = queue.splice(0, n);\n\t\tsyncPending();\n\t\treturn items;\n\t}\n\n\tfunction guardTorn(method: string): void {\n\t\tif (torn) throw new Error(`gate: ${method}() called after gate was torn down`);\n\t}\n\n\tconst output = node<T>(\n\t\t[src.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst terminal = ctx.terminalDeps[0];\n\t\t\tif (terminal !== undefined) {\n\t\t\t\ttorn = true;\n\t\t\t\tqueue = [];\n\t\t\t\tsyncPending();\n\t\t\t\tactions.down(terminal === true ? [[COMPLETE]] : [[ERROR, terminal]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst batch0 = batchData[0];\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) {\n\t\t\t\tif (latestIsOpen) {\n\t\t\t\t\tactions.emit(v);\n\t\t\t\t} else {\n\t\t\t\t\tenqueue(v);\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"gate\", opts?.meta),\n\t\t},\n\t);\n\n\tconst controller: GateController<T> = {\n\t\tnode: output,\n\t\tpending: pendingNode,\n\t\tcount: countNode,\n\t\tisOpen: isOpenNode,\n\t\tapprove(count = 1) {\n\t\t\tguardTorn(\"approve\");\n\t\t\tconst items = dequeue(count);\n\t\t\tfor (const item of items) {\n\t\t\t\tif (torn) break;\n\t\t\t\toutput.down([[DATA, item]]);\n\t\t\t}\n\t\t},\n\t\treject(count = 1) {\n\t\t\tguardTorn(\"reject\");\n\t\t\tdequeue(count);\n\t\t},\n\t\tmodify(fn, count = 1) {\n\t\t\tguardTorn(\"modify\");\n\t\t\tconst snapshot = [...queue] as readonly T[];\n\t\t\tconst items = dequeue(count);\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\tif (torn) break;\n\t\t\t\toutput.down([[DATA, fn(items[i], i, snapshot)]]);\n\t\t\t}\n\t\t},\n\t\topen() {\n\t\t\tguardTorn(\"open\");\n\t\t\t// Wrap the isOpen transition + queued flush in one batch so every\n\t\t\t// `output.down` is tier-3-deferred until after the `isOpenNode` dep\n\t\t\t// wave settles. Without this, queued DATAs could interleave with\n\t\t\t// the in-flight isOpen settlement wave under async runners — item\n\t\t\t// order relative to the open signal would be non-deterministic.\n\t\t\tbatch(() => {\n\t\t\t\tisOpenNode.down([[DATA, true]]);\n\t\t\t\tconst items = dequeue(queue.length);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tif (torn) break;\n\t\t\t\t\toutput.down([[DATA, item]]);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tguardTorn(\"close\");\n\t\t\tisOpenNode.down([[DATA, false]]);\n\t\t},\n\t};\n\n\t// Activate count so it stays reactive\n\tgraph.addDisposer(countNode.subscribe(() => undefined));\n\t// Tear down the isOpen capture when the owning graph disposes.\n\tgraph.addDisposer(isOpenUnsub);\n\n\t// Register output + internal state as a mounted subgraph (aligned with PY)\n\tregisterStep(graph, name, output as unknown as Node<unknown>, src.path ? [src.path] : []);\n\tconst internal = new Graph(`${name}_state`);\n\tinternal.add(\"pending\", pendingNode);\n\tinternal.add(\"isOpen\", isOpenNode);\n\tinternal.add(\"count\", countNode);\n\tgraph.mount(`${name}_state`, internal);\n\n\treturn controller;\n}\n\n/**\n * Registers a workflow side-effect step that runs `run` for each upstream\n * DATA value.\n *\n * `run` receives the full `NodeActions` and is the **sole emission point** —\n * call `actions.emit(v)` or `actions.down(msgs)` inside `run` to produce\n * downstream output. If `run` does not emit, this step acts as a pure\n * side-effect sink (graph-observable but no output). Throwing inside `run`\n * terminates the step with ERROR.\n */\nexport function forEach<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\trun: (value: T, actions: NodeActions) => void,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tlet terminated = false;\n\tconst step = node<T>(\n\t\t[src.node],\n\t\t(batchData, actions, ctx) => {\n\t\t\tif (terminated) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Terminal from dep\n\t\t\tconst terminal = ctx.terminalDeps[0];\n\t\t\tif (terminal !== undefined) {\n\t\t\t\tterminated = true;\n\t\t\t\tactions.down(terminal === true ? [[COMPLETE]] : [[ERROR, terminal]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst batch0 = batchData[0];\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0 as T[]) {\n\t\t\t\ttry {\n\t\t\t\t\trun(v, actions);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tterminated = true;\n\t\t\t\t\tactions.down([[ERROR, err]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"effect\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tmeta: baseMeta(\"forEach\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\t// registerStep registers the edge for graph visibility. g.connect's dedup\n\t// check skips _addDep since src.node is already a constructor dep.\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n\n/**\n * Registers a join step that emits a tuple of latest dependency values.\n */\nexport function join<T extends readonly unknown[]>(\n\tgraph: Graph,\n\tname: string,\n\tdeps: { [K in keyof T]: StepRef },\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst resolved = deps.map((dep) => resolveDep(graph, dep));\n\tconst step = derived<T>(\n\t\tresolved.map((d) => d.node),\n\t\t(values) => values as T,\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tmeta: baseMeta(\"join\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\tresolved.flatMap((d) => (d.path ? [d.path] : [])),\n\t);\n\treturn step;\n}\n\n/**\n * Registers a loop step that applies `iterate` to each source value N times.\n */\nexport function loop<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\titerate: (value: T, iteration: number, actions: NodeActions) => T,\n\topts?: LoopOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst iterRef = opts?.iterations;\n\tconst iterDep =\n\t\ttypeof iterRef === \"number\" || iterRef === undefined ? undefined : resolveDep(graph, iterRef);\n\tconst staticIterations = typeof iterRef === \"number\" ? iterRef : undefined;\n\tconst step = node<T>(\n\t\titerDep ? [src.node, iterDep.node] : [src.node],\n\t\t(depValues, actions, ctx) => {\n\t\t\tconst batch0 = depValues[0];\n\t\t\tlet current = (batch0 != null && batch0.length > 0 ? batch0.at(-1) : ctx.prevData[0]) as T;\n\t\t\tconst batch1 = iterDep ? depValues[1] : undefined;\n\t\t\tconst rawCount =\n\t\t\t\tstaticIterations ??\n\t\t\t\t(iterDep ? (batch1 != null && batch1.length > 0 ? batch1.at(-1) : ctx.prevData[1]) : 1);\n\t\t\tconst count = coerceLoopIterations(rawCount);\n\t\t\tfor (let i = 0; i < count; i += 1) {\n\t\t\t\tcurrent = iterate(current, i, actions);\n\t\t\t}\n\t\t\tactions.emit(current);\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"loop\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(\n\t\tgraph,\n\t\tname,\n\t\tstep as unknown as Node<unknown>,\n\t\t[src.path, iterDep?.path].filter((v): v is string => typeof v === \"string\"),\n\t);\n\treturn step;\n}\n\n/**\n * Mounts and returns a child workflow graph.\n */\nexport function subPipeline(\n\tgraph: Graph,\n\tname: string,\n\tchildOrBuild?: Graph | SubPipelineBuilder,\n\topts?: GraphOptions,\n): Graph {\n\tconst child = childOrBuild instanceof Graph ? childOrBuild : pipeline(name, opts);\n\tif (typeof childOrBuild === \"function\") {\n\t\tchildOrBuild(child);\n\t}\n\tgraph.mount(name, child);\n\treturn child;\n}\n\n/**\n * Registers a producer-style sensor source and returns imperative controls.\n */\nexport function sensor<T>(\n\tgraph: Graph,\n\tname: string,\n\tinitial?: T,\n\topts?: Omit<NodeOptions<unknown>, \"name\" | \"describeKind\" | \"meta\"> & {\n\t\tmeta?: Record<string, unknown>;\n\t},\n): SensorControls<T> {\n\tconst source = node<T>([], () => undefined, {\n\t\t...opts,\n\t\tname,\n\t\tinitial,\n\t\tdescribeKind: \"producer\",\n\t\tmeta: baseMeta(\"sensor\", opts?.meta),\n\t});\n\tregisterStep(graph, name, source as unknown as Node<unknown>, []);\n\treturn {\n\t\tnode: source,\n\t\tpush(value: T) {\n\t\t\tsource.down([[DATA, value]] satisfies Messages);\n\t\t},\n\t\terror(err: unknown) {\n\t\t\tsource.down([[ERROR, err]] satisfies Messages);\n\t\t},\n\t\tcomplete() {\n\t\t\tsource.down([[COMPLETE]] satisfies Messages);\n\t\t},\n\t};\n}\n\n/**\n * Registers a delayed-forwarding step (value-level wait).\n */\nexport function wait<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\tms: number,\n\topts?: WaitOptions,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tconst timers = new Set<ReturnType<typeof setTimeout>>();\n\tlet terminated = false;\n\tlet completed = false;\n\n\tfunction clearAllTimers(): void {\n\t\tfor (const id of timers) clearTimeout(id);\n\t\ttimers.clear();\n\t}\n\n\t// Producer pattern: 0 deps, manual subscribe to source.\n\t// Under Model B (push-on-subscribe) the fn runs eagerly via _startProducer,\n\t// ensuring the cleanup is registered and timers are cleared on teardown.\n\t// Only set initial if source has a real cached value (not SENTINEL/undefined).\n\tconst srcVal = src.node.cache;\n\tconst initialOpt = srcVal !== undefined ? { initial: srcVal as T } : {};\n\n\tconst step = node<T>(\n\t\t[],\n\t\t(_deps, actions) => {\n\t\t\tclearAllTimers();\n\t\t\tterminated = false;\n\t\t\tcompleted = false;\n\t\t\tconst unsub = src.node.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (terminated) return;\n\t\t\t\t\tif (msg[0] === DATA) {\n\t\t\t\t\t\tconst id = setTimeout(() => {\n\t\t\t\t\t\t\ttimers.delete(id);\n\t\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t\t\tif (completed && timers.size === 0) {\n\t\t\t\t\t\t\t\tactions.down([[COMPLETE]] satisfies Messages);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}, ms);\n\t\t\t\t\t\ttimers.add(id);\n\t\t\t\t\t} else if (msg[0] === COMPLETE) {\n\t\t\t\t\t\tterminated = true;\n\t\t\t\t\t\tcompleted = true;\n\t\t\t\t\t\tif (timers.size === 0) {\n\t\t\t\t\t\t\tactions.down([[COMPLETE]] satisfies Messages);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (msg[0] === ERROR) {\n\t\t\t\t\t\tterminated = true;\n\t\t\t\t\t\tclearAllTimers();\n\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsub();\n\t\t\t\tclearAllTimers();\n\t\t\t\tterminated = true;\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\t...initialOpt,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tmeta: baseMeta(\"wait\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\t// Producer pattern: register in graph without dep edges (manual subscription).\n\t// Post edge-registry deletion (Unit 7), edges are derived from node `_deps`\n\t// exclusively; this producer's logical dep on `src` is not reflected in\n\t// `describe()` — by design, since there is no real constructor-time\n\t// dependency to show.\n\tgraph.add(name, step as unknown as Node<unknown>);\n\treturn step;\n}\n\n/**\n * Registers an error-recovery step for a source.\n */\nexport function onFailure<T>(\n\tgraph: Graph,\n\tname: string,\n\tsource: StepRef,\n\trecover: (err: unknown, actions: NodeActions) => T,\n\topts?: Omit<OrchestrationStepOptions, \"deps\">,\n): Node<T> {\n\tconst src = resolveDep(graph, source);\n\tlet terminated = false;\n\t// Producer pattern: manually subscribe to source for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\tconst step = node<T>(\n\t\t[],\n\t\t(_data, actions) => {\n\t\t\tconst unsub = src.node.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tif (terminated) return;\n\t\t\t\t\tif (msg[0] === ERROR) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tactions.emit(recover(msg[1], actions));\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tterminated = true;\n\t\t\t\t\t\t\tactions.down([[ERROR, err]] satisfies Messages);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tactions.down([msg] satisfies Messages);\n\t\t\t\t\t\tif (msg[0] === COMPLETE) terminated = true;\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\t{\n\t\t\t...opts,\n\t\t\tname,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t// onFailure handles errors via manual subscription (recover callback).\n\t\t\t// Disable auto-propagation so dep-channel ERROR doesn't terminate this\n\t\t\t// node before the recover callback has a chance to emit a replacement value.\n\t\t\terrorWhenDepsError: false,\n\t\t\tmeta: baseMeta(\"onFailure\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\tregisterStep(graph, name, step as unknown as Node<unknown>, src.path ? [src.path] : []);\n\treturn step;\n}\n","/**\n * Three-pane demo shell (roadmap §7.2).\n *\n * A `Graph(\"demo-shell\")` that dogfoods reactive coordination for the\n * main/side split layout with synchronized cross-highlighting.\n *\n * **Zero framework dependency** — framework bindings wrap pane components only.\n * The shell graph is headless and fully testable.\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { describeNode, resolveDescribeFields } from \"../core/meta.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { Graph } from \"../graph/graph.js\";\nimport type { MeasurementAdapter } from \"./reactive-layout/reactive-layout.js\";\nimport { analyzeAndMeasure, computeLineBreaks } from \"./reactive-layout/reactive-layout.js\";\n\n// ——————————————————————————————————————————————————————————\n// Types\n// ——————————————————————————————————————————————————————————\n\n/** Identifies which pane is the source of a hover event. */\nexport type HoverPaneType = \"visual\" | \"graph\" | \"code\";\n\n/** Cross-highlighting hover target. `null` means nothing hovered. */\nexport type HoverTarget = { pane: HoverPaneType; id: string } | null;\n\n/** Which pane is full-screened (null = normal layout). */\nexport type FullscreenPane = \"main\" | \"graph\" | \"code\" | null;\n\n/**\n * Cross-referencing registry: maps node paths to code line numbers and\n * visual element selectors. Provided by each demo's `store.ts`.\n */\nexport type NodeRegistry = Map<string, { codeLine: number; visualSelector: string }>;\n\n/** Callbacks for cross-highlighting effect nodes. */\nexport type HighlightCallbacks = {\n\t/** Called when code-scroll highlight target changes. */\n\tcodeScroll?: (line: number | null) => void;\n\t/** Called when visual highlight target changes. */\n\tvisual?: (selector: string | null) => void;\n\t/** Called when graph highlight target changes. */\n\tgraph?: (nodeId: string | null) => void;\n};\n\n/** Label dimensions for graph node sizing. */\nexport type GraphLabelSize = { width: number; height: number };\n\n/** Options for {@link demoShell}. */\nexport type DemoShellOptions = {\n\t/** Initial main/side split ratio (0–1). Default: `0.65`. */\n\tmainRatio?: number;\n\t/** Initial graph/code vertical split in the side pane (0–1). Default: `0.5`. */\n\tsideSplit?: number;\n\t/** Initial viewport width in pixels. Default: `1280`. */\n\tviewportWidth?: number;\n\t/** Cross-referencing registry for hover→code/visual/graph mapping. */\n\tnodeRegistry?: NodeRegistry;\n\t/** Measurement adapter for layout engine integration. When provided, enables layout/* derived nodes. */\n\tadapter?: MeasurementAdapter;\n\t/** Font string for layout measurement. Default: `\"14px monospace\"`. */\n\tlayoutFont?: string;\n\t/** Callbacks for cross-highlighting effect nodes. When provided, creates effect nodes visible in describe(). */\n\tonHighlight?: HighlightCallbacks;\n};\n\n/** Return type of {@link demoShell}. */\nexport type DemoShellHandle = {\n\t/** The demo-shell graph. */\n\tgraph: Graph;\n\n\t// ── Convenience setters (shorthand for graph.set) ──────────\n\tsetMainRatio(ratio: number): void;\n\tsetSideSplit(ratio: number): void;\n\tsetFullscreen(pane: FullscreenPane): void;\n\tsetViewportWidth(width: number): void;\n\tsetHoverTarget(target: HoverTarget): void;\n\tsetDemoGraph(g: Graph | null): void;\n\tbumpGraphTick(): void;\n\tselectNode(path: string | null): void;\n\tsetMetaDebug(on: boolean): void;\n\t/** Set code text for layout/code-lines measurement (requires adapter). */\n\tsetCodeText(text: string): void;\n\t/** Atomic multi-set — wraps core `batch()` for glitch-free updates. */\n\tbatch(fn: () => void): void;\n\tdestroy(): void;\n};\n\n// ——————————————————————————————————————————————————————————\n// Helpers\n// ——————————————————————————————————————————————————————————\n\nfunction clamp01(v: number): number {\n\treturn Math.max(0, Math.min(1, v));\n}\n\n// ——————————————————————————————————————————————————————————\n// Factory\n// ——————————————————————————————————————————————————————————\n\n/**\n * Creates the three-pane demo shell graph (roadmap §7.2).\n *\n * All coordination is reactive — no polling, no imperative triggers.\n * Framework bindings subscribe to named nodes and drive `state` inputs.\n */\nexport function demoShell(opts?: DemoShellOptions): DemoShellHandle {\n\tconst mainRatioInit = clamp01(opts?.mainRatio ?? 0.65);\n\tconst sideSplitInit = clamp01(opts?.sideSplit ?? 0.5);\n\tconst viewportInit = Math.max(0, opts?.viewportWidth ?? 1280);\n\tconst registry = opts?.nodeRegistry ?? new Map();\n\tconst adapter = opts?.adapter ?? null;\n\tconst layoutFont = opts?.layoutFont ?? \"14px monospace\";\n\tconst onHighlight = opts?.onHighlight;\n\n\tconst g = new Graph(\"demo-shell\");\n\n\t// ── Layout state ─────────────────────────────────────\n\tconst paneMainRatio = state(mainRatioInit, { name: \"pane/main-ratio\" });\n\tconst paneSideSplit = state(sideSplitInit, { name: \"pane/side-split\" });\n\tconst paneFullscreen = state<FullscreenPane>(null, {\n\t\tname: \"pane/fullscreen\",\n\t});\n\tconst viewportWidth = state(viewportInit, { name: \"viewport/width\" });\n\n\tg.add(\"pane/main-ratio\", paneMainRatio);\n\tg.add(\"pane/side-split\", paneSideSplit);\n\tg.add(\"pane/fullscreen\", paneFullscreen);\n\tg.add(\"viewport/width\", viewportWidth);\n\n\t// ── Derived pane dimensions ──────────────────────────\n\tconst paneMainWidth = derived(\n\t\t[paneMainRatio, viewportWidth, paneFullscreen],\n\t\t([ratio, vw, fs]) => {\n\t\t\tconst r = ratio as number;\n\t\t\tconst w = vw as number;\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tif (fullscreen === \"main\") return w;\n\t\t\tif (fullscreen === \"graph\" || fullscreen === \"code\") return 0;\n\t\t\treturn Math.round(w * r);\n\t\t},\n\t\t{ name: \"pane/main-width\" },\n\t);\n\n\tconst paneSideWidth = derived(\n\t\t[paneMainWidth, viewportWidth, paneFullscreen],\n\t\t([main, vw, fs]) => {\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tconst w = vw as number;\n\t\t\tif (fullscreen === \"main\") return 0;\n\t\t\tif (fullscreen === \"graph\" || fullscreen === \"code\") return w;\n\t\t\treturn (w as number) - (main as number);\n\t\t},\n\t\t{ name: \"pane/side-width\" },\n\t);\n\n\tconst paneGraphHeight = derived(\n\t\t[paneSideSplit, paneFullscreen],\n\t\t([split, fs]) => {\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tif (fullscreen === \"graph\") return 1;\n\t\t\tif (fullscreen === \"code\") return 0;\n\t\t\tif (fullscreen === \"main\") return 0;\n\t\t\treturn clamp01(split as number);\n\t\t},\n\t\t{ name: \"pane/graph-height-ratio\" },\n\t);\n\n\tconst paneCodeHeight = derived(\n\t\t[paneGraphHeight, paneFullscreen],\n\t\t([graphH, fs]) => {\n\t\t\tconst fullscreen = fs as FullscreenPane;\n\t\t\tif (fullscreen === \"code\") return 1;\n\t\t\tif (fullscreen === \"graph\" || fullscreen === \"main\") return 0;\n\t\t\treturn 1 - (graphH as number);\n\t\t},\n\t\t{ name: \"pane/code-height-ratio\" },\n\t);\n\n\tg.add(\"pane/main-width\", paneMainWidth);\n\tg.add(\"pane/side-width\", paneSideWidth);\n\tg.add(\"pane/graph-height-ratio\", paneGraphHeight);\n\tg.add(\"pane/code-height-ratio\", paneCodeHeight);\n\n\t// ── External graph observation ───────────────────────\n\tconst demoGraphRef = state<Graph | null>(null, {\n\t\tname: \"demo/graph-ref\",\n\t});\n\tconst demoGraphTick = state(0, { name: \"demo/graph-tick\" });\n\n\tg.add(\"demo/graph-ref\", demoGraphRef);\n\tg.add(\"demo/graph-tick\", demoGraphTick);\n\n\tconst graphMermaid = derived(\n\t\t[demoGraphRef, demoGraphTick],\n\t\t([ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tif (!demo) return \"\";\n\t\t\treturn demo.describe({ format: \"mermaid\" });\n\t\t},\n\t\t{ name: \"graph/mermaid\" },\n\t);\n\n\tconst graphDescribe = derived(\n\t\t[demoGraphRef, demoGraphTick],\n\t\t([ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tif (!demo) return null;\n\t\t\tconst { expand: _, ...snapshot } = demo.describe({ detail: \"standard\" });\n\t\t\treturn snapshot;\n\t\t},\n\t\t{ name: \"graph/describe\" },\n\t);\n\n\tg.add(\"graph/mermaid\", graphMermaid);\n\tg.add(\"graph/describe\", graphDescribe);\n\n\t// ── Cross-highlighting ───────────────────────────────\n\tconst hoverTarget = state<HoverTarget>(null, { name: \"hover/target\" });\n\tg.add(\"hover/target\", hoverTarget);\n\n\tconst highlightCodeScroll = derived(\n\t\t[hoverTarget],\n\t\t([target]) => {\n\t\t\tconst t = target as HoverTarget;\n\t\t\tif (!t) return null;\n\t\t\tconst entry = registry.get(t.id);\n\t\t\treturn entry ? entry.codeLine : null;\n\t\t},\n\t\t{ name: \"highlight/code-scroll\" },\n\t);\n\n\tconst highlightVisual = derived(\n\t\t[hoverTarget],\n\t\t([target]) => {\n\t\t\tconst t = target as HoverTarget;\n\t\t\tif (!t) return null;\n\t\t\tconst entry = registry.get(t.id);\n\t\t\treturn entry ? entry.visualSelector : null;\n\t\t},\n\t\t{ name: \"highlight/visual\" },\n\t);\n\n\tconst highlightGraph = derived(\n\t\t[hoverTarget],\n\t\t([target]) => {\n\t\t\tconst t = target as HoverTarget;\n\t\t\tif (!t) return null;\n\t\t\treturn t.id;\n\t\t},\n\t\t{ name: \"highlight/graph\" },\n\t);\n\n\tg.add(\"highlight/code-scroll\", highlightCodeScroll);\n\tg.add(\"highlight/visual\", highlightVisual);\n\tg.add(\"highlight/graph\", highlightGraph);\n\n\t// ── Cross-highlighting effect nodes (optional) ─────\n\t// Created when onHighlight callbacks are provided, making the full\n\t// source→derived→effect chain visible in describe()/toMermaid().\n\n\tif (onHighlight?.codeScroll) {\n\t\tconst cb = onHighlight.codeScroll;\n\t\tconst applyCodeScroll = effect([highlightCodeScroll], ([line]) => {\n\t\t\tcb(line as number | null);\n\t\t});\n\t\tg.add(\"highlight/apply-code-scroll\", applyCodeScroll);\n\t}\n\n\tif (onHighlight?.visual) {\n\t\tconst cb = onHighlight.visual;\n\t\tconst applyVisual = effect([highlightVisual], ([selector]) => {\n\t\t\tcb(selector as string | null);\n\t\t});\n\t\tg.add(\"highlight/apply-visual\", applyVisual);\n\t}\n\n\tif (onHighlight?.graph) {\n\t\tconst cb = onHighlight.graph;\n\t\tconst applyGraph = effect([highlightGraph], ([nodeId]) => {\n\t\t\tcb(nodeId as string | null);\n\t\t});\n\t\tg.add(\"highlight/apply-graph\", applyGraph);\n\t}\n\n\t// ── Inspect panel ────────────────────────────────────\n\tconst inspectSelected = state<string | null>(null, {\n\t\tname: \"inspect/selected-node\",\n\t});\n\tg.add(\"inspect/selected-node\", inspectSelected);\n\n\tconst standardFields = resolveDescribeFields(\"standard\");\n\n\tconst inspectNodeDetail = derived(\n\t\t[inspectSelected, demoGraphRef, demoGraphTick],\n\t\t([path, ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tconst p = path as string | null;\n\t\t\tif (!demo || !p) return null;\n\t\t\ttry {\n\t\t\t\tconst nd = demo.resolve(p);\n\t\t\t\tconst nodeDesc = describeNode(nd, standardFields);\n\t\t\t\treturn { path: p, ...nodeDesc, value: nd.cache };\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t\t{ name: \"inspect/node-detail\" },\n\t);\n\n\tconst inspectTraceLog = derived(\n\t\t[demoGraphRef, demoGraphTick],\n\t\t([ref, _tick]) => {\n\t\t\tconst demo = ref as Graph | null;\n\t\t\tif (!demo) return [];\n\t\t\treturn demo.trace();\n\t\t},\n\t\t{ name: \"inspect/trace-log\" },\n\t);\n\n\tg.add(\"inspect/node-detail\", inspectNodeDetail);\n\tg.add(\"inspect/trace-log\", inspectTraceLog);\n\n\t// ── Meta debug toggle ────────────────────────────────\n\tconst metaDebug = state(false, { name: \"meta/debug\" });\n\tg.add(\"meta/debug\", metaDebug);\n\n\tconst metaShellMermaid = derived(\n\t\t[metaDebug, demoGraphTick],\n\t\t([debug, _tick]) => {\n\t\t\tif (!(debug as boolean)) return \"\";\n\t\t\treturn g.describe({ format: \"mermaid\" });\n\t\t},\n\t\t{ name: \"meta/shell-mermaid\" },\n\t);\n\tg.add(\"meta/shell-mermaid\", metaShellMermaid);\n\n\t// ── Layout engine integration (optional, requires adapter) ──\n\tconst codeTextNode = state(\"\", { name: \"layout/code-text\" });\n\tg.add(\"layout/code-text\", codeTextNode);\n\n\tif (adapter) {\n\t\tconst measureCache = new Map<string, Map<string, number>>();\n\n\t\tconst graphLabels = derived(\n\t\t\t[graphDescribe],\n\t\t\t([desc]) => {\n\t\t\t\tconst d = desc as { nodes: Record<string, { type: string }> } | null;\n\t\t\t\tif (!d) return new Map<string, GraphLabelSize>();\n\t\t\t\tconst result = new Map<string, GraphLabelSize>();\n\t\t\t\tfor (const [name] of Object.entries(d.nodes)) {\n\t\t\t\t\tconst segments = analyzeAndMeasure(name, layoutFont, adapter, measureCache);\n\t\t\t\t\tconst lb = computeLineBreaks(segments, Infinity, adapter, layoutFont, measureCache);\n\t\t\t\t\tconst width = lb.lines.reduce((max, l) => Math.max(max, l.width), 0);\n\t\t\t\t\tconst height = lb.lineCount * 20; // line-height approximation\n\t\t\t\t\tresult.set(name, { width, height });\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"layout/graph-labels\",\n\t\t\t\tequals: (a, b) => {\n\t\t\t\t\tif (a === b) return true;\n\t\t\t\t\tconst ma = a as Map<string, GraphLabelSize>;\n\t\t\t\t\tconst mb = b as Map<string, GraphLabelSize>;\n\t\t\t\t\tif (ma.size !== mb.size) return false;\n\t\t\t\t\tfor (const [k, v] of ma) {\n\t\t\t\t\t\tconst bv = mb.get(k);\n\t\t\t\t\t\tif (!bv || bv.width !== v.width || bv.height !== v.height) return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tconst codeLines = derived(\n\t\t\t[codeTextNode, paneSideWidth],\n\t\t\t([text, sideW]) => {\n\t\t\t\tconst t = text as string;\n\t\t\t\tif (!t) return { lineCount: 0, lines: [] };\n\t\t\t\tconst segments = analyzeAndMeasure(t, layoutFont, adapter, measureCache);\n\t\t\t\tconst maxW = (sideW as number) - 40; // side pane minus padding\n\t\t\t\treturn computeLineBreaks(segments, Math.max(100, maxW), adapter, layoutFont, measureCache);\n\t\t\t},\n\t\t\t{ name: \"layout/code-lines\" },\n\t\t);\n\n\t\tconst sideWidthHint = derived(\n\t\t\t[graphLabels],\n\t\t\t([labels]) => {\n\t\t\t\tconst m = labels as Map<string, GraphLabelSize>;\n\t\t\t\tif (m.size === 0) return 200; // minimum default\n\t\t\t\tlet maxW = 0;\n\t\t\t\tfor (const { width } of m.values()) {\n\t\t\t\t\tif (width > maxW) maxW = width;\n\t\t\t\t}\n\t\t\t\t// widest label + padding (node box chrome + margin)\n\t\t\t\treturn Math.max(200, Math.round(maxW + 80));\n\t\t\t},\n\t\t\t{ name: \"layout/side-width-hint\" },\n\t\t);\n\n\t\tg.add(\"layout/graph-labels\", graphLabels);\n\t\tg.add(\"layout/code-lines\", codeLines);\n\t\tg.add(\"layout/side-width-hint\", sideWidthHint);\n\t}\n\n\t// ── Edges (explicit wiring for describe/toMermaid) ───\n\n\t// ── Handle ───────────────────────────────────────────\n\tlet tickCounter = 0;\n\treturn {\n\t\tgraph: g,\n\t\tsetMainRatio(ratio: number) {\n\t\t\tg.set(\"pane/main-ratio\", clamp01(ratio));\n\t\t},\n\t\tsetSideSplit(ratio: number) {\n\t\t\tg.set(\"pane/side-split\", clamp01(ratio));\n\t\t},\n\t\tsetFullscreen(pane: FullscreenPane) {\n\t\t\tg.set(\"pane/fullscreen\", pane);\n\t\t},\n\t\tsetViewportWidth(width: number) {\n\t\t\tg.set(\"viewport/width\", Math.max(0, width));\n\t\t},\n\t\tsetHoverTarget(target: HoverTarget) {\n\t\t\tg.set(\"hover/target\", target);\n\t\t},\n\t\tsetDemoGraph(demo: Graph | null) {\n\t\t\tg.set(\"demo/graph-ref\", demo);\n\t\t},\n\t\tbumpGraphTick() {\n\t\t\tg.set(\"demo/graph-tick\", ++tickCounter);\n\t\t},\n\t\tselectNode(path: string | null) {\n\t\t\tg.set(\"inspect/selected-node\", path);\n\t\t},\n\t\tsetMetaDebug(on: boolean) {\n\t\t\tg.set(\"meta/debug\", on);\n\t\t},\n\t\tsetCodeText(text: string) {\n\t\t\tg.set(\"layout/code-text\", text);\n\t\t},\n\t\tbatch(fn: () => void) {\n\t\t\tbatch(fn);\n\t\t},\n\t\tdestroy() {\n\t\t\tg.destroy();\n\t\t},\n\t};\n}\n","/**\n * Domain templates (roadmap §8.2).\n *\n * Opinionated Graph factories for common \"info → action\" domains.\n * Each template wires up §8.1 reduction primitives (stratify, funnel, feedback,\n * budgetGate, scorer) with domain-specific stages. Users fork/extend by\n * accessing named nodes and swapping stages.\n *\n * **Source injection (option B):** templates accept a `source` node, not a\n * hardcoded adapter. Pass `fromOTel(...)`, `fromGitHook(...)`, or a test\n * `state()` — the topology is the same.\n *\n * @module\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { reactiveLog } from \"../extra/reactive-log.js\";\nimport { Graph, type GraphOptions } from \"../graph/graph.js\";\nimport { feedback, type StratifyRule, scorer, stratify } from \"./reduction.js\";\n\n// ---------------------------------------------------------------------------\n// Shared\n// ---------------------------------------------------------------------------\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"domain_template\", kind, extra);\n}\n\n// ---------------------------------------------------------------------------\n// 1. observabilityGraph\n// ---------------------------------------------------------------------------\n\n/** Stratification branch config for observability signals. */\nexport type ObservabilityBranch = {\n\tname: string;\n\tclassify: (value: unknown) => boolean;\n};\n\n/** Options for {@link observabilityGraph}. */\nexport type ObservabilityGraphOptions = GraphOptions & {\n\t/** Ingested signal source (e.g. fromOTel(...) or test state). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Classification rules for signal stratification.\n\t * Default: errors / traces / metrics branches.\n\t */\n\tbranches?: ObservabilityBranch[];\n\n\t/**\n\t * Correlation function: receives stratified branch values and produces\n\t * correlated insights. Default: identity pass-through.\n\t */\n\tcorrelate?: (values: unknown[]) => unknown;\n\n\t/**\n\t * SLO verification function: returns a verification result for a\n\t * correlated insight. Default: always passes.\n\t */\n\tsloCheck?: (value: unknown) => unknown;\n\n\t/**\n\t * Scorer weights for alert prioritization. One per branch.\n\t * Default: equal weights [1, 1, 1].\n\t */\n\tweights?: number[];\n\n\t/** Max feedback iterations for false-positive learning. Default: 5. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * OTel ingest → stratified reduction → correlation → SLO verification →\n * alert prioritization → output.\n *\n * Well-known node names:\n * - `\"source\"` — injected signal source\n * - `\"stratify::branch/<name>\"` — per-branch classification\n * - `\"correlate\"` — cross-branch correlation\n * - `\"slo_value\"`, `\"slo_verified\"` — SLO verification pair\n * - `\"alerts\"` — scored, prioritized output\n * - `\"output\"` — final output (alias for alerts)\n *\n * @category patterns\n */\nexport function observabilityGraph(name: string, opts: ObservabilityGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Stratify ---\n\tconst defaultBranches: ObservabilityBranch[] = [\n\t\t{ name: \"errors\", classify: (v) => isTagged(v, \"error\") },\n\t\t{ name: \"traces\", classify: (v) => isTagged(v, \"trace\") },\n\t\t{ name: \"metrics\", classify: (v) => isTagged(v, \"metric\") },\n\t];\n\tconst branches = opts.branches ?? defaultBranches;\n\tconst rules: StratifyRule<unknown>[] = branches.map((b) => ({\n\t\tname: b.name,\n\t\tclassify: b.classify,\n\t}));\n\tconst strat = stratify(\"stratify\", opts.source, rules);\n\tg.mount(\"stratify\", strat);\n\n\t// --- Correlate ---\n\t// Collect latest value from each branch, produce correlated output.\n\t// Wrap each branch in a derived with `initial: null` so every branch has\n\t// a seed value at subscribe time — this lets the correlate wave reach its\n\t// first-run gate even when the classifier only routes to one branch.\n\tconst branchNodes = branches.map((b) => {\n\t\ttry {\n\t\t\tconst raw = g.resolve(`stratify::branch/${b.name}`);\n\t\t\treturn derived([raw as Node], ([v]) => v, { initial: null });\n\t\t} catch {\n\t\t\treturn state<unknown>(null);\n\t\t}\n\t});\n\tconst correlateFn = opts.correlate ?? ((vals: unknown[]) => vals);\n\tconst correlateNode = derived<unknown>(\n\t\tbranchNodes as Node[],\n\t\t(vals) => correlateFn(vals as unknown[]),\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"correlate\" }),\n\t\t},\n\t);\n\tg.add(\"correlate\", correlateNode);\n\n\t// --- SLO verification ---\n\tconst sloCheckFn = opts.sloCheck ?? (() => ({ pass: true }));\n\tconst sloValue = derived<unknown>([correlateNode], (vals) => vals[0], {\n\t\tmeta: baseMeta(\"observability\", { stage: \"slo_value\" }),\n\t});\n\tconst sloVerified = derived<unknown>([sloValue], (vals) => sloCheckFn(vals[0]), {\n\t\tmeta: baseMeta(\"observability\", { stage: \"slo_verified\" }),\n\t});\n\tg.add(\"slo_value\", sloValue);\n\tg.add(\"slo_verified\", sloVerified);\n\n\t// --- Alert scorer ---\n\tconst weightValues = opts.weights ?? branches.map(() => 1);\n\tconst signalNodes = branchNodes.map((bn) =>\n\t\tderived<number>([bn], (vals) => (vals[0] != null ? 1 : 0)),\n\t);\n\tconst weightNodes = weightValues.map((w) => state<number>(w));\n\tfor (let i = 0; i < signalNodes.length; i++) {\n\t\tg.add(`__signal_${i}`, signalNodes[i] as Node<unknown>);\n\t\tg.add(`__weight_${i}`, weightNodes[i] as Node<unknown>);\n\t}\n\tconst alerts = scorer(\n\t\tsignalNodes as ReadonlyArray<Node<number>>,\n\t\tweightNodes as ReadonlyArray<Node<number>>,\n\t);\n\tg.add(\"alerts\", alerts as Node<unknown>);\n\n\t// --- Output alias ---\n\tconst output = derived<unknown>(\n\t\t[alerts as Node, sloVerified],\n\t\t(vals) => ({\n\t\t\tscored: vals[0],\n\t\t\tslo: vals[1],\n\t\t}),\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"output\" }),\n\t\t},\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (false-positive learning) ---\n\t// SLO failures feed back to re-check with updated context.\n\tconst fbReentry = state<unknown>(null, {\n\t\tmeta: baseMeta(\"observability\", { stage: \"feedback_reentry\" }),\n\t});\n\tg.add(\"feedback_reentry\", fbReentry);\n\tconst fbCondition = derived<unknown>(\n\t\t[sloVerified],\n\t\t(vals) => {\n\t\t\tconst result = vals[0] as Record<string, unknown> | null;\n\t\t\tif (result && result.pass === false) return result;\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"feedback_reentry\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 5,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 2. issueTrackerGraph\n// ---------------------------------------------------------------------------\n\n/** A structured issue extracted from raw findings. */\nexport type ExtractedIssue = {\n\tid: string;\n\ttitle: string;\n\tseverity: number;\n\tsource: string;\n\traw: unknown;\n};\n\n/** Options for {@link issueTrackerGraph}. */\nexport type IssueTrackerGraphOptions = GraphOptions & {\n\t/** Findings source (e.g. fromGitHook(...), fromFSWatch(...)). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Extract structured issues from raw findings.\n\t * Default: wraps raw value as a single issue.\n\t */\n\textract?: (raw: unknown) => ExtractedIssue;\n\n\t/**\n\t * Verify an extracted issue (assertion check).\n\t * Default: always valid.\n\t */\n\tverify?: (issue: ExtractedIssue) => unknown;\n\n\t/**\n\t * Detect regression by comparing against known patterns.\n\t * Receives (current issue, known patterns).\n\t * Default: no regression detected.\n\t */\n\tdetectRegression?: (issue: ExtractedIssue, known: unknown) => unknown;\n\n\t/** Max feedback iterations for re-scanning. Default: 3. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * Findings ingest → extraction → verification → regression detection →\n * distillation → prioritized queue.\n *\n * Well-known node names:\n * - `\"source\"` — injected findings source\n * - `\"extract\"` — structured issue extraction\n * - `\"verify\"` — issue verification\n * - `\"known_patterns\"` — accumulated known issue patterns (state)\n * - `\"regression\"` — regression detection\n * - `\"priority\"` — severity-based prioritization\n * - `\"output\"` — final prioritized output\n *\n * @category patterns\n */\nexport function issueTrackerGraph(name: string, opts: IssueTrackerGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Extract ---\n\tlet _issueCounter = 0;\n\tconst defaultExtract = (raw: unknown): ExtractedIssue => ({\n\t\tid: `issue-${++_issueCounter}`,\n\t\ttitle: String(raw),\n\t\tseverity: 1,\n\t\tsource: \"unknown\",\n\t\traw,\n\t});\n\tconst extractFn = opts.extract ?? defaultExtract;\n\tconst extractNode = derived<ExtractedIssue>([opts.source], (vals) => extractFn(vals[0]), {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"extract\" }),\n\t});\n\tg.add(\"extract\", extractNode as Node<unknown>);\n\n\t// --- Verify ---\n\tconst verifyFn = opts.verify ?? (() => ({ valid: true }));\n\tconst verifyNode = derived<unknown>(\n\t\t[extractNode as Node],\n\t\t(vals) => {\n\t\t\tconst issue = vals[0] as ExtractedIssue;\n\t\t\treturn { issue, verification: verifyFn(issue) };\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"verify\" }),\n\t\t},\n\t);\n\tg.add(\"verify\", verifyNode);\n\n\t// --- Known patterns (memory / distillation state) ---\n\tconst knownPatterns = state<unknown[]>([], {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"known_patterns\" }),\n\t});\n\tg.add(\"known_patterns\", knownPatterns as Node<unknown>);\n\n\t// --- Regression detection ---\n\tconst detectFn = opts.detectRegression ?? (() => ({ regression: false }));\n\tconst regressionNode = derived<unknown>(\n\t\t[extractNode as Node, knownPatterns as Node],\n\t\t(vals) => {\n\t\t\tconst issue = vals[0] as ExtractedIssue;\n\t\t\tconst known = vals[1];\n\t\t\treturn { issue, regression: detectFn(issue, known) };\n\t\t},\n\t\t{ meta: baseMeta(\"issue_tracker\", { stage: \"regression\" }) },\n\t);\n\tg.add(\"regression\", regressionNode);\n\n\t// --- Priority scoring ---\n\tconst severitySignal = derived<number>([extractNode as Node], (vals) => {\n\t\tconst issue = vals[0] as ExtractedIssue;\n\t\treturn issue?.severity ?? 0;\n\t});\n\tconst regressionSignal = derived<number>([regressionNode], (vals) => {\n\t\tconst r = vals[0] as Record<string, unknown> | null;\n\t\treturn r?.regression ? 2 : 0;\n\t});\n\tg.add(\"__severity_signal\", severitySignal as Node<unknown>);\n\tg.add(\"__regression_signal\", regressionSignal as Node<unknown>);\n\n\tconst severityWeight = state<number>(1);\n\tconst regressionWeight = state<number>(1.5);\n\tg.add(\"__severity_weight\", severityWeight as Node<unknown>);\n\tg.add(\"__regression_weight\", regressionWeight as Node<unknown>);\n\n\tconst priority = scorer([severitySignal, regressionSignal], [severityWeight, regressionWeight]);\n\tg.add(\"priority\", priority as Node<unknown>);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[verifyNode, regressionNode, priority as Node],\n\t\t(vals) => ({\n\t\t\tverified: vals[0],\n\t\t\tregression: vals[1],\n\t\t\tpriority: vals[2],\n\t\t}),\n\t\t{ meta: baseMeta(\"issue_tracker\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (re-scan on verification failure) ---\n\tconst fbReentry = state<unknown>(null, {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"feedback_reentry\" }),\n\t});\n\tg.add(\"feedback_reentry\", fbReentry);\n\tconst fbCondition = derived<unknown>(\n\t\t[verifyNode],\n\t\t(vals) => {\n\t\t\tconst result = vals[0] as Record<string, unknown> | null;\n\t\t\tif (result) {\n\t\t\t\tconst v = result.verification as Record<string, unknown> | null;\n\t\t\t\tif (v && v.valid === false) return result;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"feedback_reentry\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 3,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 3. contentModerationGraph\n// ---------------------------------------------------------------------------\n\n/** Classification result from LLM moderation. */\nexport type ModerationResult = {\n\tlabel: \"safe\" | \"review\" | \"block\";\n\tconfidence: number;\n\treason?: string;\n\toriginal: unknown;\n};\n\n/** Options for {@link contentModerationGraph}. */\nexport type ContentModerationGraphOptions = GraphOptions & {\n\t/** Content source (text/multimedia ingest). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Classification function: returns a ModerationResult.\n\t * Default: labels everything \"review\" with confidence 0.5.\n\t */\n\tclassify?: (content: unknown) => ModerationResult;\n\n\t/** System prompt for LLM classification. */\n\tsystemPrompt?: string;\n\n\t/** Scorer weights: [safe, review, block]. Default: [0.1, 1, 2]. */\n\tweights?: [number, number, number];\n\n\t/** Max feedback iterations for policy refinement. Default: 5. */\n\tmaxFeedbackIterations?: number;\n\n\t/** Max review queue size. When set, oldest entries are trimmed on overflow. */\n\tmaxQueueSize?: number;\n};\n\n/**\n * Content ingest → LLM/rule classification → stratified routing (safe/review/block) →\n * human review queue → scorer → feedback (false positives → policy refinement) → output.\n *\n * Well-known node names:\n * - `\"source\"` — content ingest\n * - `\"classify\"` — LLM or rule-based classification\n * - `\"stratify::branch/safe\"`, `\"stratify::branch/review\"`, `\"stratify::branch/block\"` — routed branches\n * - `\"review_queue\"` — state node for human review items\n * - `\"priority\"` — scored priority output\n * - `\"policy\"` — writable state for policy refinement\n * - `\"output\"` — final moderation output\n *\n * @category patterns\n */\nexport function contentModerationGraph(name: string, opts: ContentModerationGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Classify ---\n\tconst defaultClassify = (content: unknown): ModerationResult => ({\n\t\tlabel: \"review\",\n\t\tconfidence: 0.5,\n\t\toriginal: content,\n\t});\n\tconst classifyFn = opts.classify ?? defaultClassify;\n\tconst classifyNode = derived<ModerationResult>([opts.source], (vals) => classifyFn(vals[0]), {\n\t\tmeta: baseMeta(\"content_moderation\", { stage: \"classify\" }),\n\t});\n\tg.add(\"classify\", classifyNode as Node<unknown>);\n\n\t// --- Stratify (safe / review / block) ---\n\tconst strat = stratify<ModerationResult>(\"stratify\", classifyNode, [\n\t\t{ name: \"safe\", classify: (v) => v.label === \"safe\" },\n\t\t{ name: \"review\", classify: (v) => v.label === \"review\" },\n\t\t{ name: \"block\", classify: (v) => v.label === \"block\" },\n\t]);\n\tg.mount(\"stratify\", strat);\n\n\t// --- Review queue (reactiveLog — O(1) append, bounded) ---\n\tconst reviewLog = reactiveLog<ModerationResult>([], {\n\t\tname: \"review_queue\",\n\t\tmaxSize: opts.maxQueueSize,\n\t});\n\tg.add(\"review_queue\", reviewLog.entries as Node<unknown>);\n\n\t// Bridge review branch → review queue accumulator\n\tlet reviewBranch: Node<unknown>;\n\ttry {\n\t\treviewBranch = g.resolve(\"stratify::branch/review\");\n\t} catch {\n\t\treviewBranch = state<unknown>(null);\n\t\tg.add(\"__review_fallback\", reviewBranch);\n\t}\n\tconst reviewAccumulator = effect([reviewBranch], (vals) => {\n\t\tconst item = vals[0] as ModerationResult | null;\n\t\tif (item) {\n\t\t\treviewLog.append(item);\n\t\t}\n\t});\n\tg.add(\"__review_accumulator\", reviewAccumulator as Node<unknown>);\n\tg.addDisposer(keepalive(reviewAccumulator as Node<unknown>));\n\ttry {\n\t} catch {\n\t\t// fallback branch — no stratify edge to register\n\t}\n\n\t// --- Policy state (human/LLM writable) ---\n\tconst policy = state<Record<string, unknown>>(\n\t\t{},\n\t\t{\n\t\t\tmeta: baseMeta(\"content_moderation\", {\n\t\t\t\tstage: \"policy\",\n\t\t\t\taccess: \"both\",\n\t\t\t\tdescription: \"Moderation policy rules — updated via feedback\",\n\t\t\t}),\n\t\t},\n\t);\n\tg.add(\"policy\", policy as Node<unknown>);\n\n\t// --- Priority scorer ---\n\tconst weights = opts.weights ?? [0.1, 1, 2];\n\tconst confidenceSignal = derived<number>([classifyNode as Node], (vals) => {\n\t\tconst r = vals[0] as ModerationResult | null;\n\t\treturn r?.confidence ?? 0;\n\t});\n\tconst severitySignal = derived<number>([classifyNode as Node], (vals) => {\n\t\tconst r = vals[0] as ModerationResult | null;\n\t\tif (!r) return 0;\n\t\treturn r.label === \"block\" ? weights[2] : r.label === \"review\" ? weights[1] : weights[0];\n\t});\n\tg.add(\"__confidence_signal\", confidenceSignal as Node<unknown>);\n\tg.add(\"__severity_signal\", severitySignal as Node<unknown>);\n\n\tconst wConfidence = state<number>(1);\n\tconst wSeverity = state<number>(1);\n\tg.add(\"__w_confidence\", wConfidence as Node<unknown>);\n\tg.add(\"__w_severity\", wSeverity as Node<unknown>);\n\n\tconst priority = scorer([confidenceSignal, severitySignal], [wConfidence, wSeverity]);\n\tg.add(\"priority\", priority as Node<unknown>);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[classifyNode as Node, priority as Node],\n\t\t(vals) => ({\n\t\t\tclassification: vals[0],\n\t\t\tpriority: vals[1],\n\t\t}),\n\t\t{ meta: baseMeta(\"content_moderation\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (false positive → policy refinement) ---\n\t// Feedback condition: human marks a review item as false positive.\n\t// When review_queue changes and policy exists, signal for update.\n\tconst fbCondition = derived<unknown>(\n\t\t[reviewLog.entries as Node, policy as Node],\n\t\t(vals) => {\n\t\t\tconst entries = vals[0] as readonly ModerationResult[] | null;\n\t\t\tif (entries && entries.length > 0) {\n\t\t\t\tconst latest = entries[entries.length - 1];\n\t\t\t\t// Items explicitly marked as false positive feed back\n\t\t\t\tif (latest && (latest as unknown as Record<string, unknown>).falsePositive) {\n\t\t\t\t\treturn latest;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"content_moderation\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"policy\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 5,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 4. dataQualityGraph\n// ---------------------------------------------------------------------------\n\n/** Schema validation result. */\nexport type ValidationResult = {\n\tvalid: boolean;\n\terrors: string[];\n\trecord: unknown;\n};\n\n/** Anomaly detection result. */\nexport type AnomalyResult = {\n\tanomaly: boolean;\n\tscore: number;\n\tdetail?: string;\n\trecord: unknown;\n};\n\n/** Options for {@link dataQualityGraph}. */\nexport type DataQualityGraphOptions = GraphOptions & {\n\t/** Data source (e.g. fromPrisma(...), fromKysely(...)). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Schema validation function.\n\t * Default: always valid.\n\t */\n\tvalidate?: (record: unknown) => ValidationResult;\n\n\t/**\n\t * Anomaly detection function.\n\t * Default: no anomaly.\n\t */\n\tdetectAnomaly?: (record: unknown) => AnomalyResult;\n\n\t/**\n\t * Drift detection: compares current record against baseline.\n\t * Default: no drift.\n\t */\n\tdetectDrift?: (record: unknown, baseline: unknown) => unknown;\n\n\t/**\n\t * Remediation suggestion function.\n\t * Default: no suggestion.\n\t */\n\tsuggest?: (result: { validation: ValidationResult; anomaly: AnomalyResult }) => unknown;\n\n\t/** Max feedback iterations for rule refinement. Default: 3. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * Data ingest → schema validation → anomaly detection → drift alerting →\n * auto-remediation suggestions → output.\n *\n * Well-known node names:\n * - `\"source\"` — data ingest\n * - `\"validate\"` — schema validation\n * - `\"anomaly\"` — anomaly detection\n * - `\"baseline\"` — rolling baseline state\n * - `\"drift\"` — drift detection\n * - `\"remediate\"` — auto-remediation suggestions\n * - `\"output\"` — combined quality report\n *\n * @category patterns\n */\nexport function dataQualityGraph(name: string, opts: DataQualityGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Schema validation ---\n\tconst validateFn =\n\t\topts.validate ??\n\t\t((record: unknown): ValidationResult => ({\n\t\t\tvalid: true,\n\t\t\terrors: [],\n\t\t\trecord,\n\t\t}));\n\tconst validateNode = derived<ValidationResult | undefined>(\n\t\t[opts.source],\n\t\t(vals) => (vals[0] != null ? validateFn(vals[0]) : undefined),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"validate\" }) },\n\t);\n\tg.add(\"validate\", validateNode as Node<unknown>);\n\n\t// --- Anomaly detection ---\n\tconst detectAnomalyFn =\n\t\topts.detectAnomaly ??\n\t\t((record: unknown): AnomalyResult => ({\n\t\t\tanomaly: false,\n\t\t\tscore: 0,\n\t\t\trecord,\n\t\t}));\n\tconst anomalyNode = derived<AnomalyResult | undefined>(\n\t\t[opts.source],\n\t\t(vals) => (vals[0] != null ? detectAnomalyFn(vals[0]) : undefined),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"anomaly\" }) },\n\t);\n\tg.add(\"anomaly\", anomalyNode as Node<unknown>);\n\n\t// --- Baseline (rolling state) ---\n\tconst baseline = state<unknown>(null, {\n\t\tmeta: baseMeta(\"data_quality\", {\n\t\t\tstage: \"baseline\",\n\t\t\tdescription: \"Rolling baseline for drift detection\",\n\t\t}),\n\t});\n\tg.add(\"baseline\", baseline);\n\n\t// Update baseline on valid records\n\tconst baselineUpdater = effect([validateNode as Node], (vals) => {\n\t\tconst result = vals[0] as ValidationResult;\n\t\tif (result?.valid) {\n\t\t\tbatch(() => {\n\t\t\t\tbaseline.down([[DATA, result.record]]);\n\t\t\t});\n\t\t}\n\t});\n\tg.add(\"__baseline_updater\", baselineUpdater as Node<unknown>);\n\tkeepalive(baselineUpdater as Node<unknown>);\n\n\t// --- Drift detection ---\n\tconst detectDriftFn = opts.detectDrift ?? (() => ({ drift: false }));\n\tconst driftNode = derived<unknown>(\n\t\t[opts.source, baseline],\n\t\t(vals) => detectDriftFn(vals[0], vals[1]),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"drift\" }) },\n\t);\n\tg.add(\"drift\", driftNode);\n\n\t// --- Remediation suggestions ---\n\tconst suggestFn = opts.suggest ?? (() => null);\n\tconst remediateNode = derived<unknown>(\n\t\t[validateNode as Node, anomalyNode as Node],\n\t\t(vals) =>\n\t\t\tsuggestFn({\n\t\t\t\tvalidation: vals[0] as ValidationResult,\n\t\t\t\tanomaly: vals[1] as AnomalyResult,\n\t\t\t}),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"remediate\" }) },\n\t);\n\tg.add(\"remediate\", remediateNode);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[validateNode as Node, anomalyNode as Node, driftNode, remediateNode],\n\t\t(vals) => ({\n\t\t\tvalidation: vals[0],\n\t\t\tanomaly: vals[1],\n\t\t\tdrift: vals[2],\n\t\t\tremediation: vals[3],\n\t\t}),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (anomaly → validation rule refinement) ---\n\tconst validationRules = state<unknown[]>([], {\n\t\tmeta: baseMeta(\"data_quality\", { stage: \"validation_rules\" }),\n\t});\n\tg.add(\"validation_rules\", validationRules as Node<unknown>);\n\n\tconst fbCondition = derived<unknown>(\n\t\t[anomalyNode as Node],\n\t\t(vals) => {\n\t\t\tconst a = vals[0] as AnomalyResult | null;\n\t\t\tif (a?.anomaly) return a;\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"data_quality\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"validation_rules\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 3,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Check if a value has a `type` or `kind` tag matching the given label. */\nfunction isTagged(value: unknown, tag: string): boolean {\n\tif (value == null || typeof value !== \"object\") return false;\n\tconst v = value as Record<string, unknown>;\n\treturn v.type === tag || v.kind === tag;\n}\n","/**\n * Reduction primitives (roadmap §8.1).\n *\n * Composable building blocks for taking heterogeneous massive inputs and producing\n * prioritized, auditable, human-actionable output. Each primitive is either a Graph\n * factory or a Node factory, built on top of core + extra primitives.\n *\n * @module\n */\n\nimport { batch } from \"../core/batch.js\";\nimport type { NodeActions } from \"../core/config.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\ttype Message,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport { type Node, type NodeOptions, node } from \"../core/node.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { merge } from \"../extra/operators.js\";\nimport { reactiveMap } from \"../extra/reactive-map.js\";\nimport { Graph, type GraphOptions } from \"../graph/graph.js\";\n\n// ---------------------------------------------------------------------------\n// Shared helpers (same pattern as orchestration.ts)\n// ---------------------------------------------------------------------------\n\nexport type StepRef = string | Node<unknown>;\n\nimport { domainMeta, keepalive, tryIncrementBounded } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"reduction\", kind, meta);\n}\n\n// ---------------------------------------------------------------------------\n// stratify\n// ---------------------------------------------------------------------------\n\n/** A single routing rule for {@link stratify}. */\nexport type StratifyRule<T> = {\n\t/** Branch name (used as node name under `branch/<name>`). */\n\tname: string;\n\t/** Classifier: returns `true` if the value belongs to this branch. */\n\tclassify: (value: T) => boolean;\n\t/** Optional operator chain applied to the branch after classification. */\n\tops?: (n: Node<T>) => Node;\n};\n\n/** Options for {@link stratify}. */\nexport type StratifyOptions = GraphOptions & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Route input to different reduction branches based on classifier functions.\n *\n * Each branch gets an independent operator chain. Rules are reactive — update\n * the `\"rules\"` state node to rewrite classification at runtime. Rule updates\n * affect **future items only** (streaming classification, not retroactive).\n *\n * Branch nodes are structural — created at construction time and persist for\n * the graph's lifetime. If a rule name is removed from the rules array, the\n * corresponding branch silently drops items (classifier not found). To tear\n * down a dead branch, call `graph.remove(\"branch/<name>\")`.\n *\n * @param name - Graph name.\n * @param source - Input node (registered externally or will be added as `\"source\"`).\n * @param rules - Initial routing rules.\n * @param opts - Optional graph/meta options.\n * @returns Graph with `\"source\"`, `\"rules\"`, and `\"branch/<name>\"` nodes.\n *\n * @category patterns\n */\nexport function stratify<T>(\n\tname: string,\n\tsource: Node<T>,\n\trules: ReadonlyArray<StratifyRule<T>>,\n\topts?: StratifyOptions,\n): Graph {\n\tconst g = new Graph(name, opts);\n\n\tg.add(\"source\", source as Node<unknown>);\n\tconst rulesNode = state<ReadonlyArray<StratifyRule<T>>>(rules, {\n\t\tmeta: baseMeta(\"stratify_rules\"),\n\t});\n\tg.add(\"rules\", rulesNode as Node<unknown>);\n\n\tfor (const rule of rules) {\n\t\t_addBranch(g, source, rulesNode, rule);\n\t}\n\n\treturn g;\n}\n\nfunction _addBranch<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\trulesNode: Node<ReadonlyArray<StratifyRule<T>>>,\n\trule: StratifyRule<T>,\n): void {\n\tconst branchName = `branch/${rule.name}`;\n\n\t// Two-dep gating: intercepts messages from BOTH source (dep 0) and rules\n\t// (dep 1). Classification is deferred until all dirty deps have settled,\n\t// eliminating the stale-rules race when both are updated in the same batch().\n\t//\n\t// Protocol: DIRTY is buffered until DATA arrives. If the classifier matches,\n\t// emit [DIRTY, DATA]. If not, emit [DIRTY, RESOLVED] so downstream exits\n\t// dirty status cleanly (spec §1.3.1). Source RESOLVED forwards as RESOLVED.\n\t// Rules-only changes produce no downstream emission (\"future items only\").\n\t//\n\t// Producer pattern with `[]` deps: the framework does NOT auto-propagate\n\t// DIRTY/RESOLVED/COMPLETE from source or rules. We forward source terminals\n\t// explicitly below, and we silently absorb rules signals — preserving the\n\t// \"future items only\" semantic (rules changes are invisible downstream).\n\tconst _noValue: unique symbol = Symbol(\"noValue\");\n\tlet sourceDirty = false;\n\tlet rulesDirty = false;\n\tlet sourcePhase2 = false; // source delivered DATA or RESOLVED this cycle\n\tlet sourceValue: T | typeof _noValue = _noValue; // DATA payload, or _noValue for RESOLVED\n\tlet pendingDirty = false; // owe downstream a DIRTY\n\t// Latest rules DATA, seeded at factory time (wiring-time external read —\n\t// allowed per foundation-redesign §3.6). Updated by the rules subscribe\n\t// handler so `resolve()` never reads `rulesNode.cache` from a reactive context.\n\tlet latestRules: ReadonlyArray<StratifyRule<T>> = rulesNode.cache ?? [];\n\n\tfunction resolve(actions: NodeActions): void {\n\t\tif (sourcePhase2) {\n\t\t\tsourcePhase2 = false;\n\t\t\tconst value = sourceValue;\n\t\t\tsourceValue = _noValue;\n\t\t\tif (value !== _noValue) {\n\t\t\t\t// Source emitted DATA — classify with settled rules\n\t\t\t\tconst currentRule = latestRules.find((r) => r.name === rule.name);\n\t\t\t\tlet matches = false;\n\t\t\t\ttry {\n\t\t\t\t\tmatches = currentRule?.classify(value) ?? false;\n\t\t\t\t} catch {\n\t\t\t\t\tmatches = false;\n\t\t\t\t}\n\t\t\t\tif (matches) {\n\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\tactions.emit(value);\n\t\t\t\t} else {\n\t\t\t\t\tif (pendingDirty) {\n\t\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\t\tactions.down([[DIRTY], [RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Source RESOLVED (unchanged)\n\t\t\t\tif (pendingDirty) {\n\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\tactions.down([[DIRTY], [RESOLVED]]);\n\t\t\t\t} else {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// else: rules-only change — no reclassification (\"future items only\")\n\t}\n\n\t// Producer pattern: manually subscribe to source and rules for per-message\n\t// interception (onMessage removed in v5)\n\tconst filterNode = node<T>(\n\t\t[],\n\t\t(_data, filterActions) => {\n\t\t\tconst srcUnsub = (source as Node).subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t_handleStratifyMessage(msg, 0, filterActions);\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst rulesUnsub = (rulesNode as Node).subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t_handleStratifyMessage(msg, 1, filterActions);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsrcUnsub();\n\t\t\t\trulesUnsub();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"stratify_branch\", { branch: rule.name }),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t},\n\t);\n\n\tfunction _handleStratifyMessage(msg: Message, depIndex: number, actions: NodeActions): boolean {\n\t\tconst t = msg[0];\n\n\t\t// --- DIRTY (phase 1) ---\n\t\tif (t === DIRTY) {\n\t\t\tif (depIndex === 0) {\n\t\t\t\tsourceDirty = true;\n\t\t\t\tpendingDirty = true;\n\t\t\t} else {\n\t\t\t\trulesDirty = true;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// --- Phase 2 (DATA / RESOLVED) ---\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (depIndex === 0) {\n\t\t\t\tsourceDirty = false;\n\t\t\t\tsourcePhase2 = true;\n\t\t\t\tsourceValue = t === DATA ? (msg[1] as T) : _noValue;\n\t\t\t} else {\n\t\t\t\t// Rules dep: capture DATA payload into closure before settling.\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tlatestRules = msg[1] as ReadonlyArray<StratifyRule<T>>;\n\t\t\t\t}\n\t\t\t\trulesDirty = false;\n\t\t\t}\n\n\t\t\t// Wait for all dirty deps to settle\n\t\t\tif (sourceDirty || rulesDirty) return true;\n\n\t\t\tresolve(actions);\n\t\t\treturn true;\n\t\t}\n\n\t\t// --- Terminal ---\n\t\tif (t === COMPLETE || t === ERROR || t === TEARDOWN) {\n\t\t\tsourceDirty = false;\n\t\t\trulesDirty = false;\n\t\t\tsourcePhase2 = false;\n\t\t\tsourceValue = _noValue;\n\t\t\tpendingDirty = false;\n\t\t\tif (depIndex === 0) {\n\t\t\t\tactions.down([msg]);\n\t\t\t}\n\t\t\t// Rules terminal: swallow (branch stays alive)\n\t\t\treturn true;\n\t\t}\n\n\t\t// Swallow PAUSE/RESUME/INVALIDATE from rules dep (internal impl detail)\n\t\tif (depIndex === 1) return true;\n\n\t\treturn false;\n\t}\n\n\tgraph.add(branchName, filterNode as Node<unknown>);\n\n\t// If the rule has an ops chain, apply it and connect the edge\n\tif (rule.ops) {\n\t\tconst transformed = rule.ops(filterNode);\n\t\tconst transformedName = `branch/${rule.name}/out`;\n\t\tgraph.add(transformedName, transformed as Node<unknown>);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// funnel\n// ---------------------------------------------------------------------------\n\n/** A named stage for {@link funnel}. */\nexport type FunnelStage = {\n\t/** Stage name (mounted as subgraph). */\n\tname: string;\n\t/** Builder: receives a sub-graph, should add an `\"input\"` and `\"output\"` node. */\n\tbuild: (sub: Graph) => void;\n};\n\n/** Options for {@link funnel}. */\nexport type FunnelOptions = GraphOptions & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Multi-source merge with sequential reduction stages.\n *\n * Sources are merged into a single stream. Each stage is a named subgraph\n * (mounted via `graph.mount()`). Stages connect linearly:\n * `merged → stage[0].input → stage[0].output → stage[1].input → ...`\n *\n * @param name - Graph name.\n * @param sources - Input nodes to merge.\n * @param stages - Sequential reduction stages.\n * @param opts - Optional graph/meta options.\n * @returns Graph with `\"merged\"` and mounted stage subgraphs.\n *\n * @category patterns\n */\nexport function funnel<T>(\n\tname: string,\n\tsources: ReadonlyArray<Node<T>>,\n\tstages: ReadonlyArray<FunnelStage>,\n\topts?: FunnelOptions,\n): Graph {\n\tif (sources.length === 0) throw new RangeError(\"funnel requires at least one source\");\n\tif (stages.length === 0) throw new RangeError(\"funnel requires at least one stage\");\n\n\tconst g = new Graph(name, opts);\n\n\t// Merge all sources\n\tconst merged = sources.length === 1 ? sources[0] : merge(...(sources as unknown as Node<T>[]));\n\tg.add(\"merged\", merged as Node<unknown>);\n\n\t// Build and mount each stage linearly.\n\t// Stage inputs are standalone state nodes, so we bridge via subscribe\n\t// (connect() requires constructor deps). Bridge effects forward DATA\n\t// from the previous output to the next stage's input.\n\tlet prevOutputPath = \"merged\";\n\tfor (let i = 0; i < stages.length; i++) {\n\t\tconst stage = stages[i];\n\t\tconst sub = new Graph(stage.name);\n\t\tstage.build(sub);\n\n\t\t// Validate that the stage has input and output nodes\n\t\ttry {\n\t\t\tsub.resolve(\"input\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"input\" node`);\n\t\t}\n\t\ttry {\n\t\t\tsub.resolve(\"output\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"output\" node`);\n\t\t}\n\n\t\tg.mount(stage.name, sub);\n\n\t\t// Bridge replacement: effect that forwards DATA from previous output\n\t\t// to the next stage's input. TEARDOWN excluded because stage lifecycle\n\t\t// is managed by the parent graph. Shows up in describe().\n\t\tconst prevNode = g.resolve(prevOutputPath);\n\t\tconst stageInputPath = `${stage.name}::input`;\n\t\tconst stageInput = g.resolve(stageInputPath);\n\t\tconst bridgeName = `__bridge_${prevOutputPath}→${stage.name}_input`;\n\t\tconst br = effect(\n\t\t\t[prevNode],\n\t\t\t([data]) => {\n\t\t\t\tstageInput.down([[DATA, data]]);\n\t\t\t},\n\t\t\t{ name: bridgeName },\n\t\t);\n\t\tg.add(bridgeName, br as Node<unknown>);\n\t\tg.addDisposer(keepalive(br));\n\n\t\tprevOutputPath = `${stage.name}::output`;\n\t}\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// feedback\n// ---------------------------------------------------------------------------\n\n/** Options for {@link feedback}. */\nexport type FeedbackOptions = {\n\t/** Maximum feedback iterations before stopping (default: 10). */\n\tmaxIterations?: number;\n\t/** Optional budget gate node path for cost-bounded iteration. */\n\tbudgetNode?: StepRef;\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Introduce a bounded reactive cycle into an existing graph.\n *\n * When `condition` emits a non-null DATA value, the feedback effect routes it\n * back to the `reentry` state node — creating a cycle. Bounded by\n * `maxIterations` (default 10). The counter node (`__feedback_<condition>`)\n * is the source of truth — reset it to 0 to allow more iterations.\n *\n * To remove the feedback cycle, call `graph.remove(\"__feedback_<condition>\")`.\n *\n * @param graph - Existing graph to augment with a feedback cycle.\n * @param condition - Path to a node whose DATA triggers feedback.\n * @param reentry - Path to a state node that receives the feedback value.\n * @param opts - Iteration bounds and metadata.\n * @returns The same graph (mutated with feedback nodes added).\n *\n * @category patterns\n */\nexport function feedback(\n\tgraph: Graph,\n\tcondition: string,\n\treentry: string,\n\topts?: FeedbackOptions,\n): Graph {\n\tconst maxIter = opts?.maxIterations ?? 10;\n\n\t// Internal counter node — source of truth for iteration bound.\n\t// Reset to 0 to allow more iterations.\n\tconst counterName = `__feedback_${condition}`;\n\tconst counter = state<number>(0, {\n\t\tmeta: baseMeta(\"feedback_counter\", {\n\t\t\tmaxIterations: maxIter,\n\t\t\tfeedbackFrom: condition,\n\t\t\tfeedbackTo: reentry,\n\t\t}),\n\t});\n\tgraph.add(counterName, counter as Node<unknown>);\n\n\t// Resolve the condition and reentry nodes\n\tconst condNode = graph.resolve(condition);\n\tconst reentryNode = graph.resolve(reentry);\n\n\t// Graph-visible feedback effect: intercepts condition DATA, routes back to\n\t// reentry with iteration counting. Registered in the graph so it shows up\n\t// in describe() and cleans up on graph.destroy().\n\t// Feedback effect: subscribe to condition node for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\tconst feedbackEffectName = `__feedback_effect_${condition}`;\n\tconst feedbackEffect = node(\n\t\t[],\n\t\t(_data, _feedbackActions) => {\n\t\t\tconst unsub = condNode.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tconst t = msg[0];\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tconst condValue = msg[1];\n\t\t\t\t\t\tif (condValue == null) return;\n\t\t\t\t\t\tbatch(() => {\n\t\t\t\t\t\t\tif (tryIncrementBounded(counter, maxIter)) {\n\t\t\t\t\t\t\t\treentryNode.down([[DATA, condValue]]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (t === COMPLETE || t === ERROR) {\n\t\t\t\t\t\tconst terminal: Message = t === ERROR && msg.length > 1 ? [ERROR, msg[1]] : [t];\n\t\t\t\t\t\tcounter.down([terminal]);\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\t{\n\t\t\tname: feedbackEffectName,\n\t\t\tdescribeKind: \"effect\",\n\t\t\tmeta: {\n\t\t\t\t...baseMeta(\"feedback_effect\", {\n\t\t\t\t\tfeedbackFrom: condition,\n\t\t\t\t\tfeedbackTo: reentry,\n\t\t\t\t}),\n\t\t\t\t_internal: true,\n\t\t\t},\n\t\t},\n\t);\n\tgraph.add(feedbackEffectName, feedbackEffect as Node<unknown>);\n\tgraph.addDisposer(keepalive(feedbackEffect));\n\n\treturn graph;\n}\n\n// ---------------------------------------------------------------------------\n// budgetGate\n// ---------------------------------------------------------------------------\n\n/** A reactive constraint for {@link budgetGate}. */\nexport type BudgetConstraint<T = unknown> = {\n\t/** Constraint node whose value is checked. */\n\tnode: Node<T>;\n\t/** Returns `true` when the constraint is satisfied (budget available). */\n\tcheck: (value: T) => boolean;\n};\n\n/** Options for {@link budgetGate}. */\nexport type BudgetGateOptions = Omit<NodeOptions<unknown>, \"describeKind\" | \"name\" | \"meta\"> & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Pass-through that respects reactive constraint nodes.\n *\n * DATA flows through when all constraints are satisfied. When any constraint\n * is exceeded, PAUSE is sent upstream and DATA is buffered. When constraints\n * relax, RESUME is sent and buffered DATA flushes.\n *\n * @param source - Input node.\n * @param constraints - Reactive constraint checks.\n * @param opts - Optional node options.\n * @returns Gated node.\n *\n * @category patterns\n */\nexport function budgetGate<T>(\n\tsource: Node<T>,\n\tconstraints: ReadonlyArray<BudgetConstraint>,\n\topts?: BudgetGateOptions,\n): Node<T> {\n\tif (constraints.length === 0) throw new RangeError(\"budgetGate requires at least one constraint\");\n\n\tconst constraintNodes = constraints.map((c) => c.node);\n\tconst allDeps = [source as Node, ...constraintNodes] as Node[];\n\n\tlet buffer: T[] = [];\n\tlet paused = false;\n\tlet pendingResolved = false;\n\tconst lockId = Symbol(\"budget-gate\");\n\n\t// Latest DATA from each constraint. Seeded at **activation time** (inside the\n\t// producer fn below) — a wiring-time boundary read, not a reactive-callback\n\t// read — so concurrent constraint updates between factory-time and\n\t// activation-time are reflected before `checkBudget()` first runs. The\n\t// subscribe handler updates this array on each constraint DATA message, so\n\t// `checkBudget` never reads `.cache` from inside a reactive callback.\n\tconst latestValues: unknown[] = new Array(constraints.length);\n\n\tfunction checkBudget(): boolean {\n\t\treturn constraints.every((c, i) => c.check(latestValues[i]));\n\t}\n\n\tfunction flushBuffer(actions: NodeActions): void {\n\t\twhile (buffer.length > 0 && checkBudget()) {\n\t\t\tconst item = buffer[0]!;\n\t\t\tbuffer = buffer.slice(1);\n\t\t\tactions.emit(item);\n\t\t}\n\t\t// Drain deferred RESOLVED once buffer is empty\n\t\tif (buffer.length === 0 && pendingResolved) {\n\t\t\tpendingResolved = false;\n\t\t\tactions.down([[RESOLVED]]);\n\t\t}\n\t}\n\n\t// Producer pattern: manually subscribe to all deps for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\treturn node<T>(\n\t\t[],\n\t\t(_data, gateActions) => {\n\t\t\t// Seed `latestValues` at activation (not factory time) so any constraint\n\t\t\t// updates between factory return and first subscribe are captured before\n\t\t\t// source's push-on-subscribe fires `checkBudget()`.\n\t\t\tfor (let i = 0; i < constraints.length; i++) {\n\t\t\t\tlatestValues[i] = constraints[i]!.node.cache;\n\t\t\t}\n\t\t\tconst unsubs: Array<() => void> = [];\n\t\t\tfor (let depIdx = 0; depIdx < allDeps.length; depIdx++) {\n\t\t\t\tconst dep = allDeps[depIdx];\n\t\t\t\tunsubs.push(\n\t\t\t\t\tdep.subscribe((msgs) => {\n\t\t\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t\t\t_handleBudgetMessage(msg, depIdx, gateActions);\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\treturn () => {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"budget_gate\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\n\tfunction _handleBudgetMessage(msg: Message, depIndex: number, actions: NodeActions): boolean {\n\t\tconst t = msg[0];\n\n\t\t// Source messages (dep 0)\n\t\tif (depIndex === 0) {\n\t\t\tif (t === DATA) {\n\t\t\t\tif (checkBudget() && buffer.length === 0) {\n\t\t\t\t\tactions.emit(msg[1] as T);\n\t\t\t\t} else {\n\t\t\t\t\tbuffer.push(msg[1] as T);\n\t\t\t\t\tif (!paused) {\n\t\t\t\t\t\tpaused = true;\n\t\t\t\t\t\tactions.up([[PAUSE, lockId]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tactions.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\tif (buffer.length === 0) {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t} else {\n\t\t\t\t\t// Buffer non-empty: defer RESOLVED until buffer drains\n\t\t\t\t\tpendingResolved = true;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\t// Force-flush all buffered items regardless of budget (terminal = done)\n\t\t\t\tfor (const item of buffer) {\n\t\t\t\t\tactions.emit(item);\n\t\t\t\t}\n\t\t\t\tbuffer = [];\n\t\t\t\tpendingResolved = false;\n\t\t\t\t// Release PAUSE lock before forwarding terminal\n\t\t\t\tif (paused) {\n\t\t\t\t\tpaused = false;\n\t\t\t\t\tactions.up([[RESUME, lockId]]);\n\t\t\t\t}\n\t\t\t\tactions.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Constraint node messages (dep 1+): capture DATA then re-check budget\n\t\tif (t === DATA) {\n\t\t\tlatestValues[depIndex - 1] = msg[1];\n\t\t}\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (checkBudget() && buffer.length > 0) {\n\t\t\t\tflushBuffer(actions);\n\t\t\t\tif (buffer.length === 0 && paused) {\n\t\t\t\t\tpaused = false;\n\t\t\t\t\tactions.up([[RESUME, lockId]]);\n\t\t\t\t}\n\t\t\t} else if (!checkBudget() && !paused && buffer.length > 0) {\n\t\t\t\tpaused = true;\n\t\t\t\tactions.up([[PAUSE, lockId]]);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (t === DIRTY) {\n\t\t\t// Don't propagate constraint DIRTY downstream\n\t\t\treturn true;\n\t\t}\n\t\tif (t === ERROR) {\n\t\t\t// Constraint error → forward downstream\n\t\t\tactions.down([msg]);\n\t\t\treturn true;\n\t\t}\n\t\tif (t === COMPLETE) {\n\t\t\t// Constraint completed — locked at last value, no-op\n\t\t\treturn true;\n\t\t}\n\t\t// Unknown constraint types → default forwarding\n\t\treturn false;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// scorer\n// ---------------------------------------------------------------------------\n\n/** A scored item with full breakdown. */\nexport type ScoredItem<T = unknown> = {\n\t/** Original value. */\n\tvalue: T;\n\t/** Final weighted score. */\n\tscore: number;\n\t/** Per-signal breakdown: signal index → weighted contribution. */\n\tbreakdown: number[];\n};\n\n/** Options for {@link scorer}. */\nexport type ScorerOptions = Omit<NodeOptions<unknown>, \"describeKind\" | \"name\" | \"meta\"> & {\n\tmeta?: Record<string, unknown>;\n\t/** Custom scoring function per signal. Default: identity (signal value IS the score). */\n\tscoreFns?: ReadonlyArray<(value: unknown) => number>;\n};\n\n/**\n * Reactive multi-signal scoring with live weights.\n *\n * Each source emits items to score. Weights are reactive state nodes that\n * LLM or human can adjust live. Output is sorted scored items with full\n * breakdown.\n *\n * @param sources - Signal nodes (each emits a numeric score dimension).\n * @param weights - Reactive weight nodes (one per source).\n * @param opts - Optional node/meta options.\n * @returns Node emitting scored output.\n *\n * @category patterns\n */\nexport function scorer(\n\tsources: ReadonlyArray<Node<number>>,\n\tweights: ReadonlyArray<Node<number>>,\n\topts?: ScorerOptions,\n): Node<ScoredItem<number[]>> {\n\tif (sources.length === 0) throw new RangeError(\"scorer requires at least one source\");\n\tif (sources.length !== weights.length) {\n\t\tthrow new RangeError(\"scorer requires the same number of sources and weights\");\n\t}\n\n\tconst allDeps = [...(sources as unknown as Node[]), ...(weights as unknown as Node[])];\n\tconst n = sources.length;\n\tconst scoreFns = opts?.scoreFns;\n\n\treturn derived<ScoredItem<number[]>>(\n\t\tallDeps,\n\t\t(vals) => {\n\t\t\tconst signals = vals.slice(0, n) as number[];\n\t\t\tconst weightValues = vals.slice(n) as number[];\n\n\t\t\tconst breakdown: number[] = [];\n\t\t\tlet totalScore = 0;\n\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tconst sig = signals[i] ?? 0;\n\t\t\t\tconst wt = weightValues[i] ?? 0;\n\t\t\t\tconst rawScore = scoreFns?.[i] ? scoreFns[i](sig) : sig;\n\t\t\t\tconst weighted = (rawScore as number) * wt;\n\t\t\t\tbreakdown.push(weighted);\n\t\t\t\ttotalScore += weighted;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tvalue: signals,\n\t\t\t\tscore: totalScore,\n\t\t\t\tbreakdown,\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...(opts\n\t\t\t\t? {\n\t\t\t\t\t\tequals: opts.equals,\n\t\t\t\t\t\tresubscribable: opts.resubscribable,\n\t\t\t\t\t\tresetOnTeardown: opts.resetOnTeardown,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"scorer\", opts?.meta),\n\t\t},\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// effectivenessTracker\n// ---------------------------------------------------------------------------\n\n/** A single effectiveness record for an action×context pair. */\nexport type EffectivenessEntry = {\n\treadonly key: string;\n\treadonly attempts: number;\n\treadonly successes: number;\n\treadonly successRate: number;\n};\n\n/** Snapshot shape for the effectiveness tracker node. */\nexport type EffectivenessSnapshot = ReadonlyMap<string, EffectivenessEntry>;\n\n/** Bundle returned by {@link effectivenessTracker}. */\nexport interface EffectivenessTrackerBundle {\n\t/** Reactive node — current effectiveness map snapshot. */\n\treadonly node: Node<EffectivenessSnapshot>;\n\n\t/** Record a completed action (success or failure). */\n\trecord(key: string, success: boolean): void;\n\n\t/** Look up effectiveness for a specific key. */\n\tlookup(key: string): EffectivenessEntry | undefined;\n\n\t/** Tear down internal keepalive subscriptions. */\n\tdispose(): void;\n}\n\n/** Options for {@link effectivenessTracker}. */\nexport type EffectivenessTrackerOptions = {\n\t/** Name for the reactive map (default \"effectiveness-entries\"). */\n\tname?: string;\n};\n\n/**\n * Generic action×context → success rate tracker.\n *\n * Generalized from the harness `strategyModel` pattern. Tracks attempts and\n * successes per string key, exposes a reactive snapshot node, and provides\n * `record()` / `lookup()` methods.\n *\n * Use cases: A/B testing, routing optimization, cache policy tuning, retry\n * strategy selection — any domain that tracks effectiveness per action.\n *\n * @param opts - Optional configuration.\n * @returns Bundle with reactive node, record(), lookup(), dispose().\n */\nexport function effectivenessTracker(\n\topts?: EffectivenessTrackerOptions,\n): EffectivenessTrackerBundle {\n\tconst _map = reactiveMap<string, EffectivenessEntry>({\n\t\tname: opts?.name ?? \"effectiveness-entries\",\n\t});\n\n\tconst snapshot = derived<EffectivenessSnapshot>(\n\t\t[_map.entries],\n\t\t([mapSnap]) => {\n\t\t\treturn new Map(mapSnap as ReadonlyMap<string, EffectivenessEntry>);\n\t\t},\n\t\t{\n\t\t\tname: `${opts?.name ?? \"effectiveness\"}-snapshot`,\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst am = a as EffectivenessSnapshot;\n\t\t\t\tconst bm = b as EffectivenessSnapshot;\n\t\t\t\tif (am.size !== bm.size) return false;\n\t\t\t\tfor (const [k, v] of am) {\n\t\t\t\t\tconst bv = bm.get(k);\n\t\t\t\t\tif (!bv || v.attempts !== bv.attempts || v.successes !== bv.successes) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\tfunction record(key: string, success: boolean): void {\n\t\tconst existing = _map.get(key);\n\t\tconst attempts = (existing?.attempts ?? 0) + 1;\n\t\tconst successes = (existing?.successes ?? 0) + (success ? 1 : 0);\n\t\t_map.set(key, {\n\t\t\tkey,\n\t\t\tattempts,\n\t\t\tsuccesses,\n\t\t\tsuccessRate: successes / attempts,\n\t\t});\n\t}\n\n\tfunction lookup(key: string): EffectivenessEntry | undefined {\n\t\treturn _map.get(key);\n\t}\n\n\tconst _unsub = keepalive(snapshot);\n\n\treturn {\n\t\tnode: snapshot,\n\t\trecord,\n\t\tlookup,\n\t\tdispose: () => _unsub(),\n\t};\n}\n","/**\n * LLM graph composition (roadmap §8.3).\n *\n * Declarative GraphSpec schema + compiler/decompiler for graph topology.\n * The LLM designs graphs as JSON; compileSpec instantiates them; decompileGraph\n * extracts them back. Templates support reusable subgraph patterns. Feedback\n * edges express bounded cycles via §8.1 feedback().\n *\n * @module\n */\n\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, producer, state } from \"../core/sugar.js\";\nimport { GRAPH_META_SEGMENT, Graph } from \"../graph/graph.js\";\nimport type { ChatMessage, LLMAdapter, LLMResponse } from \"./ai.js\";\nimport { feedback as feedbackPrimitive } from \"./reduction.js\";\n\n// ---------------------------------------------------------------------------\n// GraphSpec types\n// ---------------------------------------------------------------------------\n\n/** A single node declaration in a GraphSpec. */\nexport type GraphSpecNode = {\n\t/** Node kind: state, producer, derived, effect, operator. */\n\ttype: \"state\" | \"producer\" | \"derived\" | \"effect\" | \"operator\";\n\t/** Dependency node names (for derived/effect/operator). */\n\tdeps?: string[];\n\t/** Named function from the catalog (for derived/effect/operator/producer). */\n\tfn?: string;\n\t/** Named source from the catalog (for producer). */\n\tsource?: string;\n\t/** Freeform config passed to the catalog fn/source factory. */\n\tconfig?: Record<string, unknown>;\n\t/** Initial value (for state nodes). */\n\tinitial?: unknown;\n\t/** Human/LLM-readable metadata. */\n\tmeta?: Record<string, unknown>;\n};\n\n/** Template instantiation node — expanded at compile time. */\nexport type GraphSpecTemplateRef = {\n\ttype: \"template\";\n\t/** Name of the template to instantiate. */\n\ttemplate: string;\n\t/** Parameter bindings: template param name → node name. */\n\tbind: Record<string, string>;\n};\n\n/** A reusable subgraph pattern with parameter substitution. */\nexport type GraphSpecTemplate = {\n\t/** Parameter names (prefixed with $ in node refs). */\n\tparams: string[];\n\t/** Node declarations within the template. */\n\tnodes: Record<string, GraphSpecNode>;\n\t/** Which node's output is the template's output. */\n\toutput: string;\n};\n\n/** A feedback edge: bounded cycle from condition to reentry. */\nexport type GraphSpecFeedbackEdge = {\n\t/** Node whose DATA triggers the feedback. */\n\tfrom: string;\n\t/** State node that receives the feedback value. */\n\tto: string;\n\t/** Max iterations before stopping (default: 10). */\n\tmaxIterations?: number;\n};\n\n/** Declarative graph topology for LLM composition (§8.3). */\nexport type GraphSpec = {\n\t/** Graph name. */\n\tname: string;\n\t/** Node declarations (keyed by node name). */\n\tnodes: Record<string, GraphSpecNode | GraphSpecTemplateRef>;\n\t/** Reusable subgraph templates. */\n\ttemplates?: Record<string, GraphSpecTemplate>;\n\t/** Feedback edges (bounded cycles). */\n\tfeedback?: GraphSpecFeedbackEdge[];\n};\n\n// ---------------------------------------------------------------------------\n// Catalog types\n// ---------------------------------------------------------------------------\n\n/**\n * Factory for creating a derived/effect/operator node from catalog.\n * Receives resolved dep nodes and the config from the spec.\n */\nexport type FnFactory = (deps: Node<unknown>[], config: Record<string, unknown>) => Node<unknown>;\n\n/**\n * Factory for creating a producer node from catalog.\n * Receives the config from the spec.\n */\nexport type SourceFactory = (config: Record<string, unknown>) => Node<unknown>;\n\n// ---------------------------------------------------------------------------\n// Rich catalog entries (§9.1b — auto-prompt, catalog-aware validation)\n// ---------------------------------------------------------------------------\n\n/** Simple config field descriptor for LLM prompt generation and validation. */\nexport type ConfigFieldSchema = {\n\t/** Human-readable type: \"string\", \"number\", \"boolean\", \"string[]\", etc. */\n\ttype: string;\n\t/** Whether this field is required (default: true). */\n\trequired?: boolean;\n\t/** Allowed values (enum constraint). */\n\tenum?: readonly (string | number | boolean)[];\n\t/** Human-readable description for LLM context. */\n\tdescription?: string;\n\t/** Default value if omitted. */\n\tdefault?: unknown;\n};\n\n/**\n * Rich catalog entry: bundles a runtime factory with LLM-facing metadata.\n *\n * The metadata is used to:\n * 1. Auto-generate prompt text for {@link llmCompose} (replaces manual `catalogDescription`)\n * 2. Validate LLM output in {@link validateSpec} (catch wrong fn names, invalid config)\n * 3. Provide actionable error messages for {@link llmRefine} feedback loops\n *\n * Developers register ONE object; the library handles prompt generation and validation.\n */\nexport type CatalogFnEntry = {\n\t/** Runtime factory. */\n\tfactory: FnFactory;\n\t/** One-line description for LLM prompt (what it does, not how). */\n\tdescription: string;\n\t/** Config field schemas. Keys are config field names. */\n\tconfigSchema?: Record<string, ConfigFieldSchema>;\n\t/** Example config objects (shown in prompt for complex fns). */\n\texamples?: Record<string, unknown>[];\n\t/** Category tags for grouping in prompt (e.g., \"resilience\", \"reduction\", \"ai\"). */\n\ttags?: string[];\n};\n\n/** Rich catalog entry for producer sources. */\nexport type CatalogSourceEntry = {\n\t/** Runtime factory. */\n\tfactory: SourceFactory;\n\t/** One-line description for LLM prompt. */\n\tdescription: string;\n\t/** Config field schemas. */\n\tconfigSchema?: Record<string, ConfigFieldSchema>;\n\t/** Example config objects. */\n\texamples?: Record<string, unknown>[];\n\t/** Category tags. */\n\ttags?: string[];\n};\n\n/**\n * Fn/source lookup table passed to compileSpec and llmCompose.\n *\n * Accepts both bare factories (backward-compatible) and rich {@link CatalogFnEntry}\n * / {@link CatalogSourceEntry} objects. When rich entries are provided, the library\n * auto-generates LLM prompts and validates LLM output against the catalog.\n */\nexport type GraphSpecCatalog = {\n\tfns?: Record<string, FnFactory | CatalogFnEntry>;\n\tsources?: Record<string, SourceFactory | CatalogSourceEntry>;\n};\n\n// ---------------------------------------------------------------------------\n// Catalog helpers\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this a rich catalog fn entry (vs bare factory)? */\nexport function isRichFnEntry(entry: FnFactory | CatalogFnEntry): entry is CatalogFnEntry {\n\treturn typeof entry === \"object\" && entry !== null && \"factory\" in entry;\n}\n\n/** Type guard: is this a rich catalog source entry (vs bare factory)? */\nexport function isRichSourceEntry(\n\tentry: SourceFactory | CatalogSourceEntry,\n): entry is CatalogSourceEntry {\n\treturn typeof entry === \"object\" && entry !== null && \"factory\" in entry;\n}\n\n/** Extract the runtime factory from a catalog entry (rich or bare). */\nexport function extractFnFactory(entry: FnFactory | CatalogFnEntry): FnFactory {\n\treturn isRichFnEntry(entry) ? entry.factory : entry;\n}\n\n/** Extract the runtime factory from a catalog source entry (rich or bare). */\nexport function extractSourceFactory(entry: SourceFactory | CatalogSourceEntry): SourceFactory {\n\treturn isRichSourceEntry(entry) ? entry.factory : entry;\n}\n\n/**\n * Auto-generate catalog prompt text from rich catalog entries.\n *\n * Groups fns by tag, formats each as `- name: description. Config: { ... }`.\n * Falls back to listing names only for bare factories.\n */\nexport function generateCatalogPrompt(catalog: GraphSpecCatalog): string {\n\tconst sections: string[] = [];\n\n\tif (catalog.fns) {\n\t\t// Group by first tag (or \"Other\")\n\t\tconst groups = new Map<string, string[]>();\n\t\tfor (const [name, entry] of Object.entries(catalog.fns)) {\n\t\t\tconst tag = isRichFnEntry(entry) ? (entry.tags?.[0] ?? \"Other\") : \"Other\";\n\t\t\tif (!groups.has(tag)) groups.set(tag, []);\n\t\t\tgroups.get(tag)!.push(formatFnEntry(name, entry));\n\t\t}\n\t\tfor (const [tag, lines] of groups) {\n\t\t\tsections.push(`${tag}:\\n${lines.join(\"\\n\")}`);\n\t\t}\n\t}\n\n\tif (catalog.sources) {\n\t\tconst lines: string[] = [];\n\t\tfor (const [name, entry] of Object.entries(catalog.sources)) {\n\t\t\tlines.push(formatSourceEntry(name, entry));\n\t\t}\n\t\tif (lines.length > 0) {\n\t\t\tsections.push(`Sources:\\n${lines.join(\"\\n\")}`);\n\t\t}\n\t}\n\n\treturn sections.join(\"\\n\\n\");\n}\n\nfunction formatFnEntry(name: string, entry: FnFactory | CatalogFnEntry): string {\n\tif (!isRichFnEntry(entry)) return `- ${name}`;\n\tlet line = `- ${name}: ${entry.description}`;\n\tif (entry.configSchema) {\n\t\tconst fields = Object.entries(entry.configSchema).map(([k, v]) => {\n\t\t\tlet desc = `${k}: ${v.type}`;\n\t\t\tif (v.enum) desc += ` (${v.enum.join(\"|\")})`;\n\t\t\tif (v.required === false) desc += \"?\";\n\t\t\treturn desc;\n\t\t});\n\t\tline += `. Config: { ${fields.join(\", \")} }`;\n\t}\n\treturn line;\n}\n\nfunction formatSourceEntry(name: string, entry: SourceFactory | CatalogSourceEntry): string {\n\tif (!isRichSourceEntry(entry)) return `- ${name}`;\n\tlet line = `- ${name}: ${entry.description}`;\n\tif (entry.configSchema) {\n\t\tconst fields = Object.entries(entry.configSchema).map(([k, v]) => {\n\t\t\tlet desc = `${k}: ${v.type}`;\n\t\t\tif (v.required === false) desc += \"?\";\n\t\t\treturn desc;\n\t\t});\n\t\tline += `. Config: { ${fields.join(\", \")} }`;\n\t}\n\treturn line;\n}\n\n/**\n * Validate a GraphSpec against a catalog.\n *\n * Checks that fn/source names reference actual catalog entries, and validates\n * config fields against configSchema when rich entries are available.\n * Returns additional errors beyond structural {@link validateSpec} checks.\n */\nexport function validateSpecAgainstCatalog(\n\tspec: GraphSpec,\n\tcatalog: GraphSpecCatalog,\n): GraphSpecValidation {\n\tconst errors: string[] = [];\n\tconst fnNames = new Set(Object.keys(catalog.fns ?? {}));\n\tconst sourceNames = new Set(Object.keys(catalog.sources ?? {}));\n\n\tfor (const [nodeName, nodeRaw] of Object.entries(spec.nodes)) {\n\t\tif (nodeRaw.type === \"template\") continue;\n\t\tconst node = nodeRaw as GraphSpecNode;\n\n\t\t// Check fn name exists in catalog\n\t\tif (node.fn && fnNames.size > 0 && !fnNames.has(node.fn)) {\n\t\t\t// Check if they used a source name as fn\n\t\t\tif (sourceNames.has(node.fn)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": fn \"${node.fn}\" is a source, not a function. ` +\n\t\t\t\t\t\t`Use it as a producer source instead, or use a function from: ${[...fnNames].join(\", \")}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst suggestion = findClosest(node.fn, fnNames);\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": fn \"${node.fn}\" not found in catalog` +\n\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Check source name exists in catalog\n\t\tif (node.source && sourceNames.size > 0 && !sourceNames.has(node.source)) {\n\t\t\tif (fnNames.has(node.source)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": source \"${node.source}\" is a function, not a source. ` +\n\t\t\t\t\t\t`Use it as fn instead, or use a source from: ${[...sourceNames].join(\", \")}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst suggestion = findClosest(node.source, sourceNames);\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": source \"${node.source}\" not found in catalog` +\n\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Validate config against schema (if rich entry)\n\t\tif (node.fn && node.config && catalog.fns?.[node.fn]) {\n\t\t\tconst entry = catalog.fns[node.fn];\n\t\t\tif (isRichFnEntry(entry) && entry.configSchema) {\n\t\t\t\tfor (const [field, schema] of Object.entries(entry.configSchema)) {\n\t\t\t\t\tif (schema.required !== false && !(field in node.config)) {\n\t\t\t\t\t\terrors.push(`Node \"${nodeName}\": config missing required field \"${field}\"`);\n\t\t\t\t\t}\n\t\t\t\t\tif (field in node.config && schema.enum) {\n\t\t\t\t\t\tconst val = node.config[field];\n\t\t\t\t\t\tif (!schema.enum.includes(val as string | number | boolean)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${nodeName}\": config.${field} = ${JSON.stringify(val)}, ` +\n\t\t\t\t\t\t\t\t\t`expected one of: ${schema.enum.join(\", \")}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Also check template inner nodes\n\tif (spec.templates) {\n\t\tfor (const [tName, template] of Object.entries(spec.templates)) {\n\t\t\tfor (const [nodeName, node] of Object.entries(template.nodes)) {\n\t\t\t\tif (node.fn && fnNames.size > 0 && !fnNames.has(node.fn)) {\n\t\t\t\t\tconst suggestion = findClosest(node.fn, fnNames);\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Template \"${tName}\" node \"${nodeName}\": fn \"${node.fn}\" not found in catalog` +\n\t\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n/** Simple Levenshtein-based closest match for \"did you mean?\" suggestions. */\nfunction findClosest(input: string, candidates: Set<string>): string | null {\n\tlet best: string | null = null;\n\tlet bestDist = Infinity;\n\tconst lower = input.toLowerCase();\n\tfor (const c of candidates) {\n\t\tconst dist = levenshtein(lower, c.toLowerCase());\n\t\tif (dist < bestDist && dist <= Math.max(3, Math.floor(input.length / 2))) {\n\t\t\tbestDist = dist;\n\t\t\tbest = c;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction levenshtein(a: string, b: string): number {\n\tconst m = a.length;\n\tconst n = b.length;\n\tconst dp: number[][] = Array.from({ length: m + 1 }, (_, i) =>\n\t\tArray.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n\t);\n\tfor (let i = 1; i <= m; i++) {\n\t\tfor (let j = 1; j <= n; j++) {\n\t\t\tdp[i][j] =\n\t\t\t\ta[i - 1] === b[j - 1]\n\t\t\t\t\t? dp[i - 1][j - 1]\n\t\t\t\t\t: 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);\n\t\t}\n\t}\n\treturn dp[m][n];\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\n/** Validation result from {@link validateSpec}. */\nexport type GraphSpecValidation = {\n\tvalid: boolean;\n\terrors: string[];\n};\n\nconst VALID_NODE_TYPES = new Set([\n\t\"state\",\n\t\"producer\",\n\t\"derived\",\n\t\"effect\",\n\t\"operator\",\n\t\"template\",\n]);\n\nconst INNER_NODE_TYPES = new Set([\"state\", \"producer\", \"derived\", \"effect\", \"operator\"]);\n\n/**\n * Validate a GraphSpec JSON object.\n *\n * Checks structural validity: required fields, node types, dep references,\n * template references, feedback edge targets, self-cycles, and bind completeness.\n */\nexport function validateSpec(spec: unknown): GraphSpecValidation {\n\tconst errors: string[] = [];\n\n\tif (spec == null || typeof spec !== \"object\") {\n\t\treturn { valid: false, errors: [\"GraphSpec must be a non-null object\"] };\n\t}\n\n\tconst s = spec as Record<string, unknown>;\n\n\tif (typeof s.name !== \"string\" || s.name.length === 0) {\n\t\terrors.push(\"Missing or empty 'name' field\");\n\t}\n\n\tif (s.nodes == null || typeof s.nodes !== \"object\" || Array.isArray(s.nodes)) {\n\t\terrors.push(\"Missing or invalid 'nodes' field (must be an object)\");\n\t\treturn { valid: false, errors };\n\t}\n\n\tconst nodeNames = new Set(Object.keys(s.nodes as object));\n\tconst nodeTypes = new Map<string, string>();\n\tconst templateDefs = new Map<string, { params: string[] }>();\n\n\t// Pre-scan template definitions for param validation\n\tif (s.templates != null && typeof s.templates === \"object\" && !Array.isArray(s.templates)) {\n\t\tfor (const [tName, tRaw] of Object.entries(s.templates as Record<string, unknown>)) {\n\t\t\tif (tRaw != null && typeof tRaw === \"object\") {\n\t\t\t\tconst t = tRaw as Record<string, unknown>;\n\t\t\t\ttemplateDefs.set(tName, {\n\t\t\t\t\tparams: Array.isArray(t.params) ? (t.params as string[]) : [],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate templates\n\tif (s.templates != null) {\n\t\tif (typeof s.templates !== \"object\" || Array.isArray(s.templates)) {\n\t\t\terrors.push(\"'templates' must be an object\");\n\t\t} else {\n\t\t\tfor (const [tName, tRaw] of Object.entries(s.templates as Record<string, unknown>)) {\n\t\t\t\tif (tRaw == null || typeof tRaw !== \"object\") {\n\t\t\t\t\terrors.push(`Template \"${tName}\": must be an object`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst t = tRaw as Record<string, unknown>;\n\t\t\t\tif (!Array.isArray(t.params)) {\n\t\t\t\t\terrors.push(`Template \"${tName}\": missing 'params' array`);\n\t\t\t\t}\n\t\t\t\tif (t.nodes == null || typeof t.nodes !== \"object\" || Array.isArray(t.nodes)) {\n\t\t\t\t\terrors.push(`Template \"${tName}\": missing or invalid 'nodes' object`);\n\t\t\t\t} else {\n\t\t\t\t\tconst paramSet = new Set(Array.isArray(t.params) ? (t.params as string[]) : []);\n\t\t\t\t\tconst innerNames = new Set(Object.keys(t.nodes as object));\n\t\t\t\t\tfor (const [nName, nRaw] of Object.entries(t.nodes as Record<string, unknown>)) {\n\t\t\t\t\t\tif (nRaw == null || typeof nRaw !== \"object\") {\n\t\t\t\t\t\t\terrors.push(`Template \"${tName}\" node \"${nName}\": must be an object`);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst n = nRaw as Record<string, unknown>;\n\t\t\t\t\t\tif (typeof n.type !== \"string\" || !INNER_NODE_TYPES.has(n.type)) {\n\t\t\t\t\t\t\terrors.push(`Template \"${tName}\" node \"${nName}\": invalid type`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (Array.isArray(n.deps)) {\n\t\t\t\t\t\t\tfor (const dep of n.deps as string[]) {\n\t\t\t\t\t\t\t\tif (!innerNames.has(dep) && !paramSet.has(dep)) {\n\t\t\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t\t\t`Template \"${tName}\" node \"${nName}\": dep \"${dep}\" is not an inner node or param`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof t.output !== \"string\") {\n\t\t\t\t\t\terrors.push(`Template \"${tName}\": missing 'output' string`);\n\t\t\t\t\t} else if (!(t.nodes as Record<string, unknown>)[t.output as string]) {\n\t\t\t\t\t\terrors.push(`Template \"${tName}\": output \"${t.output}\" is not a declared node`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate nodes\n\tfor (const [name, raw] of Object.entries(s.nodes as Record<string, unknown>)) {\n\t\tif (raw == null || typeof raw !== \"object\") {\n\t\t\terrors.push(`Node \"${name}\": must be an object`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst n = raw as Record<string, unknown>;\n\t\tif (typeof n.type !== \"string\" || !VALID_NODE_TYPES.has(n.type)) {\n\t\t\terrors.push(\n\t\t\t\t`Node \"${name}\": invalid type \"${String(n.type)}\" (expected: ${[...VALID_NODE_TYPES].join(\", \")})`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tnodeTypes.set(name, n.type);\n\n\t\tif (n.type === \"template\") {\n\t\t\tif (typeof n.template !== \"string\" || !templateDefs.has(n.template)) {\n\t\t\t\terrors.push(`Node \"${name}\": template \"${String(n.template)}\" not found in templates`);\n\t\t\t} else {\n\t\t\t\t// Check bind completeness: all template params must be bound\n\t\t\t\tif (n.bind == null || typeof n.bind !== \"object\" || Array.isArray(n.bind)) {\n\t\t\t\t\terrors.push(`Node \"${name}\": template ref requires 'bind' object`);\n\t\t\t\t} else {\n\t\t\t\t\tconst tmpl = templateDefs.get(n.template as string)!;\n\t\t\t\t\tconst bind = n.bind as Record<string, string>;\n\t\t\t\t\tfor (const param of tmpl.params) {\n\t\t\t\t\t\tif (!(param in bind)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${name}\": template param \"${param}\" is not bound (template \"${n.template}\")`,\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\tfor (const [, target] of Object.entries(bind)) {\n\t\t\t\t\t\tif (typeof target === \"string\" && !nodeNames.has(target)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${name}\": bind target \"${target}\" does not reference an existing node`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (Array.isArray(n.deps)) {\n\t\t\t\tfor (const dep of n.deps as string[]) {\n\t\t\t\t\t// Self-referencing dep\n\t\t\t\t\tif (dep === name) {\n\t\t\t\t\t\terrors.push(`Node \"${name}\": self-referencing dep`);\n\t\t\t\t\t} else if (!nodeNames.has(dep)) {\n\t\t\t\t\t\terrors.push(`Node \"${name}\": dep \"${dep}\" does not reference an existing node`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Warn: derived/effect/operator without deps\n\t\t\tif (\n\t\t\t\t(n.type === \"derived\" || n.type === \"effect\" || n.type === \"operator\") &&\n\t\t\t\t!Array.isArray(n.deps)\n\t\t\t) {\n\t\t\t\terrors.push(`Node \"${name}\": ${n.type} node should have a 'deps' array`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate feedback edges\n\tif (s.feedback != null) {\n\t\tif (!Array.isArray(s.feedback)) {\n\t\t\terrors.push(\"'feedback' must be an array\");\n\t\t} else {\n\t\t\tfor (let i = 0; i < (s.feedback as unknown[]).length; i++) {\n\t\t\t\tconst edge = (s.feedback as unknown[])[i];\n\t\t\t\tif (edge == null || typeof edge !== \"object\") {\n\t\t\t\t\terrors.push(`Feedback [${i}]: must be an object`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst e = edge as Record<string, unknown>;\n\t\t\t\tif (typeof e.from !== \"string\" || !nodeNames.has(e.from)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'from' \"${String(e.from)}\" does not reference an existing node`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (typeof e.from === \"string\" && e.from === e.to) {\n\t\t\t\t\terrors.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`);\n\t\t\t\t}\n\t\t\t\tif (typeof e.to !== \"string\" || !nodeNames.has(e.to)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'to' \"${String(e.to)}\" does not reference an existing node`,\n\t\t\t\t\t);\n\t\t\t\t} else if (typeof e.to === \"string\" && nodeTypes.get(e.to) !== \"state\") {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'to' node \"${e.to}\" must be a state node (got \"${nodeTypes.get(e.to) ?? \"unknown\"}\")`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// compileSpec\n// ---------------------------------------------------------------------------\n\n/** Options for {@link compileSpec}. */\nexport type CompileSpecOptions = {\n\t/** Fn/source catalog for resolving named factories. */\n\tcatalog?: GraphSpecCatalog;\n};\n\n/**\n * Instantiate a Graph from a GraphSpec.\n *\n * Handles template expansion (mounted subgraphs), feedback wiring via §8.1\n * feedback(), node factory lookup from the catalog, and topology validation.\n *\n * @param spec - Declarative graph topology.\n * @param opts - Catalog and compile options.\n * @returns A running Graph.\n * @throws On validation failure, missing catalog entries, or unresolvable deps.\n *\n * @category patterns\n */\nexport function compileSpec(spec: GraphSpec, opts?: CompileSpecOptions): Graph {\n\tconst validation = validateSpec(spec);\n\tif (!validation.valid) {\n\t\tthrow new Error(`compileSpec: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tconst catalog = opts?.catalog ?? {};\n\tconst g = new Graph(spec.name);\n\tconst templates = spec.templates ?? {};\n\n\t// Catalog-aware validation (when rich entries are available)\n\tconst catalogValidation = validateSpecAgainstCatalog(spec, catalog);\n\tif (!catalogValidation.valid) {\n\t\tthrow new Error(\n\t\t\t`compileSpec: catalog validation errors:\\n${catalogValidation.errors.join(\"\\n\")}`,\n\t\t);\n\t}\n\n\t// Helper: resolve fn/source factories from catalog (handles rich + bare entries)\n\tconst resolveFn = (fnName: string): FnFactory | undefined => {\n\t\tconst entry = catalog.fns?.[fnName];\n\t\treturn entry ? extractFnFactory(entry) : undefined;\n\t};\n\tconst resolveSource = (sourceName: string): SourceFactory | undefined => {\n\t\tconst entry = catalog.sources?.[sourceName];\n\t\treturn entry ? extractSourceFactory(entry) : undefined;\n\t};\n\n\t// Phase 1: Create non-template nodes (state/producer first, then derived/effect/operator)\n\tconst created = new Map<string, Node<unknown>>();\n\tconst deferred: [string, GraphSpecNode][] = [];\n\n\tfor (const [name, raw] of Object.entries(spec.nodes)) {\n\t\tif (raw.type === \"template\") continue; // handled in Phase 2\n\n\t\tconst n = raw as GraphSpecNode;\n\t\tif (n.type === \"state\") {\n\t\t\tconst nd = state(n.initial, {\n\t\t\t\tname,\n\t\t\t\tmeta: n.meta ? { ...n.meta } : undefined,\n\t\t\t});\n\t\t\tg.add(name, nd);\n\t\t\tcreated.set(name, nd);\n\t\t} else if (n.type === \"producer\") {\n\t\t\tconst sourceFactory = n.source ? resolveSource(n.source) : undefined;\n\t\t\tconst fnFactory = n.fn ? resolveFn(n.fn) : undefined;\n\t\t\tif (sourceFactory) {\n\t\t\t\tconst nd = sourceFactory(n.config ?? {});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t} else if (fnFactory) {\n\t\t\t\tconst nd = fnFactory([], n.config ?? {});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t} else {\n\t\t\t\t// No catalog entry — create a bare producer placeholder\n\t\t\t\tconst nd = producer(() => {}, {\n\t\t\t\t\tname,\n\t\t\t\t\tmeta: { ...n.meta, _specFn: n.fn, _specSource: n.source },\n\t\t\t\t});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t}\n\t\t} else {\n\t\t\tdeferred.push([name, n]);\n\t\t}\n\t}\n\n\t// Resolve deferred nodes (derived/effect/operator) in dependency order\n\tlet progressed = true;\n\tconst pending = new Map(deferred);\n\twhile (pending.size > 0 && progressed) {\n\t\tprogressed = false;\n\t\tfor (const [name, n] of [...pending.entries()]) {\n\t\t\tconst deps = n.deps ?? [];\n\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\n\t\t\tconst resolvedDeps = deps.map((dep) => created.get(dep)!);\n\t\t\tconst fnFactory = n.fn ? resolveFn(n.fn) : undefined;\n\n\t\t\tlet nd: Node<unknown>;\n\t\t\tif (fnFactory) {\n\t\t\t\tnd = fnFactory(resolvedDeps, n.config ?? {});\n\t\t\t} else if (n.type === \"effect\") {\n\t\t\t\tnd = effect(resolvedDeps, () => {});\n\t\t\t} else {\n\t\t\t\t// derived/operator without catalog fn — identity passthrough\n\t\t\t\tnd = derived(resolvedDeps, (vals: readonly unknown[]) => vals[0]);\n\t\t\t}\n\t\t\tg.add(name, nd);\n\t\t\tcreated.set(name, nd);\n\t\t\tpending.delete(name);\n\t\t\tprogressed = true;\n\t\t}\n\t}\n\tif (pending.size > 0) {\n\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\tthrow new Error(`compileSpec: unresolvable deps for nodes: ${unresolved}`);\n\t}\n\n\t// Phase 2: Expand template instantiations as mounted subgraphs\n\tfor (const [name, raw] of Object.entries(spec.nodes)) {\n\t\tif (raw.type !== \"template\") continue;\n\t\tconst ref = raw as GraphSpecTemplateRef;\n\t\tconst tmpl = templates[ref.template]!;\n\n\t\tconst sub = new Graph(name);\n\t\tconst subCreated = new Map<string, Node<unknown>>();\n\t\tconst subDeferred: [string, GraphSpecNode][] = [];\n\n\t\t// Create inner nodes, resolving $params to bound nodes\n\t\tfor (const [nName, nSpec] of Object.entries(tmpl.nodes)) {\n\t\t\tconst resolvedDeps = (nSpec.deps ?? []).map((dep) => {\n\t\t\t\tif (dep.startsWith(\"$\") && ref.bind[dep]) {\n\t\t\t\t\treturn ref.bind[dep];\n\t\t\t\t}\n\t\t\t\treturn dep;\n\t\t\t});\n\t\t\tconst specWithResolvedDeps = { ...nSpec, deps: resolvedDeps };\n\n\t\t\tif (nSpec.type === \"state\") {\n\t\t\t\tconst nd = state(nSpec.initial, {\n\t\t\t\t\tname: nName,\n\t\t\t\t\tmeta: nSpec.meta ? { ...nSpec.meta } : undefined,\n\t\t\t\t});\n\t\t\t\tsub.add(nName, nd);\n\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t} else if (nSpec.type === \"producer\") {\n\t\t\t\t// Handle producer nodes inside templates\n\t\t\t\tconst sourceFactory = nSpec.source ? resolveSource(nSpec.source) : undefined;\n\t\t\t\tconst fnFactory = nSpec.fn ? resolveFn(nSpec.fn) : undefined;\n\t\t\t\tif (sourceFactory) {\n\t\t\t\t\tconst nd = sourceFactory(nSpec.config ?? {});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t} else if (fnFactory) {\n\t\t\t\t\tconst nd = fnFactory([], nSpec.config ?? {});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t} else {\n\t\t\t\t\tconst nd = producer(() => {}, {\n\t\t\t\t\t\tname: nName,\n\t\t\t\t\t\tmeta: { ...nSpec.meta, _specFn: nSpec.fn, _specSource: nSpec.source },\n\t\t\t\t\t});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsubDeferred.push([nName, specWithResolvedDeps]);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve deferred inner nodes\n\t\tlet subProgressed = true;\n\t\tconst subPending = new Map(subDeferred);\n\t\twhile (subPending.size > 0 && subProgressed) {\n\t\t\tsubProgressed = false;\n\t\t\tfor (const [nName, nSpec] of [...subPending.entries()]) {\n\t\t\t\tconst deps = nSpec.deps ?? [];\n\t\t\t\tconst allReady = deps.every((dep) => subCreated.has(dep) || created.has(dep));\n\t\t\t\tif (!allReady) continue;\n\n\t\t\t\tconst resolvedDeps = deps.map((dep) => subCreated.get(dep) ?? created.get(dep)!);\n\t\t\t\tconst fnFactory = nSpec.fn ? resolveFn(nSpec.fn) : undefined;\n\n\t\t\t\tlet nd: Node<unknown>;\n\t\t\t\tif (fnFactory) {\n\t\t\t\t\tnd = fnFactory(resolvedDeps, nSpec.config ?? {});\n\t\t\t\t} else if (nSpec.type === \"effect\") {\n\t\t\t\t\tnd = effect(resolvedDeps, () => {});\n\t\t\t\t} else {\n\t\t\t\t\tnd = derived(resolvedDeps, (vals: readonly unknown[]) => vals[0]);\n\t\t\t\t}\n\t\t\t\tsub.add(nName, nd);\n\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\tsubPending.delete(nName);\n\t\t\t\tsubProgressed = true;\n\t\t\t}\n\t\t}\n\t\tif (subPending.size > 0) {\n\t\t\tconst unresolved = [...subPending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`compileSpec: template \"${ref.template}\" has unresolvable deps: ${unresolved}`,\n\t\t\t);\n\t\t}\n\n\t\tg.mount(name, sub);\n\t\t// Register template output as a reachable node path\n\t\tconst outputPath = `${name}::${tmpl.output}`;\n\t\tcreated.set(name, g.resolve(outputPath));\n\n\t\t// Store template origin meta on the mounted subgraph's first node\n\t\t// so decompileGraph can recover it without structural fingerprinting.\n\t\ttry {\n\t\t\tconst outputNode = g.resolve(outputPath);\n\t\t\toutputNode.meta._templateName?.down([[DATA, ref.template]]);\n\t\t\toutputNode.meta._templateBind?.down([[DATA, ref.bind]]);\n\t\t} catch {\n\t\t\t/* meta nodes may not exist; template origin is best-effort */\n\t\t}\n\t}\n\n\t// Edges are derived from node `_deps` (Unit 7) — no explicit edge wiring step.\n\n\t// Phase 4: Wire feedback edges via §8.1 feedback()\n\tfor (const fb of spec.feedback ?? []) {\n\t\tfeedbackPrimitive(g, fb.from, fb.to, {\n\t\t\tmaxIterations: fb.maxIterations,\n\t\t});\n\t}\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// decompileGraph\n// ---------------------------------------------------------------------------\n\n/** Internal meta keys used by compileSpec/feedback — stripped from output. */\nconst INTERNAL_META_KEYS = new Set([\n\t\"reduction\",\n\t\"reduction_type\",\n\t\"_specFn\",\n\t\"_specSource\",\n\t\"_templateName\",\n\t\"_templateBind\",\n\t\"feedbackFrom\",\n\t\"feedbackTo\",\n\t\"_internal\",\n]);\n\n/**\n * Extract a GraphSpec from a running graph.\n *\n * Uses `describe({ detail: \"standard\" })` as a starting point, then enriches:\n * - Feedback edges recovered from counter node meta (`feedbackFrom`/`feedbackTo`)\n * - Template refs recovered from output node meta (`_templateName`/`_templateBind`)\n * - Structural fingerprinting as fallback for 2+ identical mounted subgraphs\n *\n * @param graph - Running graph to decompile.\n * @returns A GraphSpec representation.\n *\n * @category patterns\n */\nexport function decompileGraph(graph: Graph): GraphSpec {\n\tconst desc = graph.describe({ detail: \"standard\" });\n\tconst nodes: Record<string, GraphSpecNode> = {};\n\tconst feedbackEdges: GraphSpecFeedbackEdge[] = [];\n\tconst metaSegment = `::${GRAPH_META_SEGMENT}::`;\n\n\t// Detect feedback counter nodes and extract feedback edges from meta\n\tconst feedbackCounterPattern = /^__feedback_(?!effect_)(.+)$/;\n\tconst feedbackConditions = new Set<string>();\n\n\tfor (const path of Object.keys(desc.nodes)) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\tconst match = feedbackCounterPattern.exec(path);\n\t\tif (match) {\n\t\t\tfeedbackConditions.add(match[1]!);\n\t\t\tconst meta = desc.nodes[path]?.meta as Record<string, unknown> | undefined;\n\t\t\tif (meta?.feedbackFrom && meta?.feedbackTo) {\n\t\t\t\tfeedbackEdges.push({\n\t\t\t\t\tfrom: meta.feedbackFrom as string,\n\t\t\t\t\tto: meta.feedbackTo as string,\n\t\t\t\t\t...(meta.maxIterations ? { maxIterations: meta.maxIterations as number } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build nodes map, skipping meta, feedback internals, and bridge nodes\n\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\tif (feedbackCounterPattern.test(path)) continue;\n\t\t// Skip internal infrastructure nodes (bridge, feedback effect) via meta tag\n\t\tif (nodeDesc.meta?._internal) continue;\n\t\t// Legacy fallback: skip by naming convention\n\t\tif (path.startsWith(\"__feedback_effect_\")) continue;\n\t\tif (path.startsWith(\"__bridge_\")) continue;\n\t\t// Skip subgraph-internal nodes (they belong to templates)\n\t\tif (path.includes(\"::\")) continue;\n\n\t\tconst specNode: GraphSpecNode = {\n\t\t\ttype: nodeDesc.type as GraphSpecNode[\"type\"],\n\t\t};\n\n\t\tif (nodeDesc.deps.length > 0) {\n\t\t\tspecNode.deps = nodeDesc.deps.filter((d) => !d.includes(\"::\"));\n\t\t}\n\n\t\tif (nodeDesc.type === \"state\" && nodeDesc.value !== undefined) {\n\t\t\tspecNode.initial = nodeDesc.value;\n\t\t}\n\n\t\tif (nodeDesc.meta && Object.keys(nodeDesc.meta).length > 0) {\n\t\t\tconst meta: Record<string, unknown> = {};\n\t\t\tfor (const [k, v] of Object.entries(nodeDesc.meta as Record<string, unknown>)) {\n\t\t\t\tif (!INTERNAL_META_KEYS.has(k)) meta[k] = v;\n\t\t\t}\n\t\t\tif (Object.keys(meta).length > 0) {\n\t\t\t\tspecNode.meta = meta;\n\t\t\t}\n\t\t}\n\n\t\tnodes[path] = specNode;\n\t}\n\n\t// Detect templates: first from compile-time meta (option B), then structural fallback\n\tconst templates: Record<string, GraphSpecTemplate> = {};\n\tconst templateRefs: Record<string, GraphSpecTemplateRef> = {};\n\tconst metaDetectedSubgraphs = new Set<string>();\n\n\t// Option B: recover template origin from meta stored by compileSpec\n\tfor (const subName of desc.subgraphs) {\n\t\tconst prefix = `${subName}::`;\n\t\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\t\tif (!path.startsWith(prefix)) continue;\n\t\t\tif (path.includes(metaSegment)) continue;\n\t\t\tconst meta = nodeDesc.meta as Record<string, unknown> | undefined;\n\t\t\tif (meta?._templateName && meta?._templateBind) {\n\t\t\t\tconst templateName = meta._templateName as string;\n\t\t\t\tconst bind = meta._templateBind as Record<string, string>;\n\n\t\t\t\t// Reconstruct template definition from the subgraph's nodes\n\t\t\t\tif (!templates[templateName]) {\n\t\t\t\t\tconst tmplNodes: Record<string, GraphSpecNode> = {};\n\t\t\t\t\tconst tmplInnerNames = new Set<string>();\n\t\t\t\t\tconst tmplPrefix = `${subName}::`;\n\t\t\t\t\tfor (const [p, nd] of Object.entries(desc.nodes)) {\n\t\t\t\t\t\tif (!p.startsWith(tmplPrefix) || p.includes(metaSegment)) continue;\n\t\t\t\t\t\tconst localName = p.slice(tmplPrefix.length);\n\t\t\t\t\t\tif (localName.includes(\"::\")) continue;\n\t\t\t\t\t\ttmplInnerNames.add(localName);\n\t\t\t\t\t\ttmplNodes[localName] = {\n\t\t\t\t\t\t\ttype: nd.type as GraphSpecNode[\"type\"],\n\t\t\t\t\t\t\t...(nd.deps.length > 0\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tdeps: nd.deps.map((d) =>\n\t\t\t\t\t\t\t\t\t\t\td.startsWith(tmplPrefix) ? d.slice(tmplPrefix.length) : d,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\t// Detect params (external deps) and output\n\t\t\t\t\tconst tmplParams: string[] = [];\n\t\t\t\t\tconst tmplParamMap = new Map<string, string>();\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\t\t\tif (!tmplInnerNames.has(dep) && !tmplParamMap.has(dep)) {\n\t\t\t\t\t\t\t\tconst param = `$${dep}`;\n\t\t\t\t\t\t\t\ttmplParams.push(param);\n\t\t\t\t\t\t\t\ttmplParamMap.set(dep, param);\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\t// Substitute external deps with $params\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tif (n.deps) n.deps = n.deps.map((d) => tmplParamMap.get(d) ?? d);\n\t\t\t\t\t}\n\t\t\t\t\t// Find output\n\t\t\t\t\tconst depended = new Set<string>();\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\t\t\tif (tmplInnerNames.has(dep)) depended.add(dep);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst outputCandidates = [...tmplInnerNames].filter((n) => !depended.has(n));\n\t\t\t\t\tconst tmplOutput = outputCandidates[0] ?? [...tmplInnerNames].pop()!;\n\n\t\t\t\t\ttemplates[templateName] = { params: tmplParams, nodes: tmplNodes, output: tmplOutput };\n\t\t\t\t}\n\n\t\t\t\tdelete nodes[subName];\n\t\t\t\ttemplateRefs[subName] = { type: \"template\", template: templateName, bind };\n\t\t\t\tmetaDetectedSubgraphs.add(subName);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Structural fallback: group remaining mounted subgraphs by fingerprint\n\tconst structureMap = new Map<string, { name: string; nodes: Record<string, GraphSpecNode> }[]>();\n\tfor (const subName of desc.subgraphs) {\n\t\tif (metaDetectedSubgraphs.has(subName)) continue;\n\t\tconst subNodes: Record<string, GraphSpecNode> = {};\n\t\tconst prefix = `${subName}::`;\n\t\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\t\tif (path.includes(metaSegment)) continue;\n\t\t\tif (!path.startsWith(prefix)) continue;\n\t\t\tconst localName = path.slice(prefix.length);\n\t\t\tif (localName.includes(\"::\")) continue;\n\t\t\tsubNodes[localName] = {\n\t\t\t\ttype: nodeDesc.type as GraphSpecNode[\"type\"],\n\t\t\t\t...(nodeDesc.deps.length > 0\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdeps: nodeDesc.deps.map((d) => (d.startsWith(prefix) ? d.slice(prefix.length) : d)),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t\tconst fingerprint = JSON.stringify(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(subNodes)\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([k, v]) => [k, { type: v.type, deps: v.deps ?? [] }]),\n\t\t\t),\n\t\t);\n\t\tif (!structureMap.has(fingerprint)) {\n\t\t\tstructureMap.set(fingerprint, []);\n\t\t}\n\t\tstructureMap.get(fingerprint)!.push({ name: subName, nodes: subNodes });\n\t}\n\n\t// Subgraphs with identical structure (2+ instances) → templates\n\tfor (const [, group] of structureMap) {\n\t\tif (group.length < 2) continue;\n\t\tconst templateName = `${group[0]!.name}_template`;\n\t\tconst refNodes = group[0]!.nodes;\n\t\tconst innerNames = new Set(Object.keys(refNodes));\n\n\t\t// Detect external deps as params (from first member)\n\t\tconst params: string[] = [];\n\t\tconst baseParamMap = new Map<string, string>();\n\t\tfor (const n of Object.values(refNodes)) {\n\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\tif (!innerNames.has(dep) && !baseParamMap.has(dep)) {\n\t\t\t\t\tconst param = `$${dep}`;\n\t\t\t\t\tparams.push(param);\n\t\t\t\t\tbaseParamMap.set(dep, param);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Find output node\n\t\tconst depended = new Set<string>();\n\t\tfor (const n of Object.values(refNodes)) {\n\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\tif (innerNames.has(dep)) depended.add(dep);\n\t\t\t}\n\t\t}\n\t\tconst outputCandidates = [...innerNames].filter((n) => !depended.has(n));\n\t\tconst output = outputCandidates[0] ?? [...innerNames].pop()!;\n\n\t\t// Build template nodes with param-substituted deps\n\t\tconst tmplNodes: Record<string, GraphSpecNode> = {};\n\t\tfor (const [nName, nSpec] of Object.entries(refNodes)) {\n\t\t\ttmplNodes[nName] = {\n\t\t\t\t...nSpec,\n\t\t\t\tdeps: nSpec.deps?.map((d) => baseParamMap.get(d) ?? d),\n\t\t\t};\n\t\t}\n\n\t\ttemplates[templateName] = { params, nodes: tmplNodes, output };\n\n\t\t// Build per-member bind maps (each member may bind to different external nodes)\n\t\tfor (const member of group) {\n\t\t\tdelete nodes[member.name];\n\t\t\t// Build this member's own bind map by scanning its external deps\n\t\t\tconst memberBind: Record<string, string> = {};\n\t\t\tconst memberInnerNames = new Set(Object.keys(member.nodes));\n\t\t\tfor (const n of Object.values(member.nodes)) {\n\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\tif (!memberInnerNames.has(dep)) {\n\t\t\t\t\t\t// Find which param this external dep maps to\n\t\t\t\t\t\tconst param = baseParamMap.get(dep) ?? `$${dep}`;\n\t\t\t\t\t\tmemberBind[param] = dep;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplateRefs[member.name] = {\n\t\t\t\ttype: \"template\",\n\t\t\t\ttemplate: templateName,\n\t\t\t\tbind: memberBind,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst allNodes: Record<string, GraphSpecNode | GraphSpecTemplateRef> = {\n\t\t...nodes,\n\t\t...templateRefs,\n\t};\n\n\tconst result: GraphSpec = { name: desc.name, nodes: allNodes };\n\tif (Object.keys(templates).length > 0) result.templates = templates;\n\tif (feedbackEdges.length > 0) result.feedback = feedbackEdges;\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// specDiff\n// ---------------------------------------------------------------------------\n\n/** A single change in a spec diff. */\nexport type SpecDiffEntry = {\n\ttype: \"added\" | \"removed\" | \"changed\";\n\tpath: string;\n\tdetail?: string;\n};\n\n/** Structural diff between two GraphSpecs. */\nexport type SpecDiffResult = {\n\tentries: SpecDiffEntry[];\n\tsummary: string;\n};\n\n/**\n * Compute a structural diff between two GraphSpecs.\n *\n * Template-aware: reports \"changed template definition\" vs \"changed\n * instantiation bindings.\" No runtime needed — pure JSON comparison.\n *\n * @param specA - The \"before\" spec.\n * @param specB - The \"after\" spec.\n * @returns Diff entries and a human-readable summary.\n *\n * @category patterns\n */\nexport function specDiff(specA: GraphSpec, specB: GraphSpec): SpecDiffResult {\n\tconst entries: SpecDiffEntry[] = [];\n\n\t// Diff name\n\tif (specA.name !== specB.name) {\n\t\tentries.push({\n\t\t\ttype: \"changed\",\n\t\t\tpath: \"name\",\n\t\t\tdetail: `\"${specA.name}\" → \"${specB.name}\"`,\n\t\t});\n\t}\n\n\t// Diff nodes\n\tconst nodesA = new Set(Object.keys(specA.nodes));\n\tconst nodesB = new Set(Object.keys(specB.nodes));\n\n\tfor (const name of nodesB) {\n\t\tif (!nodesA.has(name)) {\n\t\t\tconst n = specB.nodes[name]!;\n\t\t\tentries.push({\n\t\t\t\ttype: \"added\",\n\t\t\t\tpath: `nodes.${name}`,\n\t\t\t\tdetail: `type: ${n.type}`,\n\t\t\t});\n\t\t}\n\t}\n\tfor (const name of nodesA) {\n\t\tif (!nodesB.has(name)) {\n\t\t\tentries.push({ type: \"removed\", path: `nodes.${name}` });\n\t\t}\n\t}\n\tfor (const name of nodesA) {\n\t\tif (!nodesB.has(name)) continue;\n\t\tconst a = specA.nodes[name]!;\n\t\tconst b = specB.nodes[name]!;\n\t\tif (JSON.stringify(a) !== JSON.stringify(b)) {\n\t\t\tconst details: string[] = [];\n\t\t\tif (a.type !== b.type) details.push(`type: ${a.type} → ${b.type}`);\n\t\t\tif (JSON.stringify((a as GraphSpecNode).deps) !== JSON.stringify((b as GraphSpecNode).deps)) {\n\t\t\t\tdetails.push(\"deps changed\");\n\t\t\t}\n\t\t\tif ((a as GraphSpecNode).fn !== (b as GraphSpecNode).fn) {\n\t\t\t\tdetails.push(`fn: ${(a as GraphSpecNode).fn} → ${(b as GraphSpecNode).fn}`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tJSON.stringify((a as GraphSpecNode).config) !== JSON.stringify((b as GraphSpecNode).config)\n\t\t\t) {\n\t\t\t\tdetails.push(\"config changed\");\n\t\t\t}\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `nodes.${name}`,\n\t\t\t\tdetail: details.join(\"; \") || \"modified\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// Diff templates\n\tconst tmplA = specA.templates ?? {};\n\tconst tmplB = specB.templates ?? {};\n\tconst tmplNamesA = new Set(Object.keys(tmplA));\n\tconst tmplNamesB = new Set(Object.keys(tmplB));\n\n\tfor (const name of tmplNamesB) {\n\t\tif (!tmplNamesA.has(name)) {\n\t\t\tentries.push({ type: \"added\", path: `templates.${name}` });\n\t\t}\n\t}\n\tfor (const name of tmplNamesA) {\n\t\tif (!tmplNamesB.has(name)) {\n\t\t\tentries.push({ type: \"removed\", path: `templates.${name}` });\n\t\t}\n\t}\n\tfor (const name of tmplNamesA) {\n\t\tif (!tmplNamesB.has(name)) continue;\n\t\tif (JSON.stringify(tmplA[name]) !== JSON.stringify(tmplB[name])) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `templates.${name}`,\n\t\t\t\tdetail: \"template definition changed\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// Diff feedback\n\tconst fbA = specA.feedback ?? [];\n\tconst fbB = specB.feedback ?? [];\n\tconst fbKeyA = new Set(fbA.map((e) => `${e.from}->${e.to}`));\n\tconst fbKeyB = new Set(fbB.map((e) => `${e.from}->${e.to}`));\n\n\tfor (const fb of fbB) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tif (!fbKeyA.has(key)) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"added\",\n\t\t\t\tpath: `feedback.${key}`,\n\t\t\t\tdetail: `maxIterations: ${fb.maxIterations ?? 10}`,\n\t\t\t});\n\t\t}\n\t}\n\tfor (const fb of fbA) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tif (!fbKeyB.has(key)) {\n\t\t\tentries.push({ type: \"removed\", path: `feedback.${key}` });\n\t\t}\n\t}\n\tfor (const fb of fbA) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tconst counterpart = fbB.find((b) => b.from === fb.from && b.to === fb.to);\n\t\tif (counterpart && JSON.stringify(fb) !== JSON.stringify(counterpart)) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `feedback.${key}`,\n\t\t\t\tdetail: `maxIterations: ${fb.maxIterations ?? 10} → ${counterpart.maxIterations ?? 10}`,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Build summary\n\tconst added = entries.filter((e) => e.type === \"added\").length;\n\tconst removed = entries.filter((e) => e.type === \"removed\").length;\n\tconst changed = entries.filter((e) => e.type === \"changed\").length;\n\tconst parts: string[] = [];\n\tif (added) parts.push(`${added} added`);\n\tif (removed) parts.push(`${removed} removed`);\n\tif (changed) parts.push(`${changed} changed`);\n\tconst summary = parts.length > 0 ? parts.join(\", \") : \"no changes\";\n\n\treturn { entries, summary };\n}\n\n// ---------------------------------------------------------------------------\n// llmCompose\n// ---------------------------------------------------------------------------\n\n/** Options for {@link llmCompose}. */\nexport type LLMComposeOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Extra instructions appended to the system prompt. */\n\tsystemPromptExtra?: string;\n\t/**\n\t * Available fn/source catalog names for the LLM to reference.\n\t * When omitted and `catalog` contains rich {@link CatalogFnEntry} entries,\n\t * the prompt is auto-generated via {@link generateCatalogPrompt}.\n\t */\n\tcatalogDescription?: string;\n\t/**\n\t * Catalog for auto-prompt generation and catalog-aware validation.\n\t * When rich entries are provided, the catalog prompt is auto-generated\n\t * and LLM output is validated against fn/source names and config schemas.\n\t */\n\tcatalog?: GraphSpecCatalog;\n\t/**\n\t * Max auto-refine attempts when the LLM output fails catalog validation.\n\t * Each attempt feeds the validation errors back to the LLM via llmRefine.\n\t * Default: 0 (no auto-refine). Set to 2-3 for production use.\n\t */\n\tmaxAutoRefine?: number;\n};\n\nconst LLM_COMPOSE_SYSTEM_PROMPT = `You are a graph architect for GraphReFly, a reactive graph protocol.\n\nGiven a natural-language description, produce a JSON GraphSpec with this structure:\n\n{\n \"name\": \"<graph_name>\",\n \"nodes\": {\n \"<node_name>\": {\n \"type\": \"state\" | \"derived\" | \"producer\" | \"effect\" | \"operator\",\n \"deps\": [\"<dep_node_name>\", ...],\n \"fn\": \"<catalog_function_name>\",\n \"source\": \"<catalog_source_name>\",\n \"config\": { ... },\n \"initial\": <value>,\n \"meta\": { \"description\": \"<purpose>\" }\n },\n \"<template_instance>\": {\n \"type\": \"template\",\n \"template\": \"<template_name>\",\n \"bind\": { \"$param\": \"node_name\" }\n }\n },\n \"templates\": {\n \"<template_name>\": {\n \"params\": [\"$param1\", \"$param2\"],\n \"nodes\": { ... },\n \"output\": \"<output_node>\"\n }\n },\n \"feedback\": [\n { \"from\": \"<condition_node>\", \"to\": \"<state_node>\", \"maxIterations\": 10 }\n ]\n}\n\nRules:\n- \"state\" nodes hold user/LLM-writable values (knobs). Use \"initial\" for default values.\n- \"derived\" nodes compute from deps using a named \"fn\".\n- \"effect\" nodes produce side effects from deps.\n- \"producer\" nodes generate values from a named \"source\".\n- Use \"templates\" when the same subgraph pattern repeats (e.g., per-source resilience).\n- Use \"feedback\" for bounded cycles where a derived value writes back to a state node.\n- meta.description is required for every node.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/** Strip markdown code fences. */\nfunction stripFences(text: string): string {\n\tconst match = text.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```[\\s\\S]*$/);\n\treturn match ? match[1]! : text;\n}\n\n/**\n * Ask an LLM to compose a GraphSpec from a natural-language problem description.\n *\n * The LLM generates a GraphSpec (with templates + feedback), validated before\n * returning. The spec is for human review before compilation via compileSpec().\n *\n * @param problem - Natural language problem description.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options and catalog description.\n * @returns A validated GraphSpec.\n * @throws On invalid LLM output or validation failure.\n *\n * @category patterns\n */\nexport async function llmCompose(\n\tproblem: string,\n\tadapter: LLMAdapter,\n\topts?: LLMComposeOptions,\n): Promise<GraphSpec> {\n\tlet systemPrompt = LLM_COMPOSE_SYSTEM_PROMPT;\n\n\t// Auto-generate catalog prompt from rich entries, or use manual description\n\tconst catalogPrompt =\n\t\topts?.catalogDescription ?? (opts?.catalog ? generateCatalogPrompt(opts.catalog) : undefined);\n\tif (catalogPrompt) {\n\t\tsystemPrompt += `\\n\\nAvailable catalog (use ONLY these names):\\n${catalogPrompt}`;\n\t}\n\tif (opts?.systemPromptExtra) {\n\t\tsystemPrompt += `\\n\\n${opts.systemPromptExtra}`;\n\t}\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{ role: \"user\", content: problem },\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\t// System boundary: await the adapter's response (Promise, plain value).\n\tconst response = (await rawResult) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`llmCompose: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateSpec(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`llmCompose: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tlet spec = parsed as GraphSpec;\n\n\t// Catalog-aware validation + auto-refine loop\n\tif (opts?.catalog) {\n\t\tconst maxRefine = opts.maxAutoRefine ?? 0;\n\t\tfor (let attempt = 0; attempt <= maxRefine; attempt++) {\n\t\t\tconst catalogValidation = validateSpecAgainstCatalog(spec, opts.catalog);\n\t\t\tif (catalogValidation.valid) break;\n\n\t\t\tif (attempt === maxRefine) {\n\t\t\t\t// Last attempt failed — return with errors attached as meta\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`llmCompose: catalog validation failed after ${maxRefine} refine attempts:\\n${catalogValidation.errors.join(\"\\n\")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Auto-refine: feed catalog errors back to LLM\n\t\t\tspec = await llmRefine(\n\t\t\t\tspec,\n\t\t\t\t`Fix these catalog errors:\\n${catalogValidation.errors.join(\"\\n\")}\\n\\nUse ONLY functions and sources from the catalog.`,\n\t\t\t\tadapter,\n\t\t\t\t{ ...opts, catalogDescription: catalogPrompt },\n\t\t\t);\n\t\t}\n\t}\n\n\treturn spec;\n}\n\n// ---------------------------------------------------------------------------\n// llmRefine\n// ---------------------------------------------------------------------------\n\n/** Options for {@link llmRefine}. */\nexport type LLMRefineOptions = LLMComposeOptions;\n\n/**\n * Ask an LLM to modify an existing GraphSpec based on feedback or changed requirements.\n *\n * @param currentSpec - The current GraphSpec to modify.\n * @param feedback - Natural language feedback or changed requirements.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options.\n * @returns A new GraphSpec incorporating the feedback.\n * @throws On invalid LLM output or validation failure.\n *\n * @category patterns\n */\nexport async function llmRefine(\n\tcurrentSpec: GraphSpec,\n\tfeedback: string,\n\tadapter: LLMAdapter,\n\topts?: LLMRefineOptions,\n): Promise<GraphSpec> {\n\tlet systemPrompt = LLM_COMPOSE_SYSTEM_PROMPT;\n\tif (opts?.catalogDescription) {\n\t\tsystemPrompt += `\\n\\nAvailable catalog:\\n${opts.catalogDescription}`;\n\t}\n\tif (opts?.systemPromptExtra) {\n\t\tsystemPrompt += `\\n\\n${opts.systemPromptExtra}`;\n\t}\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{\n\t\t\trole: \"user\",\n\t\t\tcontent: `Current GraphSpec:\\n${JSON.stringify(currentSpec, null, 2)}\\n\\nModification request: ${feedback}\\n\\nReturn the complete modified GraphSpec as JSON.`,\n\t\t},\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\t// System boundary: await the adapter's response.\n\tconst response = (await rawResult) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`llmRefine: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateSpec(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`llmRefine: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\treturn parsed as GraphSpec;\n}\n","/**\n * Harness wiring (roadmap §9.0).\n *\n * Reactive collaboration loop: static-topology, flowing data.\n * Composes orchestration (gate), AI (promptNode), reduction (scorer/stratify),\n * and messaging (TopicGraph/bridge) into a 7-stage loop.\n *\n * @module\n */\n\nexport * from \"./bridge.js\";\nexport * from \"./loop.js\";\nexport * from \"./profile.js\";\nexport * from \"./strategy.js\";\nexport * from \"./trace.js\";\nexport * from \"./types.js\";\n","/**\n * Harness bridge factories (roadmap §9.0).\n *\n * Intake bridges, eval source wrapper, before/after comparison,\n * affected-task filter, code-change bridge, and notification effect.\n * All are compositions of existing primitives — no new abstractions.\n *\n * @module\n */\n\nimport type { Node } from \"../../core/node.js\";\nimport { derived, effect, state } from \"../../core/sugar.js\";\nimport { switchMap } from \"../../extra/operators.js\";\nimport { fromAny } from \"../../extra/sources.js\";\nimport type { TopicGraph } from \"../messaging.js\";\n\nimport type { IntakeItem, Severity, TriagedItem } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Generic intake bridge\n// ---------------------------------------------------------------------------\n\n/** Options for {@link createIntakeBridge}. */\nexport interface IntakeBridgeOptions {\n\t/** Name for the effect node (default \"intake-bridge\"). */\n\tname?: string;\n}\n\n/**\n * Generic source→intake bridge factory.\n *\n * Watches a source node for new values, passes each through a user-supplied\n * `parser` that produces zero or more `IntakeItem`s, and publishes them to\n * the given intake topic.\n *\n * This is the generalized pattern behind {@link evalIntakeBridge}. Use it for\n * CI results, test failures, Slack messages, monitoring alerts, or any domain\n * where structured results should flow into a harness loop.\n *\n * @param source - Reactive node emitting domain-specific data.\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param parser - Converts source data into IntakeItem[]. Return empty array to skip.\n * @param opts - Optional configuration.\n * @returns The effect node (for lifecycle management).\n */\nexport function createIntakeBridge<T>(\n\tsource: Node<T>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\tparser: (value: T) => IntakeItem[],\n\topts?: IntakeBridgeOptions,\n): Node<unknown> {\n\treturn effect(\n\t\t[source as Node<unknown>],\n\t\t([value]) => {\n\t\t\tif (value == null) return;\n\t\t\tconst items = parser(value as T);\n\t\t\tfor (const item of items) {\n\t\t\t\tintakeTopic.publish(item);\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"intake-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Generic eval result shape\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal eval result shape accepted by the bridge.\n *\n * TS eval runner uses `EvalRun` from `evals/lib/types.ts` which is a superset\n * of this shape. The bridge only reads what it needs.\n */\nexport interface EvalResult {\n\trun_id: string;\n\tmodel: string;\n\ttasks: EvalTaskResult[];\n}\n\nexport interface EvalTaskResult {\n\ttask_id: string;\n\tvalid: boolean;\n\tjudge_scores?: EvalJudgeScore[];\n}\n\nexport interface EvalJudgeScore {\n\tclaim: string;\n\tpass: boolean;\n\treasoning: string;\n}\n\n// ---------------------------------------------------------------------------\n// Bridge factory\n// ---------------------------------------------------------------------------\n\nexport interface EvalIntakeBridgeOptions {\n\t/** Name for the effect node (default \"eval-intake-bridge\"). */\n\tname?: string;\n\t/** Minimum severity for eval-sourced items (default \"medium\"). */\n\tdefaultSeverity?: Severity;\n}\n\n/**\n * Create an effect node that watches an eval results source and publishes\n * per-criterion findings to an intake topic.\n *\n * Each failing judge criterion produces a separate IntakeItem — not one\n * item per task. This gives the triage stage granular findings to classify.\n *\n * @param evalSource - Node emitting EvalResult (or EvalResult[]).\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param opts - Optional configuration.\n * @returns The effect node (for lifecycle management).\n */\nexport function evalIntakeBridge(\n\tevalSource: Node<EvalResult | EvalResult[]>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\topts?: EvalIntakeBridgeOptions,\n): Node<unknown> {\n\tconst defaultSeverity = opts?.defaultSeverity ?? \"medium\";\n\n\treturn effect(\n\t\t[evalSource],\n\t\t([results]) => {\n\t\t\tif (results == null) return;\n\t\t\tconst runs = Array.isArray(results) ? (results as EvalResult[]) : [results as EvalResult];\n\n\t\t\tfor (const run of runs) {\n\t\t\t\tfor (const task of run.tasks) {\n\t\t\t\t\t// Only process tasks with failures\n\t\t\t\t\tif (task.valid && task.judge_scores?.every((s) => s.pass)) continue;\n\n\t\t\t\t\t// Task-level validity failure (no judge scores or overall invalid)\n\t\t\t\t\tif (!task.valid && (!task.judge_scores || task.judge_scores.length === 0)) {\n\t\t\t\t\t\tintakeTopic.publish({\n\t\t\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\t\t\tsummary: `Task ${task.task_id} invalid (model: ${run.model})`,\n\t\t\t\t\t\t\tevidence: `Run ${run.run_id}: task produced invalid output`,\n\t\t\t\t\t\t\taffectsAreas: [\"graphspec\"],\n\t\t\t\t\t\t\taffectsEvalTasks: [task.task_id],\n\t\t\t\t\t\t\tseverity: defaultSeverity,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Per-criterion findings\n\t\t\t\t\tif (task.judge_scores) {\n\t\t\t\t\t\tfor (const score of task.judge_scores) {\n\t\t\t\t\t\t\tif (score.pass) continue;\n\t\t\t\t\t\t\tintakeTopic.publish({\n\t\t\t\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\t\t\t\tsummary: `${task.task_id}: ${score.claim} (model: ${run.model})`,\n\t\t\t\t\t\t\t\tevidence: score.reasoning,\n\t\t\t\t\t\t\t\taffectsAreas: [\"graphspec\"],\n\t\t\t\t\t\t\t\taffectsEvalTasks: [task.task_id],\n\t\t\t\t\t\t\t\tseverity: defaultSeverity,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"eval-intake-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition A: Eval-driven improvement loop\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap any eval runner as a reactive producer node.\n *\n * When `trigger` emits, calls `runner()` and emits the result downstream.\n * Uses `switchMap` + `fromAny` — the async boundary stays in the source\n * layer (spec §5.10). A new trigger cancels any in-flight run.\n *\n * ```ts\n * const trigger = state(0); // bump to trigger a new run\n * const results = evalSource(trigger, () => runEvals(config));\n * results.subscribe(msgs => { ... });\n * trigger.down([[DATA, 1]]); // fires the runner\n * ```\n *\n * @param trigger - Any node; each new DATA emission fires the runner.\n * @param runner - Returns an EvalResult (or promise of one).\n */\nexport function evalSource<T extends EvalResult>(\n\ttrigger: Node<unknown>,\n\trunner: () => T | Promise<T>,\n): Node<T> {\n\treturn switchMap(trigger, () => fromAny(runner()) as Node<T>);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Per-task delta produced by {@link beforeAfterCompare}. */\nexport interface EvalTaskDelta {\n\ttaskId: string;\n\tbefore: boolean;\n\tafter: boolean;\n\t/** Score-level diff (after − before), undefined if no scores present. */\n\tscoreDiff?: number;\n}\n\n/** Output of {@link beforeAfterCompare}. */\nexport interface EvalDelta {\n\t/** Task IDs that newly fail in `after` (were passing in `before`). */\n\tnewFailures: string[];\n\t/** Task IDs that now pass in `after` (were failing in `before`). */\n\tresolved: string[];\n\t/** Full per-task breakdown. */\n\ttaskDeltas: EvalTaskDelta[];\n\t/** True when net resolutions > net failures. */\n\toverallImproved: boolean;\n}\n\n/**\n * Derived node that computes before/after eval deltas.\n *\n * Pure computation: no LLM, no async. Compares per-task validity and\n * pass counts between two `EvalResult` snapshots.\n *\n * @param before - Node holding the baseline eval result.\n * @param after - Node holding the new eval result.\n */\nexport function beforeAfterCompare(\n\tbefore: Node<EvalResult>,\n\tafter: Node<EvalResult>,\n): Node<EvalDelta> {\n\treturn derived<EvalDelta>(\n\t\t[before as Node<unknown>, after as Node<unknown>],\n\t\t([b, a]) => {\n\t\t\tconst bRes = b as EvalResult;\n\t\t\tconst aRes = a as EvalResult;\n\n\t\t\tconst beforeMap = new Map<string, EvalTaskResult>(bRes.tasks.map((t) => [t.task_id, t]));\n\t\t\tconst afterMap = new Map<string, EvalTaskResult>(aRes.tasks.map((t) => [t.task_id, t]));\n\n\t\t\tconst allIds = new Set([...beforeMap.keys(), ...afterMap.keys()]);\n\t\t\tconst taskDeltas: EvalTaskDelta[] = [];\n\t\t\tconst newFailures: string[] = [];\n\t\t\tconst resolved: string[] = [];\n\n\t\t\tfor (const id of allIds) {\n\t\t\t\tconst bt = beforeMap.get(id);\n\t\t\t\tconst at = afterMap.get(id);\n\t\t\t\tconst beforeValid = bt?.valid ?? false;\n\t\t\t\tconst afterValid = at?.valid ?? false;\n\n\t\t\t\tconst beforeScore = bt?.judge_scores\n\t\t\t\t\t? bt.judge_scores.filter((s) => s.pass).length\n\t\t\t\t\t: undefined;\n\t\t\t\tconst afterScore = at?.judge_scores\n\t\t\t\t\t? at.judge_scores.filter((s) => s.pass).length\n\t\t\t\t\t: undefined;\n\t\t\t\tconst scoreDiff =\n\t\t\t\t\tbeforeScore !== undefined && afterScore !== undefined\n\t\t\t\t\t\t? afterScore - beforeScore\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\ttaskDeltas.push({ taskId: id, before: beforeValid, after: afterValid, scoreDiff });\n\t\t\t\tif (beforeValid && !afterValid) newFailures.push(id);\n\t\t\t\tif (!beforeValid && afterValid) resolved.push(id);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tnewFailures,\n\t\t\t\tresolved,\n\t\t\t\ttaskDeltas,\n\t\t\t\toverallImproved: resolved.length > newFailures.length,\n\t\t\t};\n\t\t},\n\t\t{ name: \"eval-delta\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/**\n * Derived node that selects which eval task IDs to re-run.\n *\n * Collects `affectsEvalTasks` from all triaged items, deduplicates, then\n * optionally intersects with `fullTaskSet`. Returns a sorted array of IDs.\n *\n * Use this to avoid re-running the full eval suite after each fix: only the\n * tasks that the triaged items claim to affect are returned.\n *\n * @param issues - Node holding the current list of triaged items.\n * @param fullTaskSet - Optional node (or plain array) of all known task IDs.\n * When provided, output is the intersection.\n */\nexport function affectedTaskFilter(\n\tissues: Node<readonly TriagedItem[]>,\n\tfullTaskSet?: Node<readonly string[]> | readonly string[],\n): Node<string[]> {\n\tconst taskSetNode: Node<unknown> | null =\n\t\tfullTaskSet == null\n\t\t\t? null\n\t\t\t: Array.isArray(fullTaskSet)\n\t\t\t\t? (state(fullTaskSet as readonly string[]) as Node<unknown>)\n\t\t\t\t: (fullTaskSet as Node<unknown>);\n\n\tconst deps: Node<unknown>[] = [issues as Node<unknown>];\n\tif (taskSetNode) deps.push(taskSetNode);\n\n\treturn derived<string[]>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst items = values[0] as readonly TriagedItem[];\n\t\t\tconst all = taskSetNode ? new Set(values[1] as readonly string[]) : null;\n\n\t\t\tconst affected = new Set<string>();\n\t\t\tfor (const item of items) {\n\t\t\t\tfor (const id of item.affectsEvalTasks ?? []) {\n\t\t\t\t\tif (all == null || all.has(id)) affected.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn [...affected].sort();\n\t\t},\n\t\t{ name: \"affected-task-filter\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition D: Quality gate (CI/CD)\n// ---------------------------------------------------------------------------\n\n/** A single lint error emitted by a CI tool. */\nexport interface LintError {\n\tfile: string;\n\tline: number;\n\tcol: number;\n\trule: string;\n\tmessage: string;\n}\n\n/** A single test failure emitted by a test runner. */\nexport interface TestFailure {\n\ttestId: string;\n\tfile: string;\n\tmessage: string;\n}\n\n/** Structured code-change / CI event. */\nexport interface CodeChange {\n\t/** Files touched by the change. */\n\tfiles: string[];\n\tlintErrors?: LintError[];\n\ttestFailures?: TestFailure[];\n}\n\n/** Options for {@link codeChangeBridge}. */\nexport interface CodeChangeBridgeOptions {\n\t/** Name for the effect node (default \"code-change-bridge\"). */\n\tname?: string;\n\t/** Default severity for generated IntakeItems (default \"high\"). */\n\tdefaultSeverity?: Severity;\n}\n\n/**\n * Intake bridge for code-change / CI events.\n *\n * Watches a source node for `CodeChange` events and publishes one\n * `IntakeItem` per lint error and per test failure to the intake topic.\n * Pass a custom `parser` to override the default mapping.\n *\n * @param source - Node emitting CodeChange events.\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param parser - Optional custom parser (overrides default).\n * @param opts - Optional configuration.\n */\nexport function codeChangeBridge(\n\tsource: Node<CodeChange>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\tparser?: (change: CodeChange) => IntakeItem[],\n\topts?: CodeChangeBridgeOptions,\n): Node<unknown> {\n\tconst defaultSeverity = opts?.defaultSeverity ?? \"high\";\n\n\tfunction defaultParser(change: CodeChange): IntakeItem[] {\n\t\tconst items: IntakeItem[] = [];\n\t\tfor (const err of change.lintErrors ?? []) {\n\t\t\titems.push({\n\t\t\t\tsource: \"code-change\",\n\t\t\t\tsummary: `Lint: ${err.rule} in ${err.file}:${err.line}`,\n\t\t\t\tevidence: err.message,\n\t\t\t\taffectsAreas: [err.file],\n\t\t\t\tseverity: defaultSeverity,\n\t\t\t});\n\t\t}\n\t\tfor (const fail of change.testFailures ?? []) {\n\t\t\titems.push({\n\t\t\t\tsource: \"test\",\n\t\t\t\tsummary: `Test failure: ${fail.testId}`,\n\t\t\t\tevidence: fail.message,\n\t\t\t\taffectsAreas: [fail.file],\n\t\t\t\taffectsEvalTasks: [fail.testId],\n\t\t\t\tseverity: defaultSeverity,\n\t\t\t});\n\t\t}\n\t\treturn items;\n\t}\n\n\tconst resolve = parser ?? defaultParser;\n\n\treturn effect(\n\t\t[source as Node<unknown>],\n\t\t([change]) => {\n\t\t\tif (change == null) return;\n\t\t\tfor (const item of resolve(change as CodeChange)) {\n\t\t\t\tintakeTopic.publish(item);\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"code-change-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Transport function for {@link notifyEffect}. Sync or async. */\nexport type NotifyTransport<T> = (item: T) => void | Promise<void>;\n\n/** Options for {@link notifyEffect}. */\nexport interface NotifyEffectOptions {\n\t/** Name for the effect node (default \"notify-effect\"). */\n\tname?: string;\n}\n\n/**\n * Effect node that sends each new topic entry to an external channel.\n *\n * The `transport` function is called for every item published to `topic`.\n * Async transports are bridged via `fromAny` (spec §5.10 compliant).\n *\n * Typical use: Slack webhook, GitHub PR comment, email notification, etc.\n * The factory provides reactive wiring; the transport supplies domain logic.\n *\n * ```ts\n * notifyEffect(alertQueue, async (item) => {\n * await fetch(SLACK_WEBHOOK, { method: 'POST', body: JSON.stringify({ text: item.summary }) });\n * });\n * ```\n *\n * @param topic - TopicGraph whose latest entry triggers the notification.\n * @param transport - Called with each new item. May return a Promise.\n * @param opts - Optional configuration.\n */\nexport function notifyEffect<T>(\n\ttopic: TopicGraph<T>,\n\ttransport: NotifyTransport<T>,\n\topts?: NotifyEffectOptions,\n): Node<unknown> {\n\treturn effect(\n\t\t[topic.latest as Node<unknown>],\n\t\t([item]) => {\n\t\t\tif (item == null) return;\n\t\t\t// transport is a side effect (webhook, Slack, email). Async transports\n\t\t\t// are fire-and-forget — the Promise result does not feed back into the\n\t\t\t// graph. Suppress unhandled-rejection noise by voiding the return.\n\t\t\tvoid transport(item as T);\n\t\t},\n\t\t{ name: opts?.name ?? \"notify-effect\" },\n\t);\n}\n","/**\n * Harness wiring types (roadmap §9.0).\n *\n * Shared types for the reactive collaboration loop: intake, triage, queue,\n * gate, execute, verify, reflect. These types are intentionally domain-agnostic\n * — the harness loop is not specific to eval workflows.\n *\n * @module\n */\n\n// ---------------------------------------------------------------------------\n// Intake\n// ---------------------------------------------------------------------------\n\n/** Sources that can produce intake items. */\nexport type IntakeSource = \"eval\" | \"test\" | \"human\" | \"code-change\" | \"hypothesis\" | \"parity\";\n\n/** Severity levels for intake items. */\nexport type Severity = \"critical\" | \"high\" | \"medium\" | \"low\";\n\n/** Root cause categories for triage classification. */\nexport type RootCause =\n\t| \"composition\"\n\t| \"missing-fn\"\n\t| \"bad-docs\"\n\t| \"schema-gap\"\n\t| \"regression\"\n\t| \"unknown\";\n\n/** Intervention types that address root causes. */\nexport type Intervention =\n\t| \"template\"\n\t| \"catalog-fn\"\n\t| \"docs\"\n\t| \"wrapper\"\n\t| \"schema-change\"\n\t| \"investigate\";\n\n/** Routing destinations after triage. */\nexport type QueueRoute = \"auto-fix\" | \"needs-decision\" | \"investigation\" | \"backlog\";\n\n/** Ordered queue route names for iteration. */\nexport const QUEUE_NAMES: readonly QueueRoute[] = [\n\t\"auto-fix\",\n\t\"needs-decision\",\n\t\"investigation\",\n\t\"backlog\",\n];\n\n/**\n * An item entering the harness loop via the INTAKE stage.\n *\n * All intake sources produce this uniform shape — the intake topic\n * doesn't care where items came from.\n */\nexport interface IntakeItem {\n\tsource: IntakeSource;\n\tsummary: string;\n\tevidence: string;\n\taffectsAreas: string[];\n\taffectsEvalTasks?: string[];\n\tseverity?: Severity;\n\trelatedTo?: string[];\n\t/** Item-carried reingestion count. Incremented on each full-loop reingestion. */\n\t_reingestions?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Triage output\n// ---------------------------------------------------------------------------\n\n/** Output of the TRIAGE stage — enriched intake item with classification. */\nexport interface TriagedItem extends IntakeItem {\n\trootCause: RootCause;\n\tintervention: Intervention;\n\troute: QueueRoute;\n\tpriority: number;\n\ttriageReasoning?: string;\n\t/** Item-carried retry count. Incremented on each fast-retry pass. */\n\t_retries?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Strategy model\n// ---------------------------------------------------------------------------\n\n/** Effectiveness record for a rootCause→intervention pair. */\nexport interface StrategyEntry {\n\trootCause: RootCause;\n\tintervention: Intervention;\n\tattempts: number;\n\tsuccesses: number;\n\tsuccessRate: number;\n}\n\n/** Key format: `${rootCause}→${intervention}`. */\nexport type StrategyKey = `${RootCause}→${Intervention}`;\n\nexport function strategyKey(rootCause: RootCause, intervention: Intervention): StrategyKey {\n\treturn `${rootCause}→${intervention}`;\n}\n\n// ---------------------------------------------------------------------------\n// Execution & verification\n// ---------------------------------------------------------------------------\n\n/** LLM output shape from the EXECUTE stage (partial — lacks `item`). */\nexport type ExecuteOutput = {\n\toutcome: \"success\" | \"failure\" | \"partial\";\n\tdetail: string;\n};\n\n/** Full execution result assembled downstream (LLM output + context). */\nexport interface ExecutionResult {\n\titem: TriagedItem;\n\toutcome: \"success\" | \"failure\" | \"partial\";\n\tdetail: string;\n}\n\n/** Whether an error is self-correctable (fast-retry) or structural (full loop). */\nexport type ErrorClass = \"self-correctable\" | \"structural\";\n\n/** Classifier for fast-retry path. */\nexport type ErrorClassifier = (result: ExecutionResult) => ErrorClass;\n\n/** Default error classifier: parse/config errors are self-correctable. */\nexport function defaultErrorClassifier(result: ExecutionResult): ErrorClass {\n\tconst d = result.detail.toLowerCase();\n\tif (\n\t\td.includes(\"parse\") ||\n\t\td.includes(\"json\") ||\n\t\td.includes(\"config\") ||\n\t\td.includes(\"validation\") ||\n\t\td.includes(\"syntax\")\n\t) {\n\t\treturn \"self-correctable\";\n\t}\n\treturn \"structural\";\n}\n\n// ---------------------------------------------------------------------------\n// Verification output\n// ---------------------------------------------------------------------------\n\n/** Result of the VERIFY stage. */\nexport interface VerifyResult {\n\titem: TriagedItem;\n\texecution: ExecutionResult;\n\tverified: boolean;\n\tfindings: string[];\n\terrorClass?: ErrorClass;\n}\n\n// ---------------------------------------------------------------------------\n// Priority scoring\n// ---------------------------------------------------------------------------\n\n/** Configurable signals for priority scoring. */\nexport interface PrioritySignals {\n\t/** Per-severity base weight (default: critical=100, high=70, medium=40, low=10). */\n\tseverityWeights?: Partial<Record<Severity, number>>;\n\t/** Decay rate per second for attention decay (default ~1.15e-6 ≈ 7-day half-life). */\n\tdecayRate?: number;\n\t/** Strategy model effectiveness boost threshold (default 0.7). */\n\teffectivenessThreshold?: number;\n\t/** Strategy model effectiveness boost amount (default 15). */\n\teffectivenessBoost?: number;\n}\n\n/** Default severity weights. */\nexport const DEFAULT_SEVERITY_WEIGHTS: Record<Severity, number> = {\n\tcritical: 100,\n\thigh: 70,\n\tmedium: 40,\n\tlow: 10,\n};\n\n/** Default decay rate: ~7-day half-life. */\nexport const DEFAULT_DECAY_RATE = Math.LN2 / (7 * 24 * 3600);\n\n// ---------------------------------------------------------------------------\n// Harness loop configuration\n// ---------------------------------------------------------------------------\n\n/** Per-queue configuration in the harness loop. */\nexport interface QueueConfig {\n\t/** Whether this queue is gated (requires human approval). */\n\tgated: boolean;\n\t/** Maximum pending items in the gate (default Infinity). */\n\tmaxPending?: number;\n\t/** Start the gate in open (auto-approve) mode? */\n\tstartOpen?: boolean;\n}\n\n/** Default queue configurations. */\nexport const DEFAULT_QUEUE_CONFIGS: Record<QueueRoute, QueueConfig> = {\n\t\"auto-fix\": { gated: false },\n\t\"needs-decision\": { gated: true },\n\tinvestigation: { gated: true },\n\tbacklog: { gated: false, startOpen: false },\n};\n\n/** Options for {@link harnessLoop}. */\nexport interface HarnessLoopOptions {\n\t/** LLM adapter for promptNode-based stages (triage, execute, verify, reflect). */\n\tadapter: unknown; // LLMAdapter — kept as unknown to avoid circular dep\n\n\t/** Custom triage prompt (receives IntakeItem + strategy model as context). */\n\ttriagePrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Custom execute prompt. */\n\texecutePrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Custom verify prompt. */\n\tverifyPrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Per-queue configuration overrides. */\n\tqueues?: Partial<Record<QueueRoute, QueueConfig>>;\n\n\t/** Priority scoring signals. */\n\tpriority?: PrioritySignals;\n\n\t/** Error classifier for fast-retry path. */\n\terrorClassifier?: ErrorClassifier;\n\n\t/** Max fast-retries per item before routing to full intake (default 2). */\n\tmaxRetries?: number;\n\n\t/** Global retry cap across all items — circuit breaker (default maxRetries × 10). */\n\tmaxTotalRetries?: number;\n\n\t/** Max re-ingestions from verify→intake before giving up (default 1). */\n\tmaxReingestions?: number;\n\n\t/** Global reingestion cap across all items — circuit breaker (default maxReingestions × 10). */\n\tmaxTotalReingestions?: number;\n\n\t/** Retained limit for topic logs (default 1000). */\n\tretainedLimit?: number;\n}\n","/**\n * Strategy model and priority scoring (roadmap §9.0).\n *\n * Pure-computation derived nodes — no LLM, no async.\n *\n * @module\n */\n\nimport { monotonicNs } from \"../../core/clock.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { derived } from \"../../core/sugar.js\";\nimport { reactiveMap } from \"../../extra/reactive-map.js\";\nimport { decay } from \"../memory.js\";\n\nimport {\n\tDEFAULT_DECAY_RATE,\n\tDEFAULT_SEVERITY_WEIGHTS,\n\ttype Intervention,\n\ttype PrioritySignals,\n\ttype RootCause,\n\ttype StrategyEntry,\n\ttype StrategyKey,\n\tstrategyKey,\n\ttype TriagedItem,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Strategy model\n// ---------------------------------------------------------------------------\n\n/** Snapshot shape for the strategy model node. */\nexport type StrategySnapshot = ReadonlyMap<StrategyKey, StrategyEntry>;\n\n/** Bundle returned by {@link strategyModel}. */\nexport interface StrategyModelBundle {\n\t/** Reactive node — current strategy map. */\n\treadonly node: Node<StrategySnapshot>;\n\n\t/** Record a completed issue (success or failure). */\n\trecord(rootCause: RootCause, intervention: Intervention, success: boolean): void;\n\n\t/** Look up effectiveness for a specific pair. */\n\tlookup(rootCause: RootCause, intervention: Intervention): StrategyEntry | undefined;\n\n\t/** Tear down internal keepalive subscriptions. */\n\tdispose(): void;\n}\n\n/**\n * Create a strategy model that tracks `rootCause × intervention → successRate`\n * over completed issues. Pure derived computation — no LLM.\n *\n * The model feeds back into TRIAGE for routing hints.\n */\nexport function strategyModel(): StrategyModelBundle {\n\tconst _map = reactiveMap<StrategyKey, StrategyEntry>({ name: \"strategy-entries\" });\n\n\t// Derived node that projects the reactive map into a plain Map snapshot.\n\tconst snapshot = derived<StrategySnapshot>(\n\t\t[_map.entries],\n\t\t([mapSnap]) => {\n\t\t\tconst raw = mapSnap as ReadonlyMap<StrategyKey, StrategyEntry>;\n\t\t\t// Return a fresh frozen copy so consumers see a stable reference.\n\t\t\treturn new Map(raw);\n\t\t},\n\t\t{\n\t\t\tname: \"strategy-model\",\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst am = a as StrategySnapshot;\n\t\t\t\tconst bm = b as StrategySnapshot;\n\t\t\t\tif (am.size !== bm.size) return false;\n\t\t\t\tfor (const [k, v] of am) {\n\t\t\t\t\tconst bv = bm.get(k);\n\t\t\t\t\tif (!bv || v.attempts !== bv.attempts || v.successes !== bv.successes) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\tfunction record(rootCause: RootCause, intervention: Intervention, success: boolean): void {\n\t\tconst key = strategyKey(rootCause, intervention);\n\t\tconst existing = _map.get(key);\n\t\tconst attempts = (existing?.attempts ?? 0) + 1;\n\t\tconst successes = (existing?.successes ?? 0) + (success ? 1 : 0);\n\t\t_map.set(key, {\n\t\t\trootCause,\n\t\t\tintervention,\n\t\t\tattempts,\n\t\t\tsuccesses,\n\t\t\tsuccessRate: successes / attempts,\n\t\t});\n\t}\n\n\tfunction lookup(rootCause: RootCause, intervention: Intervention): StrategyEntry | undefined {\n\t\treturn _map.get(strategyKey(rootCause, intervention));\n\t}\n\n\t// Keep the derived alive so get() works without an external subscriber.\n\tconst _unsub = snapshot.subscribe(() => {});\n\n\tfunction dispose(): void {\n\t\t_unsub();\n\t}\n\n\treturn { node: snapshot, record, lookup, dispose };\n}\n\n// ---------------------------------------------------------------------------\n// Priority scoring\n// ---------------------------------------------------------------------------\n\n/**\n * Create a priority scoring derived node for a single triaged item.\n *\n * Combines severity weight, attention decay, strategy model effectiveness,\n * and an optional external urgency signal.\n *\n * @param item - Node holding the triaged item.\n * @param strategy - Strategy model node.\n * @param lastInteractionNs - Node holding the monotonic timestamp (ns) of last human interaction.\n * @param urgency - Optional external urgency signal node (0–1 scale).\n * @param signals - Configurable scoring parameters.\n */\nexport function priorityScore(\n\titem: Node<TriagedItem>,\n\tstrategy: Node<StrategySnapshot>,\n\tlastInteractionNs: Node<number>,\n\turgency?: Node<number>,\n\tsignals?: PrioritySignals,\n): Node<number> {\n\tconst severityWeights = { ...DEFAULT_SEVERITY_WEIGHTS, ...signals?.severityWeights };\n\tconst decayRate = signals?.decayRate ?? DEFAULT_DECAY_RATE;\n\tconst effectivenessThreshold = signals?.effectivenessThreshold ?? 0.7;\n\tconst effectivenessBoost = signals?.effectivenessBoost ?? 15;\n\n\tconst deps: Node<unknown>[] = [item, strategy, lastInteractionNs];\n\tif (urgency) deps.push(urgency);\n\n\treturn derived<number>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst itm = values[0] as TriagedItem;\n\t\t\tconst strat = values[1] as StrategySnapshot;\n\t\t\tconst lastNs = values[2] as number;\n\t\t\tconst urg = urgency ? (values[3] as number) : 0;\n\n\t\t\t// Base score from severity\n\t\t\tconst baseWeight = severityWeights[itm.severity ?? \"medium\"];\n\t\t\tconst ageSeconds = (monotonicNs() - lastNs) / 1e9;\n\t\t\tlet score = decay(baseWeight, ageSeconds, decayRate, 0);\n\n\t\t\t// Strategy model boost\n\t\t\tconst key = strategyKey(itm.rootCause, itm.intervention);\n\t\t\tconst entry = strat.get(key);\n\t\t\tif (entry && entry.successRate >= effectivenessThreshold) {\n\t\t\t\tscore += effectivenessBoost;\n\t\t\t}\n\n\t\t\t// External urgency boost (0–1 scale → 0–20 points)\n\t\t\tscore += urg * 20;\n\n\t\t\treturn score;\n\t\t},\n\t\t{ name: \"priority-score\" },\n\t);\n}\n","/**\n * harnessLoop() factory (roadmap §9.0).\n *\n * Wires the static 7-stage topology: INTAKE → TRIAGE → QUEUE → GATE →\n * EXECUTE → VERIFY → REFLECT. Static topology, flowing data — the Kafka\n * insight applied to human+LLM collaboration.\n *\n * @module\n */\n\nimport type { Node } from \"../../core/node.js\";\nimport { node } from \"../../core/node.js\";\nimport { effect, state } from \"../../core/sugar.js\";\nimport { merge, withLatestFrom } from \"../../extra/operators.js\";\nimport { Graph } from \"../../graph/graph.js\";\nimport { trackingKey, tryIncrementBounded } from \"../_internal.js\";\nimport type { LLMAdapter } from \"../ai.js\";\nimport { promptNode } from \"../ai.js\";\nimport { TopicGraph } from \"../messaging.js\";\nimport { type GateController, gate } from \"../orchestration.js\";\nimport { type StrategyModelBundle, type StrategySnapshot, strategyModel } from \"./strategy.js\";\nimport {\n\tDEFAULT_QUEUE_CONFIGS,\n\tdefaultErrorClassifier,\n\ttype ErrorClass,\n\ttype ErrorClassifier,\n\ttype ExecuteOutput,\n\ttype ExecutionResult,\n\ttype HarnessLoopOptions,\n\ttype IntakeItem,\n\tQUEUE_NAMES,\n\ttype QueueConfig,\n\ttype QueueRoute,\n\ttype TriagedItem,\n\ttype VerifyResult,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Default prompts\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_TRIAGE_PROMPT = `You are a triage classifier for a reactive collaboration harness.\n\nGiven an intake item, classify it and output JSON:\n{\n \"rootCause\": \"composition\" | \"missing-fn\" | \"bad-docs\" | \"schema-gap\" | \"regression\" | \"unknown\",\n \"intervention\": \"template\" | \"catalog-fn\" | \"docs\" | \"wrapper\" | \"schema-change\" | \"investigate\",\n \"route\": \"auto-fix\" | \"needs-decision\" | \"investigation\" | \"backlog\",\n \"priority\": <number 0-100>,\n \"triageReasoning\": \"<one sentence>\"\n}\n\nStrategy model (past effectiveness):\n{{strategy}}\n\nIntake item:\n{{item}}`;\n\nconst DEFAULT_EXECUTE_PROMPT = `You are an implementation agent.\n\nGiven a triaged issue with root cause and intervention type, produce a fix.\n\nIssue:\n{{item}}\n\nOutput JSON:\n{\n \"outcome\": \"success\" | \"failure\" | \"partial\",\n \"detail\": \"<description of what was done or what failed>\"\n}`;\n\nconst DEFAULT_VERIFY_PROMPT = `You are a QA reviewer.\n\nGiven an execution result, verify whether the fix is correct.\n\nExecution:\n{{execution}}\n\nOriginal issue:\n{{item}}\n\nOutput JSON:\n{\n \"verified\": true/false,\n \"findings\": [\"<finding1>\", ...],\n \"errorClass\": \"self-correctable\" | \"structural\" // only if verified=false\n}`;\n\n// ---------------------------------------------------------------------------\n// HarnessGraph\n// ---------------------------------------------------------------------------\n\n/** The graph returned by {@link harnessLoop}. */\nexport class HarnessGraph extends Graph {\n\t/** Intake topic — publish items here to enter the loop. */\n\treadonly intake: TopicGraph<IntakeItem>;\n\n\t/** Per-route queue topics. */\n\treadonly queues: ReadonlyMap<QueueRoute, TopicGraph<TriagedItem>>;\n\n\t/** Per-route gate controllers (only for gated queues). */\n\treadonly gates: ReadonlyMap<QueueRoute, GateController<TriagedItem>>;\n\n\t/** Strategy model bundle — record outcomes, lookup effectiveness. */\n\treadonly strategy: StrategyModelBundle;\n\n\t/** Verify results topic — subscribe to see verification outcomes. */\n\treadonly verifyResults: TopicGraph<VerifyResult>;\n\n\t/** Global retry count across all items (circuit breaker). Reactive — subscribable. */\n\treadonly totalRetries: Node<number>;\n\n\t/** Global reingestion count across all items (circuit breaker). Reactive — subscribable. */\n\treadonly totalReingestions: Node<number>;\n\n\tconstructor(\n\t\tname: string,\n\t\tintake: TopicGraph<IntakeItem>,\n\t\tqueues: Map<QueueRoute, TopicGraph<TriagedItem>>,\n\t\tgates: Map<QueueRoute, GateController<TriagedItem>>,\n\t\tstrategy: StrategyModelBundle,\n\t\tverifyResults: TopicGraph<VerifyResult>,\n\t\ttotalRetries: Node<number>,\n\t\ttotalReingestions: Node<number>,\n\t) {\n\t\tsuper(name);\n\t\tthis.intake = intake;\n\t\tthis.queues = queues;\n\t\tthis.gates = gates;\n\t\tthis.strategy = strategy;\n\t\tthis.verifyResults = verifyResults;\n\t\tthis.totalRetries = totalRetries;\n\t\tthis.totalReingestions = totalReingestions;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// harnessLoop factory\n// ---------------------------------------------------------------------------\n\n/**\n * Wire the reactive collaboration loop as a static-topology graph.\n *\n * The loop has 7 stages:\n * 1. **INTAKE** — items arrive from multiple sources via `intake.publish()`\n * 2. **TRIAGE** — promptNode classifies, routes, and prioritizes\n * 3. **QUEUE** — 4 priority-ordered TopicGraphs (auto-fix, needs-decision, investigation, backlog)\n * 4. **GATE** — human approval on configurable queues\n * 5. **EXECUTE** — promptNode or human implements the fix\n * 6. **VERIFY** — promptNode reviews + optional fast-retry\n * 7. **REFLECT** — strategy model records outcomes\n *\n * @param name - Graph name.\n * @param opts - Configuration.\n * @returns HarnessGraph with controller accessors.\n */\nexport function harnessLoop(name: string, opts: HarnessLoopOptions): HarnessGraph {\n\tconst adapter = opts.adapter as LLMAdapter;\n\tconst maxRetries = opts.maxRetries ?? 2;\n\tconst retainedLimit = opts.retainedLimit ?? 1000;\n\tconst errorClassifier: ErrorClassifier = opts.errorClassifier ?? defaultErrorClassifier;\n\n\t// Merge queue configs with defaults\n\tconst queueConfigs = new Map<QueueRoute, QueueConfig>();\n\tfor (const route of QUEUE_NAMES) {\n\t\tqueueConfigs.set(route, {\n\t\t\t...DEFAULT_QUEUE_CONFIGS[route],\n\t\t\t...opts.queues?.[route],\n\t\t});\n\t}\n\n\t// --- Stage 1: INTAKE ---\n\tconst intake = new TopicGraph<IntakeItem>(\"intake\", { retainedLimit });\n\n\t// --- Strategy model (used by triage + reflect) ---\n\tconst strategy = strategyModel();\n\n\t// --- Stage 2: TRIAGE ---\n\t// Strategy context uses withLatestFrom: intake.latest is the reactive trigger,\n\t// strategy.node is sampled without being a trigger. This breaks the feedback\n\t// cycle (verify → strategy.record() → strategy.node) reactively — strategy\n\t// changes don't re-fire triage, only new intake items do.\n\tconst triageInput = withLatestFrom(\n\t\tintake.latest as Node<unknown>,\n\t\tstrategy.node as Node<unknown>,\n\t);\n\n\tconst triageNode = promptNode<TriagedItem>(\n\t\tadapter,\n\t\t[triageInput as Node<unknown>],\n\t\topts.triagePrompt ??\n\t\t\t((pair: unknown) => {\n\t\t\t\tconst [item, strat] = pair as [unknown, StrategySnapshot];\n\t\t\t\t// Empty text → promptNode's SENTINEL gate skips the LLM call.\n\t\t\t\tif (!item) return \"\";\n\t\t\t\treturn DEFAULT_TRIAGE_PROMPT.replace(\n\t\t\t\t\t\"{{strategy}}\",\n\t\t\t\t\tJSON.stringify(Array.from(strat.entries())),\n\t\t\t\t).replace(\"{{item}}\", JSON.stringify(item));\n\t\t\t}),\n\t\t{\n\t\t\tname: \"triage\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Stage 3: QUEUE ---\n\tconst queueTopics = new Map<QueueRoute, TopicGraph<TriagedItem>>();\n\tfor (const route of QUEUE_NAMES) {\n\t\tqueueTopics.set(route, new TopicGraph<TriagedItem>(`queue/${route}`, { retainedLimit }));\n\t}\n\n\t// Router: merge intake fields into triage classification before routing to queue.\n\t// The LLM only returns {rootCause, intervention, route, priority} — the router\n\t// pairs it with the original intake item (summary, evidence, etc.).\n\t// Sample triageInput (not intake.latest) — triageInput holds the [item, strategy]\n\t// pair that *triggered* this specific triage, so we get the correct item even if\n\t// a newer intake item has arrived since. triageNode triggers; triageInput sampled.\n\tconst routerInput = withLatestFrom(triageNode as Node<unknown>, triageInput as Node<unknown>);\n\tconst router = effect([routerInput as Node<unknown>], ([pair]) => {\n\t\tif (pair == null) return;\n\t\tconst [classification, triagePair] = pair as [\n\t\t\tTriagedItem | null,\n\t\t\t[IntakeItem | null, StrategySnapshot] | null,\n\t\t];\n\t\tif (!classification || !classification.route) return;\n\t\tconst intakeItem = triagePair?.[0];\n\t\tconst merged: TriagedItem = { ...intakeItem, ...classification };\n\t\tconst topic = queueTopics.get(merged.route);\n\t\tif (topic) topic.publish(merged);\n\t});\n\tconst routerUnsub = router.subscribe(() => {});\n\n\t// --- Stage 4: GATE ---\n\t// Create a container graph for gates (gate() requires a Graph to register nodes in)\n\tconst gateGraph = new Graph(\"gates\");\n\tconst gateControllers = new Map<QueueRoute, GateController<TriagedItem>>();\n\n\tfor (const route of QUEUE_NAMES) {\n\t\tconst config = queueConfigs.get(route)!;\n\t\tconst topic = queueTopics.get(route)!;\n\n\t\tif (config.gated) {\n\t\t\t// Register the topic's latest node in the gate graph so gate() can resolve it\n\t\t\tgateGraph.add(`${route}/source`, topic.latest as Node<unknown>);\n\t\t\tconst ctrl = gate<TriagedItem>(gateGraph, `${route}/gate`, `${route}/source`, {\n\t\t\t\tmaxPending: config.maxPending,\n\t\t\t\tstartOpen: config.startOpen,\n\t\t\t});\n\t\t\tgateControllers.set(route, ctrl);\n\t\t}\n\t}\n\n\t// --- Stage 5: EXECUTE ---\n\t// Merge all gate outputs + ungated queue latests + retry feedback into a\n\t// single execute input using the merge() operator (no imperative .down()).\n\tconst retryTopic = new TopicGraph<TriagedItem>(\"retry-input\", { retainedLimit });\n\n\tconst queueOutputs: Node<TriagedItem | null>[] = [];\n\tfor (const route of QUEUE_NAMES) {\n\t\tconst config = queueConfigs.get(route)!;\n\t\tif (config.gated && gateControllers.has(route)) {\n\t\t\tqueueOutputs.push(gateControllers.get(route)!.node as Node<TriagedItem | null>);\n\t\t} else {\n\t\t\tqueueOutputs.push(queueTopics.get(route)!.latest as Node<TriagedItem | null>);\n\t\t}\n\t}\n\tqueueOutputs.push(retryTopic.latest as Node<TriagedItem | null>);\n\n\tconst executeInput = merge<TriagedItem | null>(...queueOutputs);\n\n\tconst executeNode = promptNode<ExecuteOutput>(\n\t\tadapter,\n\t\t[executeInput as Node<unknown>],\n\t\topts.executePrompt ??\n\t\t\t((item: unknown) => DEFAULT_EXECUTE_PROMPT.replace(\"{{item}}\", JSON.stringify(item))),\n\t\t{\n\t\t\tname: \"execute\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Execute context: [execOutput, item] captured once per execute-wave ---\n\t//\n\t// executeInput feeds into executeNode (dep) AND later into verifyNode (dep).\n\t// Without this node, verifyNode would fire twice per wave in the retry path:\n\t// once when executeNode settles (with stale item from prevData), and once when\n\t// executeInput delivers the retry item directly. The second fire would pair the\n\t// correct item with a verify output that was computed using the wrong item.\n\t//\n\t// withLatestFrom(executeNode, executeInput) fires exactly once per execute-wave:\n\t// executeInput notifies executeNode first (depth-first), executeNode runs fn and\n\t// settles in executeContextNode.dep[0], then executeInput settles in dep[1].\n\t// dirtyDepCount reaches 0 only after both settle → fn runs once with correct data.\n\tconst executeContextNode = withLatestFrom(\n\t\texecuteNode as Node<unknown>,\n\t\texecuteInput as Node<unknown>,\n\t);\n\n\t// --- Stage 6: VERIFY ---\n\tconst verifyResults = new TopicGraph<VerifyResult>(\"verify-results\", { retainedLimit });\n\n\t// The LLM returns only {verified, findings, errorClass?}. We type the promptNode\n\t// output as the partial shape and assemble the full VerifyResult downstream.\n\ttype VerifyOutput = { verified: boolean; findings: string[]; errorClass?: ErrorClass };\n\n\t// verifyNode depends on executeContextNode ([execOutput, item]) — single dep.\n\t// This ensures verifyNode fires once per execute-wave with the correct item.\n\tconst verifyNode = promptNode<VerifyOutput>(\n\t\tadapter,\n\t\t[executeContextNode as Node<unknown>],\n\t\topts.verifyPrompt ??\n\t\t\t((ctxPair: unknown) => {\n\t\t\t\tconst [execution, item] = ctxPair as [ExecuteOutput | null, unknown];\n\t\t\t\treturn DEFAULT_VERIFY_PROMPT.replace(\"{{execution}}\", JSON.stringify(execution)).replace(\n\t\t\t\t\t\"{{item}}\",\n\t\t\t\t\tJSON.stringify(item),\n\t\t\t\t);\n\t\t\t}),\n\t\t{\n\t\t\tname: \"verify\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Fast-retry path ---\n\t// verifyContext = withLatestFrom(verifyNode, executeContextNode):\n\t// [verifyOutput, [execOutput, item]]\n\t// Fires once when verifyNode settles; executeContextNode is sampled as secondary.\n\tconst verifyContext = withLatestFrom(\n\t\tverifyNode as Node<unknown>,\n\t\texecuteContextNode as Node<unknown>,\n\t);\n\n\tconst maxReingestions = opts.maxReingestions ?? 1;\n\tconst maxTotalRetries = Math.min(opts.maxTotalRetries ?? maxRetries * 10, 100);\n\tconst maxTotalReingestions = Math.min(opts.maxTotalReingestions ?? maxReingestions * 10, 100);\n\tconst totalRetries = state(0);\n\tconst totalReingestions = state(0);\n\n\t// Uses shared `tryIncrementBounded` (patterns/_internal.ts) — documented\n\t// P3 exception for self-owned counters read+written from a single call\n\t// site (`fastRetry` effect below).\n\n\t// Use raw node() so we can check batchData[0] directly — effect() falls back\n\t// to ctx.prevData[0] when verifyContext emits RESOLVED (secondary-only wave),\n\t// which would re-fire with stale context and create phantom retries.\n\tconst fastRetry = node([verifyContext as Node<unknown>], (batchData, _actions) => {\n\t\tconst batch = batchData[0];\n\t\tif (batch == null || batch.length === 0) return; // RESOLVED or not involved — skip\n\t\tconst ctxVal = batch[batch.length - 1];\n\t\tif (ctxVal == null) return;\n\t\t// verifyContext shape: [verifyOutput, [execOutput, item]]\n\t\tconst [vo, execCtx] = ctxVal as [\n\t\t\tVerifyOutput | null,\n\t\t\t[ExecuteOutput | null, TriagedItem | null] | null,\n\t\t];\n\t\tconst [execRaw, item] = execCtx ?? [null, null];\n\t\tif (!vo || !item) return;\n\n\t\t// Assemble full ExecutionResult + VerifyResult from LLM outputs + context\n\t\tconst exec: ExecutionResult = {\n\t\t\titem,\n\t\t\toutcome: execRaw?.outcome ?? \"failure\",\n\t\t\tdetail: execRaw?.detail ?? \"unknown\",\n\t\t};\n\t\tconst vr: VerifyResult = {\n\t\t\titem,\n\t\t\texecution: exec,\n\t\t\tverified: vo.verified,\n\t\t\tfindings: vo.findings ?? [],\n\t\t\terrorClass: vo.errorClass,\n\t\t};\n\n\t\tif (vr.verified) {\n\t\t\tstrategy.record(item.rootCause, item.intervention, true);\n\t\t\tverifyResults.publish(vr);\n\t\t\treturn;\n\t\t}\n\n\t\t// Failed verification\n\t\tconst errClass =\n\t\t\tvr.errorClass ??\n\t\t\terrorClassifier({\n\t\t\t\titem,\n\t\t\t\toutcome: \"failure\",\n\t\t\t\tdetail: vr.findings.join(\"; \"),\n\t\t\t});\n\n\t\tconst itemRetries = item._retries ?? 0;\n\n\t\tif (\n\t\t\terrClass === \"self-correctable\" &&\n\t\t\titemRetries < maxRetries &&\n\t\t\ttryIncrementBounded(totalRetries, maxTotalRetries)\n\t\t) {\n\t\t\tconst key = trackingKey(item);\n\t\t\tconst retryItem: TriagedItem = {\n\t\t\t\t...item,\n\t\t\t\t_retries: itemRetries + 1,\n\t\t\t\tsummary: `[RETRY ${itemRetries + 1}/${maxRetries}] ${key} — Previous attempt failed: ${vr.findings.join(\"; \")}`,\n\t\t\t\trelatedTo: [key],\n\t\t\t};\n\t\t\tretryTopic.publish(retryItem);\n\t\t} else {\n\t\t\t// Structural failure or max retries exceeded → full loop via INTAKE\n\t\t\tstrategy.record(item.rootCause, item.intervention, false);\n\t\t\tverifyResults.publish(vr);\n\n\t\t\tconst key = trackingKey(item);\n\t\t\tconst itemReingestions = item._reingestions ?? 0;\n\t\t\tif (\n\t\t\t\titemReingestions < maxReingestions &&\n\t\t\t\ttryIncrementBounded(totalReingestions, maxTotalReingestions)\n\t\t\t) {\n\t\t\t\tintake.publish({\n\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\tsummary: `Verification failed for: ${key}`,\n\t\t\t\t\tevidence: vr.findings.join(\"\\n\"),\n\t\t\t\t\taffectsAreas: item.affectsAreas,\n\t\t\t\t\taffectsEvalTasks: item.affectsEvalTasks,\n\t\t\t\t\tseverity: \"high\",\n\t\t\t\t\trelatedTo: [key],\n\t\t\t\t\t_reingestions: itemReingestions + 1,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\n\tconst fastRetryUnsub = fastRetry.subscribe(() => {}); // keepalive (COMPOSITION-GUIDE §1)\n\n\t// --- Stage 7: REFLECT ---\n\t// Strategy model is already updated in the fast-retry/verify effect above.\n\t// Hypothesis generation and memory distillation are pluggable extensions\n\t// wired externally via verifyResults topic subscription — not hardcoded here.\n\n\t// --- Assemble HarnessGraph ---\n\tconst harness = new HarnessGraph(\n\t\tname,\n\t\tintake,\n\t\tqueueTopics,\n\t\tgateControllers,\n\t\tstrategy,\n\t\tverifyResults,\n\t\ttotalRetries,\n\t\ttotalReingestions,\n\t);\n\n\t// Register disposers for unregistered internal nodes (D1/D2 fix)\n\tharness.addDisposer(routerUnsub);\n\tharness.addDisposer(fastRetryUnsub);\n\tharness.addDisposer(strategy.dispose);\n\n\t// Register stage nodes for introspection (harnessTrace, describe, observe)\n\tharness.add(\"triage\", triageNode as Node<unknown>);\n\tharness.add(\"execute\", executeNode as Node<unknown>);\n\tharness.add(\"verify\", verifyNode as Node<unknown>);\n\tharness.add(\"strategy\", strategy.node as Node<unknown>);\n\n\t// Mount subgraphs\n\tharness.mount(\"intake\", intake);\n\tfor (const [route, topic] of queueTopics) {\n\t\tharness.mount(`queue/${route}`, topic);\n\t}\n\tharness.mount(\"gates\", gateGraph);\n\tharness.mount(\"retry-input\", retryTopic);\n\tharness.mount(\"verify-results\", verifyResults);\n\n\treturn harness;\n}\n","/**\n * Harness-specific graph profiling (roadmap §9.0).\n *\n * Extends {@link graphProfile} with harness domain counters:\n * queue depths, strategy entries, retry/reingestion tracker sizes.\n *\n * @module\n */\n\nimport {\n\ttype GraphProfileOptions,\n\ttype GraphProfileResult,\n\tgraphProfile,\n} from \"../../graph/profile.js\";\nimport type { HarnessGraph } from \"./loop.js\";\nimport type { QueueRoute } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Harness-specific profile extending the base graph profile. */\nexport interface HarnessProfileResult extends GraphProfileResult {\n\t/** Per-queue retained item counts. */\n\tqueueDepths: Record<QueueRoute, number>;\n\t/** Number of rootCause→intervention entries in the strategy model. */\n\tstrategyEntries: number;\n\t/** Global retry count across all items. */\n\ttotalRetries: number;\n\t/** Global reingestion count across all items. */\n\ttotalReingestions: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Profile a harness graph with domain-specific counters.\n *\n * @param harness - The HarnessGraph to profile.\n * @param opts - Optional base profile options.\n * @returns Harness profile with queue depths, strategy stats, and tracker sizes.\n */\nexport function harnessProfile(\n\tharness: HarnessGraph,\n\topts?: GraphProfileOptions,\n): HarnessProfileResult {\n\tconst base = graphProfile(harness, opts);\n\n\tconst queueDepths: Record<string, number> = {};\n\tfor (const [route, topic] of harness.queues) {\n\t\tqueueDepths[route] = topic.retained().length;\n\t}\n\n\treturn {\n\t\t...base,\n\t\tqueueDepths: queueDepths as Record<QueueRoute, number>,\n\t\tstrategyEntries: harness.strategy.node.cache?.size ?? 0,\n\t\ttotalRetries: harness.totalRetries.cache ?? 0,\n\t\ttotalReingestions: harness.totalReingestions.cache ?? 0,\n\t};\n}\n","/**\n * Harness pipeline trace (roadmap §9.0 — Inspection Tool Consolidation).\n *\n * Attaches reactive observers (via `observe()`) to all harness stages.\n * One call gives full pipeline visibility with stage labels and elapsed\n * timestamps relative to the `harnessTrace()` invocation time.\n *\n * Supports two output modes:\n * - **String logger** (default): rendered lines to `console.log` or a custom sink.\n * - **Structured events**: programmatic `TraceEvent[]` list for test assertions\n * and tooling. Access via `handle.events`.\n *\n * Supports configurable detail levels (`\"summary\"`, `\"standard\"`, `\"full\"`)\n * to control output verbosity without composing different tool calls.\n *\n * @module\n */\n\nimport { monotonicNs } from \"../../core/clock.js\";\nimport type { ObserveResult } from \"../../graph/graph.js\";\nimport type { HarnessGraph } from \"./loop.js\";\nimport { QUEUE_NAMES } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Event type captured by structured trace. */\nexport type TraceEventType = \"data\" | \"error\" | \"complete\";\n\n/** A single structured trace event. */\nexport interface TraceEvent {\n\t/** Elapsed seconds since trace was created. */\n\telapsed: number;\n\t/** Pipeline stage label (INTAKE, TRIAGE, QUEUE, GATE, EXECUTE, VERIFY, STRATEGY). */\n\tstage: string;\n\t/** Event type. */\n\ttype: TraceEventType;\n\t/** Data payload (present for \"data\" and \"error\" events). Omitted at \"summary\" detail. */\n\tdata?: unknown;\n\t/** Human-readable summary of the data. Present at \"standard\" and \"full\" detail. */\n\tsummary?: string;\n}\n\n/** Detail level for trace output. */\nexport type TraceDetail =\n\t/** Stage + elapsed only. No data preview. Lowest overhead. */\n\t| \"summary\"\n\t/** Stage + elapsed + truncated data preview. Default. */\n\t| \"standard\"\n\t/** Stage + elapsed + full raw data. Use for debugging, not production. */\n\t| \"full\";\n\n/** Handle returned by {@link harnessTrace}. Call `dispose()` to stop tracing. */\nexport interface HarnessTraceHandle {\n\t/** Stop tracing and detach all observers. Safe to call multiple times. */\n\tdispose(): void;\n\t/**\n\t * Structured trace events collected since creation. Plain array — no\n\t * subscription needed (COMPOSITION-GUIDE §1: avoid lazy-activation\n\t * friction for inspection tools). Populated reactively via observe().\n\t */\n\treadonly events: readonly TraceEvent[];\n}\n\n/** Options for {@link harnessTrace}. */\nexport interface HarnessTraceOptions {\n\t/** Sink for rendered trace lines. Default: `console.log`. */\n\tlogger?: (line: string) => void;\n\t/** Detail level for both string and structured output. Default: `\"summary\"`. */\n\tdetail?: TraceDetail;\n}\n\n// ---------------------------------------------------------------------------\n// Stage labels\n// ---------------------------------------------------------------------------\n\n/** Observe paths → stage labels for the 7 harness stages. */\nconst STAGE_LABELS: Record<string, string> = {\n\t\"intake::latest\": \"INTAKE\",\n\ttriage: \"TRIAGE\",\n\texecute: \"EXECUTE\",\n\t\"verify-results::latest\": \"VERIFY\",\n\tstrategy: \"STRATEGY\",\n};\n\nfor (const route of QUEUE_NAMES) {\n\tSTAGE_LABELS[`queue/${route}::latest`] = \"QUEUE\";\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Attach reactive trace observers to all harness pipeline stages.\n *\n * Wires `graph.observe(path, { format: \"json\" })` to each stage node,\n * intercepting the logger callback to emit stage-labeled lines with\n * elapsed timestamps. Surfaces DATA, ERROR, and COMPLETE events.\n *\n * **Structured events:** Every trace event is also pushed to\n * `handle.events` — a plain array (not a reactive node) that tests and\n * tooling can inspect programmatically. To use structured events alone\n * without string output, pass `{ logger: null }`.\n *\n * **Detail levels:**\n * - `\"summary\"` — stage + elapsed only. Minimal overhead.\n * - `\"standard\"` (default) — stage + elapsed + truncated data preview.\n * - `\"full\"` — stage + elapsed + full raw data object in events.\n *\n * Elapsed timestamps are relative to the `harnessTrace()` invocation time,\n * not the first event.\n *\n * @param harness - The HarnessGraph to trace.\n * @param opts - Optional configuration.\n * @returns Handle with `dispose()` to stop tracing and `events` for structured access.\n */\nexport function harnessTrace(\n\tharness: HarnessGraph,\n\topts?: HarnessTraceOptions,\n): HarnessTraceHandle {\n\tconst logger = opts?.logger ?? console.log;\n\tconst detail: TraceDetail = opts?.detail ?? \"summary\";\n\tconst startNs = monotonicNs();\n\tconst observations: ObserveResult[] = [];\n\tconst events: TraceEvent[] = [];\n\n\tfunction elapsedSecs(): number {\n\t\treturn (monotonicNs() - startNs) / 1e9;\n\t}\n\n\tfunction elapsedStr(): string {\n\t\treturn elapsedSecs().toFixed(3);\n\t}\n\n\tfunction recordEvent(stage: string, type: TraceEventType, rawData: unknown): void {\n\t\tconst e = elapsedSecs();\n\t\tconst ev: TraceEvent = { elapsed: e, stage, type };\n\n\t\tif (detail !== \"summary\") {\n\t\t\tev.summary = summarize(rawData);\n\t\t}\n\t\tif (detail === \"full\") {\n\t\t\tev.data = rawData;\n\t\t}\n\n\t\tevents.push(ev);\n\t}\n\n\tfunction wireStage(path: string, stage: string): void {\n\t\ttry {\n\t\t\tconst obs = harness.observe(path, {\n\t\t\t\tformat: \"json\",\n\t\t\t\tlogger: (_line, event) => {\n\t\t\t\t\tif (event.type === \"data\") {\n\t\t\t\t\t\trecordEvent(stage, \"data\", event.data);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tif (detail === \"summary\") {\n\t\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ←`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst dataStr = event.data !== undefined ? ` ${summarize(event.data)}` : \"\";\n\t\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ←${dataStr}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\t\trecordEvent(stage, \"error\", event.data);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tconst errStr = event.data !== undefined ? ` ${summarize(event.data)}` : \"\";\n\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ✗${errStr}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.type === \"complete\") {\n\t\t\t\t\t\trecordEvent(stage, \"complete\", undefined);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ■ complete`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tincludeTypes: [\"data\", \"error\", \"complete\"],\n\t\t\t});\n\t\t\tobservations.push(obs);\n\t\t} catch {\n\t\t\t// Node may not exist (e.g., queue route not mounted) — skip silently\n\t\t}\n\t}\n\n\t// Wire stage nodes (COMPOSITION-GUIDE §5: sinks before sources)\n\tfor (const [path, stage] of Object.entries(STAGE_LABELS)) {\n\t\twireStage(path, stage);\n\t}\n\n\t// Wire gate outputs per gated queue\n\tfor (const [gatedRoute] of harness.gates) {\n\t\twireStage(`gates::${gatedRoute}/gate`, \"GATE\");\n\t}\n\n\treturn {\n\t\tget events(): readonly TraceEvent[] {\n\t\t\treturn events;\n\t\t},\n\t\tdispose() {\n\t\t\tfor (const obs of observations) obs.dispose();\n\t\t\tobservations.length = 0;\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction summarize(value: unknown): string {\n\tif (value == null) return \"null\";\n\tif (typeof value === \"string\") return truncate(value, 80);\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (typeof value === \"bigint\") return String(value);\n\ttry {\n\t\tconst json = JSON.stringify(value);\n\t\treturn truncate(json, 120);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction truncate(s: string, max: number): string {\n\treturn s.length > max ? `${s.slice(0, max - 1)}…` : s;\n}\n","/**\n * GraphRefly — public API surface.\n */\nexport const version = \"0.0.0\";\n\nexport * from \"./compat/index.js\";\nexport * as compat from \"./compat/index.js\";\n// Named re-exports enable finer-grained tree-shaking for consumers.\nexport * from \"./core/index.js\";\n// Keep namespace exports for ergonomic grouped imports.\nexport * as core from \"./core/index.js\";\nexport * from \"./extra/index.js\";\nexport * as extra from \"./extra/index.js\";\nexport * from \"./graph/index.js\";\nexport * as graph from \"./graph/index.js\";\nexport * from \"./patterns/index.js\";\nexport * as pat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AAY,OAAO,UAAU,UAAW,QAAO,OAAO,KAAK;AAChF,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK;AAClD,MAAI;AACH,UAAM,OAAO,KAAK,UAAU,KAAK;AACjC,WAAO,SAAS,MAAM,GAAG;AAAA,EAC1B,QAAQ;AACP,WAAO,OAAO,KAAK;AAAA,EACpB;AACD;AAEA,SAAS,SAAS,GAAW,KAAqB;AACjD,SAAO,EAAE,SAAS,MAAM,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC,WAAM;AACrD;;;AC/NO,IAAM,UAAU;","names":["initial","atom","map","node","map","pull","atom","node","pull","useStore","useSubscribe","useSubscribeRecord","useSubscribe","node","useStore","useSubscribeRecord","useStore","useSubscribe","useSubscribeRecord","useSubscribe","node","useStore","useSubscribeRecord","useStore","useSubscribe","useSubscribeRecord","computed","useSubscribe","node","useStore","computed","useSubscribeRecord","node","policy","out","forEach","valve","batch","valve","forEach","filter","interval","node","baseMeta","buffer","baseMeta","policy","node","_","VALID_NODE_TYPES","stripFences","feedback","DEFAULT_DECAY_RATE","evalSource","task","trigger","topic","DEFAULT_DECAY_RATE","DEFAULT_DECAY_RATE","topic","batch","topic"]}
|